Excel表格匯出
1.添加pom依賴
1 <!-- office 操作工具 --> 2 <dependency> 3 <groupId>org.apache.poi</groupId> 4 <artifactId>poi</artifactId> 5 <version>3.17</version> 6 </dependency> 7 <dependency> 8 <groupId>org.apache.poi</groupId> 9 <artifactId>poi-ooxml</artifactId> 10 <version>3.17</version> 11 </dependency> 12 13 <dependency> 14 <groupId>org.apache.poi</groupId> 15 <artifactId>poi-scratchpad</artifactId> 16 <version>3.17</version> 17 </dependency>
2.撰寫匯出Excel的工具類
1 public class MyExcelUtils { 2 /** 3 * @param titles 表頭 4 * @param out 5 * @param listMap 資料 6 * @param keys 資料庫欄位(與表頭相對應) 7 */ 8 public static void export(String[] titles, ServletOutputStream out, List<Map<String, Object>> listMap, String[] keys) { 9 try { 10 //1.創建一個workbook,對應一個Excel檔案 11 HSSFWorkbook workbook = new HSSFWorkbook(); 12 //2.在workbook中添加一個sheet,對應Excel檔案中的sheet 13 HSSFSheet hssfSheet = workbook.createSheet("串列1"); 14 //3.在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short 15 HSSFRow row = hssfSheet.createRow(0); 16 //4.創建單元格 設定表單 居中 17 HSSFCellStyle hssfCellStyle = workbook.createCellStyle(); 18 HSSFCell hssfCell = null; 19 for (int i = 0; i < titles.length; i++) { 20 hssfCell = row.createCell(i);//列索引從0開始 21 hssfCell.setCellValue(titles[i]);//列名1 22 hssfCell.setCellStyle(hssfCellStyle);//列居中顯示 23 } 24 //5.填充資料 25 for (int i = 0; i < listMap.size(); i++) { //行數 26 row = hssfSheet.createRow(i + 1); // 表資料的起始行數為 1 27 //資料庫資料 28 Map<String, Object> map = listMap.get(i); 29 for (int j = 0; j < titles.length; j++) { //列數 30 row.createCell(j).setCellValue((String) map.get(keys[j])); 31 } 32 } 33 // 6.將檔案輸出到客戶端瀏覽器 34 try { 35 workbook.write(out); 36 out.flush(); 37 out.close(); 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } 41 } catch (Exception e) { 42 e.printStackTrace(); 43 } 44 } 45 }
3.后端Controller實作(Controller引數: HttpServletResponse response)
為保證Excel表格的表頭和其列值相匹配,采用兩個陣列進行一一對應(或使用Map)
1 //Excel表頭、檔案名(titles的長度和xml中sql查詢的欄位個數(keys長度)一致) 2 String[] titles = {"編號", "姓名", "年齡"}; 3 //Excel檔案名 4 String name = "Excel表格下載"; 5 //資料庫對應欄位 6 String[] keys = {"id", "name", "age"}; 7 8 response.setContentType("application/binary;charset=UTF-8"); 9 try { 10 ServletOutputStream out = response.getOutputStream(); 11 try { 12 //設定檔案頭:一個引數是設定下載檔案名 13 response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name + ".xls", "UTF-8")); 14 } catch (UnsupportedEncodingException e1) { 15 e1.printStackTrace(); 16 } 17 // 資料庫對應的需要匯出的Excel資料 18 List<Map<String, Object>> listMap = exportExcelDAO.exportExcelData(); 19 // MyExcelUtils下載Excel 20 MyExcelUtils.export(titles, out, listMap, keys);
21 } catch (Exception e) { 22 e.printStackTrace();
23 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/152378.html
標籤:Java
上一篇:HTTP
