java實現Excel匯出功能-poi
阿新 • • 發佈:2018-12-18
一、jar包
從maven倉庫下載即可,我是基於專案新加了這些jar包,應該還需要logging包,大家慢慢除錯就行,缺哪個就導進哪一個
poi-3.16.jar;
poi-ooxml-3.16.jar;
poi-ooxml-schemas-3.16.jar;
xmlbeans-2.6.0.jar;
commons-collections4-4.1,jar
二、工具類(拷貝網路上資源)
//呼叫方法傳遞四個引數
//1、title:表中第一行顯示錶主旨
//2、headmap:表頭資料
//3、datalist:表中資料
//4、datePattern:處理日期格式
//5、colwidth:列寬
//6、out:輸出流
public class ExcelUtils {
public static String NO_DEFINE = “no_define”;//未定義的欄位
public static String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";//預設日期格式 public static int DEFAULT_COLOUMN_WIDTH = 17;//預設列寬 /** * 匯出Excel * * @param title * @param headMap * @param dataList * @param datePattern * @param colWidth * @param out */ public static void exportExcel(String title, Map<String, String> headMap, List<Map> dataList, String datePattern, int colWidth, OutputStream out) { if (datePattern == null) datePattern = DEFAULT_DATE_PATTERN; // 宣告一個工作薄 SXSSFWorkbook workbook = new SXSSFWorkbook(1000);//快取 workbook.setCompressTempFiles(true); //表頭樣式 CellStyle titleStyle = workbook.createCellStyle(); titleStyle.setAlignment(HorizontalAlignment.CENTER); Font titleFont = workbook.createFont(); titleFont.setFontHeightInPoints((short) 20); titleStyle.setFont(titleFont); // 列頭樣式 CellStyle headerStyle = workbook.createCellStyle(); headerStyle.setBorderLeft(BorderStyle.THIN); headerStyle.setBorderRight(BorderStyle.THIN); headerStyle.setBorderTop(BorderStyle.THIN); headerStyle.setBorderBottom(BorderStyle.THIN); headerStyle.setAlignment(HorizontalAlignment.CENTER); Font headerFont = workbook.createFont(); headerFont.setFontHeightInPoints((short) 12); headerStyle.setFont(headerFont); // 單元格樣式 CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setBorderLeft(BorderStyle.THIN); cellStyle.setBorderRight(BorderStyle.THIN); cellStyle.setBorderTop(BorderStyle.THIN); cellStyle.setBorderBottom(BorderStyle.THIN); cellStyle.setAlignment(HorizontalAlignment.CENTER); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); Font cellFont = workbook.createFont(); cellFont.setFontHeightInPoints((short) 12); cellStyle.setFont(cellFont); // 生成一個(帶標題)表格 SXSSFSheet sheet = workbook.createSheet(); //設定列寬 int minBytes = colWidth < DEFAULT_COLOUMN_WIDTH ? DEFAULT_COLOUMN_WIDTH : colWidth;//至少位元組數 int[] arrColWidth = new int[headMap.size()]; // 產生表格標題行,以及設定列寬 String[] properties = new String[headMap.size()]; String[] headers = new String[headMap.size()]; int ii = 0; for (Iterator<String> iter = headMap.keySet().iterator(); iter.hasNext(); ) { String fieldName = iter.next(); properties[ii] = fieldName; headers[ii] = headMap.get(fieldName); int bytes = fieldName.getBytes().length; arrColWidth[ii] = bytes < minBytes ? minBytes : bytes; sheet.setColumnWidth(ii, arrColWidth[ii] * 256); ii++; } // 遍歷集合資料,產生資料行 int rowIndex = 0; for (Map obj : dataList) { if (rowIndex == 0) { SXSSFRow titleRow = sheet.createRow(0);//表頭 rowIndex=0 titleRow.createCell(0).setCellValue(title); titleRow.getCell(0).setCellStyle(titleStyle); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1)); SXSSFRow headerRow = sheet.createRow(1); //列頭 rowIndex =1 for (int i = 0; i < headers.length; i++) { headerRow.createCell(i).setCellValue(headers[i]); headerRow.getCell(i).setCellStyle(headerStyle); } rowIndex = 2;//資料內容從 rowIndex=2開始 } SXSSFRow dataRow = sheet.createRow(rowIndex); for (int i = 0; i < properties.length; i++) { SXSSFCell newCell = dataRow.createCell(i); Object o = obj.get(properties[i]); String cellValue = ""; if (o == null) { cellValue = ""; } else if (o instanceof Date) { cellValue = new SimpleDateFormat(datePattern).format(o); } else if (o instanceof Float || o instanceof Double) { cellValue = new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toString(); } else { cellValue = o.toString(); } newCell.setCellValue(cellValue); newCell.setCellStyle(cellStyle); } rowIndex++; } try { workbook.write(out); workbook.close(); workbook.dispose(); } catch (IOException e) { e.printStackTrace(); } }
}
三、controller層
這裡根據各自專案,拼湊工具類方法引數。我的如下:
@RequestMapping(value = "/exportExcel", method = RequestMethod.GET) @ResponseBody public void exportExcel(HttpServletRequest request, HttpServletResponse response) { OutputStream outputStream = null; try { Map<String, Object> reqMap = new HashMap<String, Object>(); Map<String, Object> params = MyEntityUtils.getRequestParams(request); params.put("orgId", SessionUtils.getLoginUser().getOrgid()); params.put("action", "q_param"); //處理匯出按鈕傳來的引數 String decode = URLDecoder.decode(String.valueOf(params.get("search")), "UTF-8"); Map searchMap = (Map) JSON.parse(decode); params.putAll(searchMap); reqMap.put("datajson", JSON.toJSONString(params)); /** * 拼湊excel工具類的入參 */ //執行查詢獲取excel中的資料 List<Map> list = depositConfirmationService.queryDepositConfirmationList(reqMap); //第一列大表名 String sheetName = "保證金確認函"; Map<String, Object> headParam = new HashMap<String, Object>(); headParam.put("menuid","103002007"); List<Map> headList = pageConfService.getPageQueryResultByMap(headParam); Map<String, String> headMap = new HashMap<>(); if (headList != null && headList.size()>0) { for (Map map : headList) { headMap.put((String) map.get("field"),(String) map.get("title")); } } //設定response response.reset(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename="+ new String(("保證金確認函.xlsx").getBytes(), "iso-8859-1")); outputStream = response.getOutputStream(); //呼叫工具類方法將workbook寫入到流中 ExcelUtils.exportExcel(sheetName,headMap,list,null,0,outputStream); } catch (Exception e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
四、前臺點選按鈕執行匯出
注意這裡使用ajax是不行的。
$("#btnExport").click(function () {
var search = $("#mysearch").serializeObject();//獲取查詢條件
location.href = "/a/b/c/exportExcel.do?search="+encodeURI(encodeURI(JSON.stringify(search)));
})
五、特別說明
前後臺查詢引數漢字會亂碼,前臺使用encodeURI(encodeURI()),後臺使用URLDecoder.decode(str, “UTF-8”)就可以解決。