1:需要准备的依赖项
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<!--poi对excel2007以上版本的支持-->
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
2:具体实现
public void download(HttpServletRequest request , HttpServletResponse response) throws IOException { String fileName = "template/init_meter1.xls"; //这个是xls模板,这个是Springboot项目中对应的resources的地址 Resource ClassPathResource = new ClassPathResource(fileName); //这个Resource是用于读取 OutputStream out = null; Workbook wb = new hssfWorkbook(ClassPathResource.getInputStream());//hssfWorkbook是用于xls的操作 Sheet sheet = wb.getSheet(wb.getSheetName(0)); //获取表格中sheet 的名字 int row = 1; Row row1 = null; row1 = sheet.getRow(row); if (row1 == null) { row1 = sheet.createRow(row); } Cell cell1 = row1.getCell(0); //获取到对应的单元格列 if (cell1 == null) { cell1 = row1.createCell(0); } cell1.setCellValue("2"==null ? "" :"ABCDEFG"); //这里的数据可以动态生成,我这里是写死为了测试 wb.setForceFormulaRecalculation(true); //更新excel out= response.getoutputStream(); //获得输出流 response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream; charset=UTF-8"); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); wb.write(out); if (out != null) out.close(); //关闭资源 } }
如果能帮到你们点个关注,定期更新一些有用的功能
原文地址:https://www.jb51.cc/wenti/3283754.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。