SpringMVC + Apache POI 实现WEB中Excel下载功能

项目中需要将web页面中的报表导出成Excel,在网上搜寻了写资料,实现了相关功能,如图1所示:


项目后台架构采用的是SpringMVC+Spring+Mybatis,通过引入Apache POI实现excel的下载功能。
导出效果如图2所示:

首先页面中点击“导出Excel”按钮就会触发如下js代码:
[javascript] view plain copy
print ?
  1. function getXls()  
  2. {  
  3.     var selectVal = dijit.byId(‘DRSSelectFacId’).get(‘value’);  
  4.     var beginTimeVal = dijit.byId(‘DRSBeginTime’).get(‘displayedValue’);  
  5.     var endTimeVal = dijit.byId(‘DRSEndTime’).get(‘displayedValue’);    
  6.       
  7.     var url = “report/getDRSExcel.do?”+“fac_id=”+selectVal+“&beginTime=”+beginTimeVal+“&endTime=”+endTimeVal;  
  8.     window.open(url,”_self”);  
  9. }  
这段js代码的主要功能是将选择条件返回给后台,请求相应的数据并生成excel。
jsp相关代码如下:
  1. <div style=“margin-top:10px;”>  
  2.     <label for=“DRSSelectFacId”>选择电场:</label><span id=“DRSSelectFacId” ></span>      
  3.     <label for=“DRSBeginTime”>起始日期:</label><span id=“DRSBeginTime” ></span>      
  4.     <label for=“DRSEndTime”>截止日期:</label><span id=“DRSEndTime” ></span>      
  5.        <span id=“DRSbutton1” ></span>      
  6.        <span id=“DRSbutton2” ></span>  
  7. </div>  


下面是JAVA后台控制层代码:
  1. @RequestMapping(value = “/report/getDRSExcel.do”)  
  2. public void getDRSExcel(  
  3.         @RequestParam(value = “fac_id”, required = true) String fac_id,  
  4.         @RequestParam(value = “beginTime”, required = true) String beginTime,  
  5.         @RequestParam(value = “endTime”, required = true) String endTime,  
  6.         HttpServletRequest request, HttpServletResponse response)  
  7. {  
  8.     logger.info(”/report/getDRSExcel.do?fac_id=” + fac_id + “&beginTime=”  
  9.             + beginTime + ”&endTime=” + endTime);  
  10.        try {  
  11.         this.daliyRepShortService.getXls(fac_id,beginTime,endTime,request,response);  
  12.     } catch (ParseException e) {  
  13.         e.printStackTrace();  
  14.     }  
  15.    }  
这里调用了业务层代码如下:
  1. private List<Map<String, Object>> createExcelRecord(List<Fc_dailyreport> projects) {  
  2.     List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();  
  3.     Map<String, Object> map = new HashMap<String, Object>();  
  4.     map.put(”sheetName”“短期预测日报”);  
  5.     listmap.add(map);  
  6.     Fc_dailyreport project=null;  
  7.       
  8.     SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);  
  9.     DecimalFormat fnum = new DecimalFormat(“##0.0000”);   
  10.     for (int j = 0; j < projects.size(); j++) {  
  11.         project=projects.get(j);  
  12.         Map<String, Object> mapValue = new HashMap<String, Object>();  
  13.         mapValue.put(”dtime”, sdf.format(project.getDtime()));  
  14.         mapValue.put(”cap”, project.getCap());  
  15.         mapValue.put(”p”, project.getP());  
  16.         mapValue.put(”fore_p”, project.getFore_p());  
  17.         mapValue.put(”rmse”, fnum.format(project.getRmse()*100)+“%”);  
  18.         mapValue.put(”mae”, fnum.format(project.getMae()*100)+“%”);  
  19.         mapValue.put(”qualified_rate”, project.getQualified_rate()+“%”);  
  20.         mapValue.put(”colrel”, project.getColrel());  
  21.         mapValue.put(”uploadrate”, project.getUploadrate()+“%”);  
  22.         mapValue.put(”qxuploadrate”, project.getQxuploadrate()+“%”);  
  23.         listmap.add(mapValue);  
  24.     }  
  25.     return listmap;  
  26. }  
  27.   
  28. public void getXls(String fac_id,String beginTime,String endTime,HttpServletRequest request, HttpServletResponse response)   
  29.         throws ParseException  
  30. {  
  31.     String fileName=”短期预测日报”;  
  32.     //1.   
  33.     List<Fc_dailyreport> projects = getXlsData(fac_id,beginTime,endTime);  
  34.     //2.  
  35.     List<Map<String,Object>> list=createExcelRecord(projects);  
  36.     //3.  
  37.     String columnNames[]={”时间”,“容量(MW)”,“实际功率(MW)”,“预测功率(MW)”,“均方误差(%)”,“平均绝对误差(%)”,“合格率(%)”,“相关系数”,“上传率(%)”,“气象上传率(%)”};//列名  
  38.     String keys[]   =    {”dtime”,“cap”,“p”,“fore_p”,“rmse”,“mae”,“qualified_rate”,“colrel”,“uploadrate”,“qxuploadrate”};//map中的key  
  39.     //4.  
  40.     ExcelUtil.ExcelSingleOutputStream(list,keys,columnNames,fileName,request,response);  
  41. }  
在getXls方法中, getXlsData(fac_id,beginTime,endTime);主要是根据前端的查询条件参数获取所要的数据,这里采用的是mybatis实现,由于本文的主旨是与excel相关的,这里就不说明mybatis如何实现数据的获取。
第二步是创建excel的数据,如方法 createExcelRecord(projects);所示。list中第一项的 sheetName用来命名Excel中的sheet。剩余list中的数据数excel中的没一行的数据。在getXls方法中的columnNames对应excel的第一行的列名,可参考图2. keys与createExcelRecord中的相关名字一一对应(这里也与DAO值的pojo类的属性名字一一对应)。
接下来就需要了解 ExcelUtil.ExcelSingleOutputStream(list,keys,columnNames,fileName,request,response);这一段代码是做什么的了。
首选看类ExcelUtil:
  1. package com.shr.util;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.ByteArrayInputStream;  
  6. import java.io.ByteArrayOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.UnsupportedEncodingException;  
  10. import java.util.List;  
  11. import java.util.Map;  
  12.   
  13. import javax.servlet.ServletOutputStream;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16.   
  17. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  18. import org.apache.poi.ss.usermodel.Cell;  
  19. import org.apache.poi.ss.usermodel.CellStyle;  
  20. import org.apache.poi.ss.usermodel.Font;  
  21. import org.apache.poi.ss.usermodel.IndexedColors;  
  22. import org.apache.poi.ss.usermodel.Row;  
  23. import org.apache.poi.ss.usermodel.Sheet;  
  24. import org.apache.poi.ss.usermodel.Workbook;  
  25.   
  26. public class ExcelUtil {  
  27.   
  28.     public static Workbook createSingleWorkBook(List<Map<String, Object>> list,String []keys,String columnNames[]) {  
  29.         Workbook wb = new HSSFWorkbook();  
  30.         Sheet sheet = wb.createSheet(list.get(0).get(“sheetName”).toString());  
  31.         for(int i=0;i<keys.length;i++)  
  32.         {  
  33.             sheet.setColumnWidth((short) i, (short) (35.7 * 150));  
  34.         }  
  35.   
  36.         Row row = sheet.createRow((short0);  
  37.   
  38.         CellStyle cs = wb.createCellStyle();  
  39.         CellStyle cs2 = wb.createCellStyle();  
  40.   
  41.         Font f = wb.createFont();  
  42.         Font f2 = wb.createFont();  
  43.   
  44.         f.setFontHeightInPoints((short10);  
  45.         f.setColor(IndexedColors.BLACK.getIndex());  
  46.         f.setBoldweight(Font.BOLDWEIGHT_BOLD);  
  47.   
  48.         f2.setFontHeightInPoints((short10);  
  49.         f2.setColor(IndexedColors.BLACK.getIndex());  
  50.   
  51.         cs.setFont(f);  
  52.         cs.setFillForegroundColor(IndexedColors.AQUA.getIndex());  
  53.         cs.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  54.         cs.setBorderLeft(CellStyle.BORDER_THIN);  
  55.         cs.setBorderRight(CellStyle.BORDER_THIN);  
  56.         cs.setBorderTop(CellStyle.BORDER_THIN);  
  57.         cs.setBorderBottom(CellStyle.BORDER_THIN);  
  58.         cs.setAlignment(CellStyle.ALIGN_CENTER);  
  59.   
  60.         cs2.setFont(f2);  
  61.         cs2.setBorderLeft(CellStyle.BORDER_THIN);  
  62.         cs2.setBorderRight(CellStyle.BORDER_THIN);  
  63.         cs2.setBorderTop(CellStyle.BORDER_THIN);  
  64.         cs2.setBorderBottom(CellStyle.BORDER_THIN);  
  65.         cs2.setAlignment(CellStyle.ALIGN_CENTER);  
  66.         for(int i=0;i<columnNames.length;i++){  
  67.             Cell cell = row.createCell(i);  
  68.             cell.setCellValue(columnNames[i]);  
  69.             cell.setCellStyle(cs);  
  70.         }  
  71.         for (short i = 1; i < list.size(); i++) {  
  72.             Row row1 = sheet.createRow((short) i);  
  73.             for(short j=0;j<keys.length;j++){  
  74.                 Cell cell = row1.createCell(j);  
  75.                 cell.setCellValue(list.get(i).get(keys[j]) == null?“ ”: list.get(i).get(keys[j]).toString());  
  76.                 cell.setCellStyle(cs2);  
  77.             }  
  78.         }  
  79.         return wb;  
  80.     }  
  81.       
  82.     public static void ExcelSingleOutputStream(List<Map<String, Object>> list,String []keys,String columnNames[],  
  83.             String fileName, HttpServletRequest request, HttpServletResponse response)  
  84.     {  
  85.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  86.         try {  
  87.             createSingleWorkBook(list,keys,columnNames).write(os);  
  88.         } catch (IOException e2) {  
  89.             e2.printStackTrace();  
  90.         }  
  91.         ExcelOutputStream(fileName,request,response,os);  
  92.     }  
  93.       
  94.     private static void ExcelOutputStream( String fileName, HttpServletRequest request, HttpServletResponse response,ByteArrayOutputStream os)  
  95.     {  
  96.         byte[] content = os.toByteArray();  
  97.         InputStream is = new ByteArrayInputStream(content);  
  98.           
  99.         response.reset();  
  100.         response.setContentType(”application/vnd.ms-excel;charset=utf-8”);  
  101.         try {  
  102.             response.setHeader(”Content-Disposition”“attachment;filename=”new String((fileName + “.xls”).getBytes(), “iso-8859-1”));  
  103.         } catch (UnsupportedEncodingException e1) {  
  104.             e1.printStackTrace();  
  105.         }  
  106.         ServletOutputStream out = null;  
  107.         try {  
  108.             out = response.getOutputStream();  
  109.         } catch (IOException e1) {  
  110.             e1.printStackTrace();  
  111.         }  
  112.         BufferedInputStream bis = null;  
  113.         BufferedOutputStream bos = null;  
  114.   
  115.         try {  
  116.             bis = new BufferedInputStream(is);  
  117.             bos = new BufferedOutputStream(out);  
  118.             byte[] buff = new byte[2048];  
  119.             int bytesRead;  
  120.             while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
  121.                 bos.write(buff, 0, bytesRead);  
  122.             }  
  123.         } catch ( IOException e) {  
  124.             e.printStackTrace();  
  125.         } finally {  
  126.             if (bis != null)  
  127.                 try {  
  128.                     bis.close();  
  129.                 } catch (IOException e) {  
  130.                     e.printStackTrace();  
  131.                 }  
  132.             if (bos != null)  
  133.                 try {  
  134.                     bos.close();  
  135.                 } catch (IOException e) {  
  136.                     e.printStackTrace();  
  137.                 }  
  138.         }  
  139.     }  
  140. }  

这里的createSingleWorkBook方法用来根据业务层中的相关数据生成的excel,这时候生成的excel是驻留在内存中的,所以需要其输出,请参照方法ExcelSingleOutputStream和ExcelOutputStream(这里将一个方法拆分成两个是因为原项目中还有其他的情况考虑,本文只罗列出一种相对简单的情况,所以这样不要差异,可以将这两个方法看成一个也无妨,主要是向页面输出这个生成的Excel。









  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值