关于使用模板来做这个情况一般很少用,除非是样式很复杂的才借用模板,正好我就遇到了这中情况
下面就教大家如何使用模块来做导出,有兴趣的同学可以加个联系方式,很高兴与大家切磋技术上的问题!(联系方式最下方)
1.首先提供工具类
/** * tempPath 模板文件路径 * path 文件路径 * list 集合数据 */ public void exportExcel(String tempPath, String path, HttpServletResponse response, List<MarketScoreVO> marketScores) { // 读取excel模板,并复制到新文件中供写入和下载 File newFile = createNewFile(tempPath, path); InputStream is = null; XSSFSheet sheet; try { // 将excel文件转为输入流 is = new FileInputStream(newFile); // 创建个workbook, XSSFWorkbook workbook = new XSSFWorkbook(is); XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setBorderBottom(BorderStyle.THIN); //下边框 cellStyle.setBorderLeft(BorderStyle.THIN);//左边框 cellStyle.setBorderTop(BorderStyle.THIN);//上边框 cellStyle.setBorderRight(BorderStyle.THIN);//右边框 // 获取第一个sheet sheet = workbook.getSheetAt(0); // 写数据 FileOutputStream fos = new FileOutputStream(newFile); XSSFRow row = sheet.getRow(0); for (int i = 0; i < marketScores.size(); i++) { //根据excel模板格式写入数据.... MarketScoreVO scores = marketScores.get(i); //从第六行开始 row = sheet.createRow(i + 5); row.setHeightInPoints(30); XSSFCell cell = row.createCell(0); cell.setCellStyle(cellStyle); cell.setCellValue(i + 1); XSSFCell cell1 = row.createCell(1); cell1.setCellStyle(cellStyle); cell1.setCellValue(scores.getDeptName()); XSSFCell cell2 = row.createCell(2); cell2.setCellStyle(cellStyle); cell2.setCellValue(scores.getTestBatchScore()); XSSFCell cell3 = row.createCell(3); cell3.setCellStyle(cellStyle); cell3.setCellValue(scores.getTestProjectScore()); ....... } workbook.write(fos); fos.flush(); fos.close(); // 下载 InputStream fis = new BufferedInputStream(new FileInputStream(newFile)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.setContentType("text/html;charset=UTF-8"); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/x-msdownload"); String newName = URLEncoder.encode("文件名" + System.currentTimeMillis() + ".xlsx", "UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=\"" + newName + "\""); response.addHeader("Content-Length", "" + newFile.length()); toClient.write(buffer); toClient.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (Exception e) { e.printStackTrace(); } } // 删除创建的新文件 this.deleteFile(newFile); } /** * 读取excel模板,并复制到新文件中供写入和下载 * * @return */ private File createNewFile(String tempPath, String rPath) { // 读取模板,并赋值到新文件 File file = new File(tempPath); // rPath: 新的文件名 String newFileName = System.currentTimeMillis() + ".xlsx"; // 判断路径是否存在 File dir = new File(rPath); if (!dir.exists()) { dir.mkdirs(); } // 写入到新的excel File newFile = new File(rPath, newFileName); try { newFile.createNewFile(); // 复制模板到新文件 fileChannelCopy(file, newFile); } catch (Exception e) { e.printStackTrace(); } return newFile; } /** * 复制文件 * * @param s 源文件 * @param t 复制到的新文件 */ private void fileChannelCopy(File s, File t) { try { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(s),1024); out = new BufferedOutputStream(new FileOutputStream(t),1024); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } finally { if (null != in) { in.close(); } if (null != out) { out.close(); } } } catch (Exception e) { e.printStackTrace(); } } /** * 下载成功后删除 * * @param files */ private void deleteFile(File... files) { for (File file : files) { if (file.exists()) { file.delete(); } } }
2.控制层如下
/** * 根据模板导出Excel * @param ruleDTO */ @GetMapping("/export") public void ExportResult(RuleDTO ruleDTO, HttpServletRequest request, HttpServletResponse response){ String tempPath = this.getClass().getClassLoader().getResource("static/template/marketScore.xlsx").getFile(); String path = getClass().getClassLoader().getResource("static/template/").getPath(); List<MarketScoreVO> marketScores = marketScoresService.getMarketScores(ruleDTO); ExcelUtils excelUtils = new ExcelUtils(); excelUtils.exportExcel(tempPath,path,response,marketScores);
好了,照此方法就可以导出了.........
下面是重点:
当你点击导出的时候,会报如下错误 java.util.zip.ZipException: invalid stored block lengths
为什么会这样呢 ?原因是:一个源文件是被压缩,一个是没有被压缩 因为你从resource下面获取的路径是在target下面所以默认被压缩了
遇到此问题首先冷静思考,调试看错误 然后在上百度,如下提供了解决方法
在pom文件中 添加如下依赖:
<plugin> <groupId>org.apache.maven.plugins</groupId> <version>2.6</version> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>UTF-8</encoding> <nonFilteredFileExtensions> <nonFilteredFileExtension>xlsx</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin>
官网原话:To prevent corrupting your binary files when filtering is enabled, you can configure a list of file extensions that will not be filtered.
好了到这里基本都已解决了
QQ:154688593