读取的是java配置文件里面的excel模板文件
this.getClass().getClassLoader().getResource("static/CentralChinaExcleTemplate.xlsx").getPath();
工具类代码
public void ExportExcel(HttpServletRequest request, HttpServletResponse response, String date) throws IOException {
//1.加载Excel模板文件(文件路径按自己的存放路径填写)
String path = this.getClass().getClassLoader().getResource("static/CentralChinaExcleTemplate.xlsx").getPath();
path = path.substring(1);
File file = new File(path);
XSSFSheet sheet = null;
Workbook workbook = WorkbookFactory.create(file);
Sheet sheetAt = workbook.getSheetAt(0);
try (InputStream inputStream = new FileInputStream(file);
XSSFWorkbook xwb = new XSSFWorkbook(inputStream)) {
sheet = xwb.getSheetAt(0);
assert sheet != null;
XSSFCellStyle cellStyle = xwb.createCellStyle();
cellStyle.getFont().setFontHeightInPoints((short) 14);
CellStyle cellStyleLeft = workbook.createCellStyle();
cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
cellStyleLeft.setVerticalAlignment(VerticalAlignment.TOP);
//设置单元格边框
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
//设置居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
XSSFRow row = sheet.getRow(i);
//columnindex 意思为第几列的数据 1代表读取第六行第2列的数据
XSSFCell cell = null;
Row atRow = sheetAt.getRow(1);
// 生成第一行数据
if (i == 0) {
row = sheet.getRow(0);
cell = row.createCell(0);
cell.setCellStyle(cellStyle);
cell.setCellValue("月度环保统计报表(" + date + ")");
}
// 设置生成的Excel的文件名,并以中文进行编码
response.reset();
response.setHeader("Access-Control-Allow-Origin","*");
response.setContentType("application/msexcel");
response.setContentType("text/html; charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("月报数据.xlsx", "UTF-8"));
OutputStream osOut = response.getOutputStream();
// 将指定的字节写入此输出流
xwb.write(osOut);
// 刷新此输出流并强制将所有缓冲的输出字节被写出
osOut.flush();
// 关闭流
osOut.close();
} catch (IOException e) {
}
}