poi百万级数据导出excel

来源:互联网 发布:淘宝盖楼有什么技巧 编辑:程序博客网 时间:2024/06/05 17:20
通过传入实体类数组和指定导出列来即可,导出excel,读者可直接复制到项目直接使用,下面只是个简单的示例提供参考

一、导出excel工具类代码
  1. /**
  2. * 导出实体类
  3. * @param head 表头
  4. * @param exportColumn 导出字段
  5. * @param exportList 实体数组
  6. * @param clazz 实体类
  7. * @return
  8. * @throws Exception
  9. */
  10. public SXSSFWorkbook export(String[] head,String[] exportColumn,List exportList,Class clazz) throws Exception{
  11. XSSFWorkbook wb = new XSSFWorkbook ();
  12. SXSSFWorkbook swb=new SXSSFWorkbook(wb,1000);
  13. //swb.createSheet()
  14. //创建第一个sheet(页),命名为 new sheet
  15. SXSSFSheet sheet = null;
  16. sheet = (SXSSFSheet) swb.createSheet("myData");
  17. //创建head
  18. SXSSFRow heqadrow = sheet.createRow(0);
  19. int headlen = head.length;
  20. for(int i=0;i<headlen;i++) {
  21. heqadrow.createCell(i).setCellValue(head[i]);
  22. }
  23. //获取导出列
  24. List<String> columnNameList = new ArrayList<String>();
  25. if(exportColumn!=null&&exportColumn.length>0) {
  26. int columnNameLen = exportColumn.length;
  27. for(int i=0;i<columnNameLen;i++){
  28. columnNameList.add(exportColumn[i]);
  29. }
  30. } else {//通过反射获取所有列
  31. //暂未实现
  32. System.err.println("请指明导出列");
  33. }
  34. //导出列
  35. int exportListLen = exportList.size();
  36. List<Method> methodList = new ArrayList<Method>();
  37. int columnNameListLen = columnNameList.size();
  38. for(int i=0;i<columnNameListLen;i++){
  39. String methodName= "get".concat(captureName(columnNameList.get(i).toLowerCase()));
  40. Method method = clazz.getMethod(methodName);
  41. methodList.add(method);
  42. }
  43. for(int i=1;i<=exportListLen;i++){
  44. Object entity = exportList.get(i-1);
  45. SXSSFRow row = sheet.createRow(i);
  46. for(int j=0;j<columnNameListLen;j++) {
  47. Object value = methodList.get(j).invoke(entity);
  48. if(value!=null) {
  49. row.createCell(j).setCellValue(value.toString());
  50. }
  51. }
  52. }
  53. //写入文件
  54. /*FileOutputStream fos = new FileOutputStream("e:\\txt.xls");
  55. swb.write(fos);
  56. fos.flush();*/
  57. return swb;
  58. }
二、导出excel的controller下载部分
  1. SXSSFWorkbook wb = eu.export(head, exportColumn, easyJson.getRows(), TReportyszxqk.class);
  2. OutputStream output=response.getOutputStream(); //response为springMVC传入的httpservletResponse
  3. response.reset();
  4. response.setHeader("Content-disposition", "attachment; filename=details.xls");
  5. response.setContentType("application/msexcel");
  6. wb.write(output);
  7. output.close();
三、前端下载部分
1.html
  1. <form action="exportYszx" style="display:none" id="downForm" method="post">
  2. </form>
  1. <button id="btn_export"> 导出</button>
2.js
  1. $("#btn_export").click(function(){
  2. $("#downForm").empty();
  3. for(var key in searchData){
  4. var input = "<input name='"+key+"'value='"+searchData[key]+"'>";
  5. $("#downForm").append(input)
  6. }
  7. $("#downForm").submit();
  8. })