-
导入相关依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.0.0</version> </dependency>
-
controller层
public void download(HttpServletResponse response, HttpServletRequest request){ //定义文件名,需带上后缀名 String filename = "xxx.xls"; //定义工作表名 String sheetName = "xxx"; //定义工作表标题 String title = "xxx"; //创建excel文件 HSSFWorkbook workBook = new HSSFWorkbook(); //新建一个sheet表 HSSFSheet sheet = workBook.createSheet(sheetName); //创建第一行,下标从0开始 HSSFRow row_one = sheet.createRow(0); //创建第一个单元格 HSSFCell cell_one = row_one.createCell(0); //合并第一行的两个单元格,并为单元格设置内容 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1)); cell_one.setCellValue(title); //新建第二行,并给第二行设置内容 HSSFRow row_two = sheet.createRow(1); row_two.createCell(0).setCellValue("xxx"); row_two.createCell(1).setCellValue("xxx"); response.setContentType("application/ms_excel;charset=UTF-8"); response.setHeader("content-Disposition", "attachment;filename="+processFileName(request, filename)); try { OutputStream out = response.getOutputStream(); workBook.write(out); } catch (IOException e) { e.printStackTrace(); } } // IE chrom Firefox文件中文乱码问题 public String processFileName(HttpServletRequest request, String fileNames){ String codedFileName = null; try{ String agent = request.getHeader("USER-AGENT"); if(agent != null && agent.indexOf("MSIE")!= -1 || agent != null && agent.indexOf("Trident")!= -1 ){ String name = java.net.URLEncoder.encode(fileNames ,"UTF-8"); codedFileName = name; } else if(agent != null && agent.indexOf("Mozilla")!= -1){ codedFileName = new String(fileNames.getBytes("UTF-8"),"iso-8859-1"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return codedFileName; }
在SSM项目中下载(导出)excel表格
最新推荐文章于 2022-01-15 09:23:21 发布