/**
*
*@注释 导出公共方法
*@方法名称 genExport
* @param title
* @param column
* @param date
* @param filename
* @throws Exception
*/
public static void genExport(String title, Map<String,String> column,List<Map<String,Object>> date, String filename) throws Exception {
ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
HttpServletRequest r = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(title);
sheet.setDefaultColumnWidth(20);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow headrow = sheet.createRow((int) 0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
headrow = sheet.createRow(0);
if(column==null) return;
Object [] colStr = (Object [])column.keySet().toArray();
for(int i=0; i<colStr.length; i++) {
HSSFCell cell = headrow.createCell(i);
cell.setCellValue(column.get(colStr[i].toString()));
cell.setCellStyle(style);
}
for(int j = 0; j <date.size(); j++) {
Map<String,Object> obj = date.get(j);
HSSFRow row = sheet.createRow(j+1);
for(int i=0; i<colStr.length; i++) {
row.createCell(i).setCellValue(obj.get(colStr[i]) != null?obj.get(colStr[i]).toString():"");
}
}
// 第六步,将文件存到指定位置
try {
FileOutputStream fout = new FileOutputStream(filename);
wb.write(fout);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType(filename);
response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "ISO8859-1"));
InputStream in = new FileInputStream(filename);
OutputStream out = response.getOutputStream();
// 写文件
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
File file = new File(filename);
file.delete();
}