话不多说,直接上代码
首先 action层
1)定义好导出文件的名称 例如 export.xls
2)计算好需要导出的List<String;>文件
3)然后直接调用下面的方法
public static void export2Excel(HttpServletResponse response, String fileName, List<String[]> list) throws IOException {
response.reset();
//response.setContentType("application/pdf"); 导出PDF的加上该行
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
OutputStream output = response.getOutputStream();
// 初始化excel信息
HSSFWorkbook wb = new HSSFWorkbook();
int pageCnt = 1;
HSSFSheet sheet = wb.createSheet("第"+pageCnt+"页");
int count =0;
for (int r = 0; r < list.size(); r++) {// excel row
if (count >65530){//解决文件内容过长的问题
count=0;
pageCnt++;
sheet = wb.createSheet("第"+pageCnt+"页");
createHead(sheet, list.get(0), count);
count++;
createHead(sheet, list.get(r), count);
continue;
}
if (r%100 == 0){
}
createHead(sheet, list.get(r), count);
count++;
}
wb.write(output);
output.flush();
output.close();
}
private static void createHead(HSSFSheet sheet,String[] line,int count){
HSSFRow row = sheet.createRow(count);
HSSFCell cell = null;
for (int c = 0; c < line.length; c++) {// excel cell
cell = row.createCell(c);
cell.setCellValue(new HSSFRichTextString(line[c]));
}
}