部分代码:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet1");
// **设置表头的格式一直失效**
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment((short)HorizontalAlignment.CENTER.ordinal());
cellStyle.setVerticalAlignment((short)VerticalAlignment.CENTER.ordinal());
Font font = workbook.createFont();
font.setColor(HSSFColor.RED.index);
cellStyle.setFont(font);
// 创建表头(列名)
HSSFRow row = sheet.createRow(0);
for(int i = 0;i<znFiledList.size();i++){
HSSFCell cell = row.createCell(i);
cell.setCellValue(znFiledList.get(i));
}
// 读取数据后,把数据放进去
for(int i = 0;i<mapList.size();i++){
row = sheet.createRow(i+1);// index为 0 已经被使用作为列名显示了
row.createCell(0).setCellValue(mapList.get(i).get("id").toString());
row.createCell(1).setCellValue(mapList.get(i).get("name").toString());
row.createCell(2).setCellValue(mapList.get(i).get("position").toString());
row.createCell(3).setCellValue(mapList.get(i).get("role").toString().equals("1")? "上司" : "员工");
}
OutputStream outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition","attachment;filename=template.xls");
workbook.write(outputStream);
outputStream.flush();
outputStream.close();