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(); //关闭资源
}
}
如果能帮到你们点个关注,定期更新一些有用的功能