【我的写法】需要在项目下的resources文件夹下创建一个template文件夹然后模板放到template文件夹内;
【其他写法】当然如果你的情况不允许这样操作可以文件流的形式 只要拿到文件流的 InputStream 然后使用XSSFWorkbook wb = new XSSFWorkbook(inputStream); 拿到XSSFWorkbook对象后就可以为所欲为了。
/**
* 给固定模板添加数据
*
* @param responset
* @throws Exception
*/
@PostMapping("/export")
public void export(HttpServletResponse responset) throws Exception {
String name = "工单模板.xlsx";
//获取要下载的模板名称
String fileName = System.currentTimeMillis() + ".xlsx";
//设置要下载的文件的名称
responset.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
//通知客服文件的MIME类型
responset.setContentType("application/vnd.ms-template;charset=UTF-8");
//获取文件的路径
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + name)) {
//读取excel模板
assert inputStream != null;
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
Sheet sheet = wb.getSheetAt(0);
int i = 4;// 这个i是从excel的哪一行开始添加数据 i是下标
for (User user : userService.list()) {
Row row = sheet.getRow(0);
row = sheet.getRow(i);
row.createCell(0).setCellValue(user.getName());
row.createCell(1).setCellValue(user.getName());
row.createCell(2).setCellValue(user.getName());
row.createCell(3).setCellValue(user.getName());
row.createCell(4).setCellValue(user.getName());
row.createCell(5).setCellValue(user.getName());
row.createCell(6).setCellValue(user.getName());
row.createCell(7).setCellValue(user.getName());
row.createCell(8).setCellValue(user.getName());
row.createCell(9).setCellValue(user.getName());
row.createCell(10).setCellValue(user.getName());
row.createCell(11).setCellValue(user.getName());
row.createCell(12).setCellValue(user.getName());
i++;
}
OutputStream os = new BufferedOutputStream(responset.getOutputStream());
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
System.out.println("下载模板出错:" + e);
}
}