public static HSSFWorkbook getExcelForPath(String excelPath) {
HSSFWorkbook wb = null;
FileInputStream fis = null;
File f = new File(excelPath);
try {
if (f != null) {
fis = new FileInputStream(f);
wb = new HSSFWorkbook(fis);
}
} catch (Exception e) {
return null;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return wb;
}
@RequestMapping("/exportExcel")
public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
List<DataBsData> list = service.queryAllList(map);
String path = request.getSession().getServletContext().getRealPath("/");
String filePath = path + File.separator + "template" + File.separator + "abccd.xls";
log.info(" filePath is {}", filePath);
HSSFWorkbook wb = ExcelRender.getExcelForPath(filePath);
renderWorkbook(list, wb);
try {
log.info(" start download ........");
response.reset();
OutputStream os = response.getOutputStream();
response.setContentType("application/msexcel");
String fileName = "测试渲染的表";
fileName = StringUtils.isNotBlank(version) ? fileName.concat(version) : fileName;
response.setHeader("Content-disposition",
"attachment; filename=" + new String(fileName.getBytes("GB2312"), "8859_1") + ".xls");
wb.write(os);
os.close();
} catch (Exception e) {
try {
response.reset();
response.getWriter().write(e.getMessage());
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
private void renderWorkbook(List<DataBsData> list, HSSFWorkbook wb) {
org.apache.poi.ss.usermodel.Cell cell = null;
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setWrapText(true);
HSSFSheet sheet1 = wb.getSheetAt(0);
log.info(" wb.getSheetAt(0) is {}", sheet1.getDefaultColumnWidth());
HSSFRow row = sheet1.getRow(0);
for (int i = 0; i < list.size(); i++) {
DataBsData item = list.get(i);
row = sheet1.createRow(i + 4);
row.setHeight((short)900);
cell = row.createCell(0);
cell.setCellValue(item.getOrgName());
cell.setCellStyle(cellStyle);
cell = row.createCell(1);
cell.setCellStyle(cellStyle);
cell.setCellValue(item.getVa());
cell = row.createCell(2);
cell.setCellStyle(cellStyle);
cell.setCellValue(item.getVb());
cell = row.createCell(3);
cell.setCellStyle(cellStyle);
cell.setCellValue(item.getVc());
cell = row.createCell(4);
cell.setCellStyle(cellStyle);
cell.setCellValue(item.getVd());
cell = row.createCell(5);
cell.setCellStyle(cellStyle);
cell.setCellValue(item.getVe());
}
}