谷歌浏览器导出excel失败问题解决

2 篇文章 1 订阅
1 篇文章 0 订阅

问题描述:

  java poi 操作excel ,浏览器提交表单下载导出excel, 用火狐可以正常导出,用chrome一直无响应。

解决经过:

度娘了一堆答案,得到 靠谱的方案是需要设置response的Content-Length来解决,但是无法通过 excel的Workbook获取 length,于是又参照了 https://qieyi28.iteye.com/blog/2274852 的提示,先生成临时文件,再 file.length() 塞到 response的Content-Length里,最终解决。

 

以下是参照的文章原文(避免原作者删除,我还是copy一份)

 

 第一步:导入poi   jar包。因为是使用maven ,如下方式引入jar

Xml代码 

 收藏代码

  1. <dependency>  
  2.  <groupId>org.apache.poi</groupId>  
  3.  <artifactId>poi</artifactId>  
  4.  <version>3.13</version>  
  5. </dependency>  

    第二步:jsp页面使用from表单请求

Html代码 

 收藏代码

  1. <form id="form_stock" action="${contextPath}/stock/toExportExcel">  
  2. ...............  
  3.   
  4. </form>  

    第三步:设计controller

Java代码 

 收藏代码

  1. @RequestMapping("toExportExcel")  
  2. public void exportExcel(StockExt stockExt,HttpServletRequest request, HttpServletResponse response) {  
  3.     List<Stock> list = stockService.queryList(stockExt);  
  4.     String[] rowsName = new String[] {"序号","货号","品名","规格","颜色","单位","批号","库存量","仓库","库位","单类型","所属客户","入库时间","实际库存量"};    
  5.     List<Object[]> dataList = new ArrayList<Object[]>();  
  6.     for (int i = 0; i < list.size(); i++) {  
  7.         Object[] objs = new Object[rowsName.length];// 创建13个数组长度  
  8.         StockVo sto = listVo.get(i);  
  9.         objs[0] = i;  
  10.         objs[1] = sto.getCargoNum();// 货号  
  11.         objs[2] = sto.getCargoName();// 品名  
  12.         objs[3] = sto.getCargoSpecifications();// 规格  
  13.         objs[4] = sto.getCargoColor();// 颜色  
  14.         objs[5] = sto.getUnitsName();// 单位  
  15.         objs[6] = TimeUtil.getTime(sto.getManufactureDate(), "yyyyMMdd");// 批号  
  16.         objs[7] = sto.getStockAmount();  
  17.         objs[8] = sto.getStorageName();// 仓库  
  18.         objs[9] = sto.getDepotName();// 库位  
  19.         objs[10] = (sto.getIsLoss() == 1) ? "库存单" : "报损单";  
  20.         objs[11] = sto.getNickName();// 所属客户  
  21.         objs[12] = sto.getModifyDate();  
  22.         objs[13] = "";// 留给仓管员导出人员任意填写  
  23.         dataList.add(objs);  
  24.     }  
  25.       
  26.     String fileName = "库存单";  
  27.     //执行导出  
  28.     ExportExcel.exportExcel(request,response,fileName, rowsName, dataList, "yyyy-MM-dd HH:mm:ss");  
  29. }  

 上面代码中,我们只要生成exportExcel方法里对应的3个参数就可以了,这个根据你代码灵活配置。

 

第四步:实现exportExcel方法

 

Java代码 

 收藏代码

  1. package com.honsend.common.jsp.poi;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.FileOutputStream;  
  9. import java.io.IOException;  
  10. import java.io.InputStream;  
  11. import java.io.OutputStream;  
  12. import java.net.URLEncoder;  
  13. import java.text.SimpleDateFormat;  
  14. import java.util.Date;  
  15. import java.util.Iterator;  
  16. import java.util.List;  
  17.   
  18. import javax.servlet.http.HttpServletRequest;  
  19. import javax.servlet.http.HttpServletResponse;  
  20.   
  21. import org.apache.poi.hssf.usermodel.HSSFCell;  
  22. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  23. import org.apache.poi.hssf.usermodel.HSSFFont;  
  24. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  25. import org.apache.poi.hssf.usermodel.HSSFRow;  
  26. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  27. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  28. import org.apache.poi.hssf.util.HSSFColor;  
  29.   
  30. import com.honsend.common.NumberUtil;  
  31. import com.honsend.common.TimeUtil;  
  32.   
  33. /** 
  34.  * 利用开源组件POI3.13动态导出EXCEL文档 
  35.  *  
  36.  * @version v1.0 
  37.  * @param  
  38.  *  */  
  39. public class ExportExcel {  
  40.     public static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator");  
  41.       
  42.     /** 
  43.      * 这是一个通用的方法 
  44.      * @param fileName 文件名 
  45.      * @param headers  表格属性列名数组 
  46.      * @param dataset  需要显示的数据集合 
  47.          * @param pattern 如果有时间数据,设定输出格式。默认为"yyy-MM-dd" 
  48.      */  
  49.     @SuppressWarnings("deprecation")  
  50.     public static HSSFWorkbook exportExcel(HttpServletRequest request,HttpServletResponse response,String fileName, String[] headers, List<Object[]> dataset,  String pattern) {  
  51.         String docsPath = request.getSession().getServletContext().getRealPath("docs");//docs文件夹目录  
  52.         String filePath = docsPath + FILE_SEPARATOR + fileName+"-任意名.xls";  
  53.         // 声明一个工作薄  
  54.         HSSFWorkbook workbook = new HSSFWorkbook();  
  55.         // 生成一个表格  
  56.         HSSFSheet sheet = workbook.createSheet("Excel");  
  57.         // 设置表格默认列宽度为15个字节  
  58.         //sheet.setDefaultColumnWidth((short) 15);  
  59.         // 生成一个表格标题行样式  
  60.         HSSFCellStyle style = getColumnTopStyle(workbook);  
  61.         // 生成非标题样式  
  62.         HSSFCellStyle style2 = getColumnStyle(workbook);  
  63.         // 产生表格标题行  
  64.         HSSFRow row = sheet.createRow(0);  
  65.         for (short i = 0; i < headers.length; i++) {  
  66.             HSSFCell cell = row.createCell(i);  
  67.             cell.setCellStyle(style);  
  68.             HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
  69.             cell.setCellValue(text);  
  70.         }  
  71.         // 遍历集合数据,产生数据行  
  72.         Iterator<Object[]> it = dataset.iterator();  
  73.         int index = 0;  
  74.         while (it.hasNext()) {  
  75.             index++;  
  76.             row = sheet.createRow(index);//从第1行开始创建  
  77.             Object[] obj = (Object[]) it.next();  
  78.             for (short i = 0; i < obj.length; i++) {  
  79.                 HSSFCell cell = row.createCell(i);  
  80.                 cell.setCellStyle(style2);  
  81.                 Object value = obj[i];  
  82.                 String textValue = null;  
  83.                 if (!"".equals(value) && value != null) {  
  84.                     if (value instanceof Integer) {  
  85.                         int intValue = (Integer) value;  
  86.                         cell.setCellValue(intValue);  
  87.                     } else if (value instanceof Float) {  
  88.                         float fValue = (Float) value;  
  89.                         cell.setCellValue(fValue);  
  90.                     } else if (value instanceof Double) {  
  91.                         double dValue = (Double) value;  
  92.                         cell.setCellValue(dValue);  
  93.                     } else if (value instanceof Long) {  
  94.                         long longValue = (Long) value;  
  95.                         cell.setCellValue(longValue);  
  96.                     } else if (value instanceof Date) {  
  97.                         Date date = (Date) value;  
  98.                         if(null==pattern||pattern.equals("")){  
  99.                             pattern="yyyy-MM-dd";  
  100.                         }  
  101.                         SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
  102.                         textValue = sdf.format(date);  
  103.                         cell.setCellValue(textValue);  
  104.                     } else {  
  105.                         // 其它数据类型都当作字符串简单处理  
  106.                         textValue = value.toString();  
  107.                         cell.setCellValue(textValue); // 设置单元格的值  
  108.                     }  
  109.                 } else {  
  110.                     cell.setCellValue("");  
  111.                 }  
  112.             }  
  113.         }  
  114.           
  115.         //让列宽随着导出的列长自动适应    
  116.         for (int colNum = 0; colNum < headers.length; colNum++) {  
  117.             int columnWidth = sheet.getColumnWidth(colNum) / 256;  
  118.             for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {  
  119.                 HSSFRow currentRow;  
  120.                 // 当前行未被使用过  
  121.                 if (sheet.getRow(rowNum) == null) {  
  122.                     currentRow = sheet.createRow(rowNum);  
  123.                 } else {  
  124.                     currentRow = sheet.getRow(rowNum);  
  125.                 }  
  126.                 if (currentRow.getCell(colNum) != null) {  
  127.                     HSSFCell currentCell = currentRow.getCell(colNum);  
  128.                     if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {  
  129.                         int length = currentCell.getStringCellValue() != null  
  130.                                 ? currentCell.getStringCellValue().getBytes().length : 10;  
  131.                         if (columnWidth < length) {  
  132.                             columnWidth = length;  
  133.                         }  
  134.                     }  
  135.                 }  
  136.             }  
  137.             if (colNum == 0) {  
  138.                 sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);  
  139.             } else {  
  140.                 sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);  
  141.             }  
  142.         }  
  143.         try {  
  144.             if (createDir(docsPath)) {  
  145.                 OutputStream out = new FileOutputStream(filePath);  
  146.                 workbook.write(out);  
  147.                 out.close();  
  148.                 download(filePath, response);// 执行下载  
  149.                 cleanFile(filePath);// 删除已完成下载的文件  
  150.             }  
  151.         }  catch (FileNotFoundException e) {  
  152.             e.printStackTrace();  
  153.         }catch (IOException e) {  
  154.             e.printStackTrace();  
  155.         }  
  156.         return workbook;  
  157.     }     
  158.       
  159.     /** 
  160.      * 导出下载,弹出下载框 
  161.      * @param path  文件下载路径 
  162.      * @param response 
  163.      */  
  164.     public static void download(String path, HttpServletResponse response) {  
  165.         try {  
  166.             // path是指欲下载的文件的路径。  
  167.             File file = new File(path);  
  168.             // 取得文件名。  
  169.             String filename = file.getName();  
  170.             // 以流的形式下载文件。  
  171.             InputStream fis = new BufferedInputStream(new FileInputStream(path));  
  172.             byte[] buffer = new byte[fis.available()];  
  173.             fis.read(buffer);  
  174.             fis.close();  
  175.             // 清空response  
  176.             response.reset();  
  177.             // 设置response的Header  
  178.             response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8"));  
  179.             response.addHeader("Content-Length", "" + file.length());  
  180.             OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
  181.             response.setContentType("application/vnd.ms-excel;charset=gb2312");  
  182.             toClient.write(buffer);  
  183.             toClient.flush();  
  184.             toClient.close();  
  185.         } catch (IOException ex) {  
  186.             ex.printStackTrace();  
  187.         }  
  188.     }  
  189.        /** 
  190.    
  191.         * 清除文件 
  192.    
  193.         * @param filePath  文件路径 
  194.    
  195.         */  
  196.     public static  void cleanFile(String docsPath) {  
  197.         File file = new File(docsPath);  
  198.         file.delete();  
  199.     }  
  200.       
  201.     /* 
  202.      * 列头单元格样式 
  203.      */  
  204.     public static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {  
  205.         // 设置样式;  
  206.         HSSFCellStyle style = workbook.createCellStyle();  
  207.         // 设置底边框;  
  208.         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  209.         // 设置底边框颜色;  
  210.         style.setBottomBorderColor(HSSFColor.BLACK.index);  
  211.         // 设置左边框;  
  212.         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  213.         // 设置左边框颜色;  
  214.         style.setLeftBorderColor(HSSFColor.BLACK.index);  
  215.         // 设置右边框;  
  216.         style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  217.         // 设置右边框颜色;  
  218.         style.setRightBorderColor(HSSFColor.BLACK.index);  
  219.         // 设置顶边框;  
  220.         style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  221.         // 设置顶边框颜色;  
  222.         style.setTopBorderColor(HSSFColor.BLACK.index);  
  223.         // 设置自动换行;  
  224.         style.setWrapText(false);  
  225.         // 设置水平对齐的样式为居中对齐;  
  226.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  227.         // 设置垂直对齐的样式为居中对齐;  
  228.         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  229.   
  230.         // 设置字体  
  231.         HSSFFont font = workbook.createFont();  
  232.         // 设置字体颜色  
  233.         font.setColor(HSSFColor.VIOLET.index);  
  234.         // 设置字体大小  
  235.         font.setFontHeightInPoints((short) 12);  
  236.         // 字体加粗  
  237.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  238.         // 设置字体名字  
  239.         font.setFontName("Courier New");  
  240.         // 在样式用应用设置的字体;  
  241.         style.setFont(font);  
  242.           
  243.         return style;  
  244.     }  
  245.   
  246.     /* 
  247.      * 列数据信息单元格样式 
  248.      */  
  249.     public static HSSFCellStyle getColumnStyle(HSSFWorkbook workbook) {  
  250.         // 设置样式;  
  251.         HSSFCellStyle style = workbook.createCellStyle();  
  252.         // 设置底边框;  
  253.         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  254.         // 设置底边框颜色;  
  255.         style.setBottomBorderColor(HSSFColor.BLACK.index);  
  256.         // 设置左边框;  
  257.         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  258.         // 设置左边框颜色;  
  259.         style.setLeftBorderColor(HSSFColor.BLACK.index);  
  260.         // 设置右边框;  
  261.         style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  262.         // 设置右边框颜色;  
  263.         style.setRightBorderColor(HSSFColor.BLACK.index);  
  264.         // 设置顶边框;  
  265.         style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  266.         // 设置顶边框颜色;  
  267.         style.setTopBorderColor(HSSFColor.BLACK.index);  
  268.         // 设置自动换行;  
  269.         style.setWrapText(false);  
  270.         // 设置水平对齐的样式为居中对齐;  
  271.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  272.         // 设置垂直对齐的样式为居中对齐;  
  273.         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  274.   
  275.         // 设置字体  
  276.         HSSFFont font = workbook.createFont();  
  277.         // 设置字体大小  
  278.         font.setFontHeightInPoints((short) 10);  
  279.         font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
  280.         // 设置字体名字  
  281.         font.setFontName("Courier New");  
  282.         // 在样式用应用设置的字体;  
  283.         style.setFont(font);  
  284.   
  285.         return style;  
  286.     }  
  287.     /** 
  288.      * 创建目录 
  289.      * @param destDirName 
  290.      * @return  true 存在目录  false 不存在目录 
  291.      */  
  292.     public static boolean createDir(String destDirName) {  
  293.         File dir = new File(destDirName);  
  294.         if (dir.exists()) {  
  295.             return true;  
  296.         }  
  297.         if (!destDirName.endsWith(File.separator)) {  
  298.             destDirName = destDirName + File.separator;  
  299.         }  
  300.         // 创建目录  
  301.         if (dir.mkdirs()) {  
  302.             System.out.println("创建目录" + destDirName + "成功!");  
  303.             return true;  
  304.         } else {  
  305.             System.out.println("创建目录" + destDirName + "失败!");  
  306.             return false;  
  307.         }  
  308.     }  
  309. }  

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大宝大宝吃饱睡好

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值