package com.moral.monitor.util; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javax.servlet.http.HttpServletResponse; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import net.sf.json.JSONObject; @SuppressWarnings("rawtypes") public class ExportExcelUtils { public static OutputStream exportData(HttpServletResponse response, String fileName, List list,String[][] exportColumn) throws Exception { // 文件名加后缀信 String excelFileName = fileName + ".xls"; OutputStream outputStream = response.getOutputStream(); // 设定输出文件头 response.setHeader("Content-Type", "application/force-download"); // 把文件名转码使前台可以显示中文名 response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(excelFileName.getBytes("gb2312"), "ISO8859-1") + "\""); // 生成excel表格 exportExcel(outputStream,list, getColumn(exportColumn),getName(exportColumn), fileName); return outputStream; } public static void exportExcel(OutputStream os, List list, String[] colTitles, String[] fieldNames, String fileName) throws Exception { WritableWorkbook wwb = Workbook.createWorkbook(os); createSheet(wwb, fileName, 0, list, colTitles, fieldNames); wwb.write(); wwb.close(); } private static void createSheet(WritableWorkbook wwb, String sheetName, int index, List list, String[] colTitles, String[] fieldNames) throws RowsExceededException, WriteException, UnsupportedEncodingException { WritableSheet ws = wwb.createSheet(sheetName, index); // 标题定义样式 WritableFont font = new WritableFont(WritableFont.createFont("宋体"), 10, WritableFont.BOLD); WritableCellFormat wcf = new WritableCellFormat(font); for (int i = 0; i < colTitles.length; i++) { String title = colTitles[i]; ws.addCell(new Label(i, 0, title.split(",")[0], wcf)); ws.setColumnView(i, Integer.valueOf(title.split(",")[1])); } for (int i = 0; i < list.size(); i++) { JSONObject jsonObject = JSONObject.fromObject(list.get(i)); for (int j = 0; j < colTitles.length; j++) { ws.addCell(new Label(j, i + 1, jsonObject.getString(fieldNames[j]))); } } } /** * 获得导出 列标题 和 列宽度 * * @return */ public static String[] getColumn(String[][] exportColumn) { if (exportColumn != null) { String[] result = new String[exportColumn.length]; for (int i = 0; i < exportColumn.length; i++) { result[i] = exportColumn[i][0] + "," + exportColumn[i][1]; } return result; } else { return new String[0]; } } /** * 获得 表针对字段 * * @return */ public static String[] getName(String[][] exportColumn) { if (exportColumn != null) { String[] result = new String[exportColumn.length]; for (int i = 0; i < exportColumn.length; i++) { result[i] = exportColumn[i][2]; } return result; } else { return new String[0]; } } }