項目中咱們常常用到導出功能,將數據導出以便於審查和統計等。本文主要使用Apache POI實現導出數據。前端
ApachePOI是Apache軟件基金會的開放源碼函式庫,POI提供API給java程序對Microsoft Office格式檔案讀和寫的功能。java
HSSF概況apache
HSSF是Horrible SpreadSheet Format的縮寫,經過HSSF,你能夠用純java代碼來讀取、寫入、修改Excel文件。HSSF爲讀取操做提供了兩類API:usermodel和eventusermodel,既」用戶模型「和」事件-用戶模型「。數組
POI Excel 文檔結構類瀏覽器
1 HSSFWorkbook excel文檔對象 2 HSSFSheet excel的sheet 3 HSSFRow excel的行 4 HSSFCell excel的單元格 5 HSSFFont excel字體 6 HSSFName 名稱 7 HSSFDataFormat 日期格式 8 HSSFHeader sheet頭 9 HSSFFooter sheet尾 10 HSSFCellStyle cell樣式 11 HSSFDateUtil 日期 12 HSSFPrintSetup 打印 13 HSSFErrorConstants 錯誤信息表
1 POIFSFileSystem fs=newPOIFSFileSystem(new FileInputStream("d:/test.xls")); 2 //獲得Excel工做簿對象 3 HSSFWorkbook wb = new HSSFWorkbook(fs); 4 //獲得Excel工做表對象 5 HSSFSheet sheet = wb.getSheetAt(0); 6 //獲得Excel工做表的行 7 HSSFRow row = sheet.getRow(i); 8 //獲得Excel工做表指定行的單元格 9 HSSFCell cell = row.getCell((short) j); 10 cellStyle = cell.getCellStyle();//獲得單元格樣式
1 HSSFWorkbook wb = new HSSFWorkbook();//建立Excel工做簿對象 2 HSSFSheet sheet = wb.createSheet("new sheet");//建立Excel工做表對象 3 HSSFRow row = sheet.createRow((short)0); //建立Excel工做表的行 4 cellStyle = wb.createCellStyle();//建立單元格樣式 5 row.createCell((short)0).setCellStyle(cellStyle); //建立Excel工做表指定行的單元格 6 row.createCell((short)0).setCellValue(1); //設置Excel工做表的值
1 //設置sheet名稱和單元格內容 2 wb.setSheetName(1, "第一張工做表",HSSFCell.ENCODING_UTF_16); 3 cell.setEncoding((short) 1); 4 cell.setCellValue("單元格內容"); 5 6 //取得sheet的數目 7 wb.getNumberOfSheets() 8 9 //根據index取得sheet對象 10 HSSFSheet sheet = wb.getSheetAt(0); 11 12 //取得有效的行數 13 int rowcount = sheet.getLastRowNum(); 14 15 //取得一行的有效單元格個數 16 row.getLastCellNum(); 17 18 //單元格值類型讀寫 19 cell.setCellType(HSSFCell.CELL_TYPE_STRING); //設置單元格爲STRING類型 20 cell.getNumericCellValue();//讀取爲數值類型的單元格內容 21 22 //設置列寬、行高 23 sheet.setColumnWidth((short)column,(short)width); 24 row.setHeight((short)height); 25 26 //添加區域,合併單元格 27 Region region = new Region((short)rowFrom,(short)columnFrom,(short)rowTo,(short)columnTo);//合併從第rowFrom行columnFrom列 28 sheet.addMergedRegion(region);// 到rowTo行columnTo的區域 29 //獲得全部區域 30 sheet.getNumMergedRegions() 31 32 //保存Excel文件 33 FileOutputStream fileOut = new FileOutputStream(path); 34 wb.write(fileOut);
1 <dependency> 2 <groupId>org.apache.poi</groupId> 3 <artifactId>poi</artifactId> 4 <version>${poi.version</version> 5 </dependency> 6 7 <dependency> 8 <groupId>org.apache.poi</groupId> 9 <artifactId>poiscratchpad</artifactId> 10 <version>${poi.version</version> 11 </dependency> 12 13 <dependency> 14 <groupId>org.apache.poi</groupId> 15 <artifactId>poiooxml</artifactId> 16 <version>${poi.version</version> 17 </dependency>
1 public class ExcelExport { 2 //表頭 3 private String title; 4 //各個列的表頭 5 private String[] heardList; 6 //各個列的元素key值 7 private String[] heardKey; 8 //須要填充的數據信息 9 private List<Map> data; 10 //字體大小 11 private int fontSize = 14; 12 //行高 13 private int rowHeight = 30; 14 //列寬 15 private int columWidth = 200; 16 //工做表 17 private String sheetName = "sheet1"; 18 19 public String getTitle() { 20 return title; 21 } 22 23 public ExcelExport setTitle(String title) { 24 this.title = title; 25 return this; 26 } 27 28 public String[] getHeardList() { 29 return heardList; 30 } 31 32 public ExcelExport setHeardList(String[] heardList) { 33 this.heardList = heardList; 34 return this; 35 } 36 37 public String[] getHeardKey() { 38 return heardKey; 39 } 40 41 public ExcelExport setHeardKey(String[] heardKey) { 42 this.heardKey = heardKey; 43 return this; 44 } 45 46 public List<Map> getData() { 47 return data; 48 } 49 50 public ExcelExport setData(List<Map> data) { 51 this.data = data; 52 return this; 53 } 54 55 public int getFontSize() { 56 return fontSize; 57 } 58 59 public ExcelExport setFontSize(int fontSize) { 60 this.fontSize = fontSize; 61 return this; 62 } 63 64 public int getRowHeight() { 65 return rowHeight; 66 } 67 68 public ExcelExport setRowHeight(int rowHeight) { 69 this.rowHeight = rowHeight; 70 return this; 71 } 72 73 public int getColumWidth() { 74 return columWidth; 75 } 76 77 public ExcelExport setColumWidth(int columWidth) { 78 this.columWidth = columWidth; 79 return this; 80 } 81 82 public String getSheetName() { 83 return sheetName; 84 } 85 86 public ExcelExport setSheetName(String sheetName) { 87 this.sheetName = sheetName; 88 return this; 89 } 90 91 /** 92 * 開始導出數據信息 93 * 94 * @throws ExcelException 拋出數據異常類 95 */ 96 public byte[] exportExport(HttpServletRequest request, HttpServletResponse response) throws ExcelException { 97 //檢查參數配置信息 98 checkConfig(); 99 //建立工做簿 100 HSSFWorkbook wb = new HSSFWorkbook(); 101 //建立工做表 102 HSSFSheet wbSheet = wb.createSheet(this.sheetName); 103 //在第0行建立rows 104 HSSFRow row = wbSheet.createRow((int) 0); 105 //建立單元格,設置表頭,表頭居中 106 HSSFCellStyle style = wb.createCellStyle(); 107 //設置單元格樣式 108 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 109 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 110 HSSFFont font = wb.createFont(); 111 font.setFontHeightInPoints((short) this.fontSize); 112 113 //設置列頭元素 114 HSSFCell cellHead = null; 115 for (int i = 0; i < heardList.length; i++) { 116 cellHead = row.createCell(i); 117 cellHead.setCellValue(heardList[i]); 118 cellHead.setCellStyle(style); 119 } 120 121 //開始寫入實體數據信息 122 style.setFont(font); 123 for (int i = 0; i < data.size(); i++) { 124 HSSFRow roww = wbSheet.createRow((int) i + 1); 125 Map map = data.get(i); 126 HSSFCell cell = null; 127 for (int j = 0; j < heardKey.length; j++) { 128 cell = roww.createCell(j); 129 cell.setCellStyle(style); 130 Object valueObject = map.get(heardKey[j]); 131 String value = null; 132 if (valueObject == null) { 133 valueObject = ""; 134 } 135 if (valueObject instanceof String) { 136 //取出的數據是字符串直接賦值 137 value = (String) map.get(heardKey[j]); 138 } else if (valueObject instanceof Integer) { 139 //取出的數據是Integer 140 value = String.valueOf(((Integer) (valueObject)).floatValue()); 141 } else if (valueObject instanceof BigDecimal) { 142 //取出的數據是BigDecimal 143 value = String.valueOf(((BigDecimal) (valueObject)).floatValue()); 144 } else { 145 value = valueObject.toString(); 146 } 147 cell.setCellValue(Strings.isNullOrEmpty(value) ? "" : value); 148 } 149 } 150 //設置行高 151 //設置行高的過程須要注意的一不包含標題 152 for (int i = 0; i < data.size() + 1; i++) { 153 HSSFRow hssfRow = wbSheet.getRow(i); 154 hssfRow.setHeightInPoints(this.rowHeight); 155 } 156 //設置列寬 157 if (data.size() > 0) { 158 for (int i = 0; i < data.get(0).size(); i++) { 159 wbSheet.setColumnWidth(i, MSExcelUtils.pixel2WidthUnits(this.columWidth)); 160 } 161 } else { 162 for (int i = 0; i < heardList.length; i++) { 163 wbSheet.setColumnWidth(i, MSExcelUtils.pixel2WidthUnits(this.columWidth)); 164 } 165 } 166 //導出數據 167 try { 168 //設置Http響應頭告訴瀏覽器下載這個附件 169 response.setHeader("Content-Disposition", "attachment;Filename=" + System.currentTimeMillis() + ".xls"); 170 OutputStream outputStream = response.getOutputStream(); 171 wb.write(outputStream); 172 outputStream.close(); 173 return wb.getBytes(); 174 } catch (Exception ex) { 175 ex.printStackTrace(); 176 throw new ExcelException("導出Excel出現嚴重異常,異常信息:" + ex.getMessage()); 177 } 178 179 } 180 181 /** 182 * 檢查數據配置問題 183 * 184 * @throws ExcelException 拋出數據異常類 185 */ 186 protected void checkConfig() throws ExcelException { 187 if (heardKey == null || heardList.length == 0) { 188 throw new ExcelException("列名數組不能爲空或者爲NULL"); 189 } 190 191 if (fontSize < 0 || rowHeight < 0 || columWidth < 0) { 192 throw new ExcelException("字體、寬度或者高度不能爲負值"); 193 } 194 195 if (Strings.isNullOrEmpty(sheetName)) { 196 throw new ExcelException("工做表表名不能爲NULL"); 197 } 198 } 199 }
1 /** 2 * 導出分類銷售統計 3 * 4 * @param request 5 * @param response 6 * @param startDate 開始日期 7 * @param endDate 結束日期 8 * @param searchKey 關鍵字 9 * @param storeId 店鋪id 10 * @param organId 組織id 11 * @return 12 */ 13 public byte[] exportSaleCategory(HttpServletRequest request, HttpServletResponse response, String startDate,String endDate, String searchKey, String storeId, String organId) { 14 Integer count = augeSaleMapper.countShowCategoryStatistics(storeId, organId, startDate, endDate, searchKey); 15 List<Map> maps = augeSaleMapper.selectShowCategoryStatistics(storeId, organId, startDate, endDate,searchKey, 0, count); 16 String[] rowsName = new String[]{"商品分類", "銷售數量", "銷售金額", "毛利額", "毛利率"}; 17 String[] parames = new String[]{"name", "saleCount", "itemSumPrice", "grossProfit", "grossProfitMargin"}; 18 //建立導出工具類 19 ExcelExport excelExport = new ExcelExport(); 20 excelExport.setHeardKey(parames).setData(maps).setHeardList(rowsName); 21 byte[] bytes = excelExport.exportExport(request, response); 22 return bytes; 23 }
1 @RequestMapping(value = "/exportSaleCategory", method = RequestMethod.GET) 2 public ResponseEntity<byte[]> exportSaleCategory(HttpServletRequest request, HttpServletResponse response, String startDate, String endDate, String searchKey, String storeId) throws Exception { 3 AugeAdmin admin = (AugeAdmin) session.getAttribute("admin"); 4 HttpHeaders headers = new HttpHeaders(); 5 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 6 String fileName = new String(("品類銷售統計.xls").getBytes("UTF-8"), "iso-8859-1"); 7 headers.setContentDispositionFormData("attachment", fileName); 8 byte[] bytes = saleService.exportSaleCategory(request, response, Strings.emptyToNull(startDate), 9 Strings.emptyToNull(endDate), Strings.emptyToNull(searchKey), Strings.emptyToNull(storeId), admin.getOrganId()); 10 return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED); 11 }
1 $("#exportBtn").on('click', function () { 2 var startDate = $('#startDate').val(); 3 var endDate = $('#endDate').val(); 4 var storeId = $("#storeId").val(); 5 var url = "${basePath}/sale/exportSaleCategory?startDate=" + startDate + "&endDate=" +endDate + "&storeId=" + storeId; 6 window.location.href = url; 7 });