1.poi版本3.17
@RequestMapping(value = "/export", method = RequestMethod.POST)
public void exportOptimize(HttpServletResponse httpResponse){
try {
//存储的Excel文件名称
String fileName = "optimize"+".xls";
fileName = URLEncoder.encode(fileName, "UTF-8");
httpResponse.setHeader("Content-Disposition", "attachment;filename=" + fileName);
httpResponse.setContentType("application/octet-stream");
httpResponse.setCharacterEncoding("utf-8");
riskService.export(list, httpResponse);
} catch (Exception e) {
e.printStackTrace();
// throw new ServiceException("导出异常");
}
}
public void export( HttpServletResponse response) throws IOException {
//创建Excel文件输出流对象
OutputStream fos = response.getOutputStream();
//1,创建一个webbook,对应一个Excel文件
HSSFWorkbook web = new HSSFWorkbook();
//2,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = web.createSheet("优化表");
// 第四步,设置表格文本数据居中
HSSFCellStyle style = web.createCellStyle();
//水平居中
style.setAlignment(HorizontalAlignment.CENTER);
//垂直居中
style.setVerticalAlignment(VerticalAlignment.CENTER);
//设置列的默认格式(从0开始)
sheet.setDefaultColumnStyle(3, style);
sheet.setDefaultColumnStyle(4, style);
sheet.setDefaultColumnStyle(5, style);
sheet.setDefaultColumnStyle(7, style);
sheet.setDefaultColumnStyle(8, style);
sheet.setDefaultColumnStyle(9, style);
sheet.setDefaultColumnStyle(10, style);
sheet.setDefaultColumnStyle(11, style);
sheet.setDefaultColumnStyle(12, style);
sheet.setDefaultColumnStyle(13, style);
//3,在sheet中添加表头第0行
HSSFRow row = sheet.createRow((int) 0);
HSSFCell cell = row.createCell((short)0);
//设定第一列第一行的单元格的格式
cell.setCellStyle(style);
cell.setCellValue("描述");
cell = row.createCell((short)1);
cell.setCellStyle(style);
cell.setCellValue("现行");
cell = row.createCell((short)2);
cell.setCellStyle(style);
cell.setCellValue("优化");
cell = row.createCell((short)3);
cell.setCellValue("姓名");
cell = row.createCell((short)4);
cell.setCellValue("目标完成日期");
cell = row.createCell((short)5);
cell.setCellValue("状态");
cell = row.createCell((short)6);
cell.setCellStyle(style);
cell.setCellValue("证据");
cell = row.createCell((short)7);
cell.setCellValue("完成日期");
cell = row.createCell((short)8);
cell.setCellValue("严重");
cell = row.createCell((short)9);
cell.setCellValue("发生");
cell = row.createCell((short)10);
cell.setCellValue("探测");
cell = row.createCell((short)11);
cell.setCellValue("A");
cell = row.createCell((short)12);
cell.setCellValue("R");
cell = row.createCell((short)13);
cell.setCellValue("S");
web.write(fos);
fos.flush();
fos.close();
}
//创建sheet的第i行
row = sheet.createRow(i);
row.createCell((short)3).setCellValue((String) "aaaaa");
//如果此处的98为null,则会报 NullPointException
row.createCell((short)11).setCellValue((Integer) 98);
//先录入数据,再合并单元格,(一个存数据,一个不存)
CellRangeAddress region1 = new CellRangeAddress(i, i+1, 0, 0);
sheet.addMergedRegion(region1);
全局style设定文本居中一直失败,但是设定列的默认格式成功