使用java 的PO實現將從數據庫查詢的結果,導入到excel文件,並返回到頁面下載鏈接。
依賴:
1 <dependency> 2 <groupId>org.apache.poi</groupId> 3 <artifactId>poi</artifactId> 4 <version>3.15</version> 5 </dependency>
代碼:
ResultSet rs為數據庫查詢結果
1 public void write2excel(HttpServletResponse response,HttpServletRequest request, ResultSet rs, String fileName) 2 throws SQLException, IOException { 3 //創建HSSFWorkbook,一個HSSFWorkbook對應一個Excel文件 4 HSSFWorkbook wb = new HSSFWorkbook(); 5 //在workbook中添加一個sheet,對應Excel文件中的sheet 6 HSSFSheet sheet = wb.createSheet("sheet"); 7 //創建第一行 8 HSSFRow row = sheet.createRow(0); 9 HSSFCell cell; 10 // 將列名寫入 11 for (int j = 0; j < rs.getMetaData().getColumnCount(); j++) { 12 String columnName = rs.getMetaData().getColumnLabel(j + 1); 13 // 給列寫入數據,創建單元格,寫入數據 14 cell = row.createCell(j); 15 cell.setCellValue(columnName); 16 17 } 18 19 // 寫入正式數據 20 int i = 0; 21 while (rs.next()) { 22 row = sheet.createRow(i + 1); 23 for (int j = 0; j < rs.getMetaData().getColumnCount(); j++) { 24 String columnValue = rs.getString(j + 1); 25 row.createCell(j).setCellValue(columnValue); 26 } 27 ++i; 28 } 29 //上面的操作已經是生成一個完整的文件了,只需要將生成的流轉換成文件即可 30 ServletOutputStream outputStream = null; 31 32 33 //配置header 34 // attachment這個代表要下載的,如果去掉就直接打開了(attachment-作為附件下載,inline-在線打開) 35 // filename是文件名,另存為或者下載時,為默認的文件名 36 String agent = request.getHeader("USER-AGENT").toLowerCase(); 37 response.reset(); 38 39 //下面開始到try之前主要為解決excel亂碼問題 40 response.setContentType("multipart/form-data"); 41 response.setCharacterEncoding("utf-8"); 42 43 //火狐瀏覽器 44 if (agent.contains("firefox")) { 45 fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1"); 46 } else { 47 fileName = java.net.URLEncoder.encode(fileName, "UTF-8"); 48 } 49 50 response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); 51 52 try{ 53 //生成response傳輸流,若是傳輸到本地則需創建FileOutputStream 54 outputStream = response.getOutputStream(); 55 wb.write(outputStream); 56 }catch (Exception e){ 57 e.printStackTrace(); 58 }finally { 59 outputStream.flush(); 60 outputStream.close(); 61 62 } 63 64 }
tips:
此外在開發中踩到的坑還有:在使用swagger調試接口的時候,下載導出文件excel到頁面時,會亂碼,但使用url加上參數(swagger接口下面有寫好的了)則導出到頁面的鏈接下載文件后能正常顯示,不亂碼。