Maven項目結合POI導出Excl表格
一、POM文件添加依賴
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.6</version> </dependency>
二、將ExportExcel類放進項目的util中
package com.jonychen.util.core; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.util.CellRangeAddress; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import static com.jonychen.HttpKit.getResponse;(后面有代碼,復制粘貼即可) /** *導出工具類 */ public class ExportExcel{ //顯示的導出表的標題 private String title; //導出表的列名 private String[] rowName ; private List<Object[]> dataList = new ArrayList<Object[]>(); HttpServletResponse response; //構造方法,傳入要導出的數據 public ExportExcel(String title,String[] rowName,List<Object[]> dataList){ this.dataList = dataList; this.rowName = rowName; this.title = title; } /* * 導出數據 * */ public void export() throws Exception{ try{ HSSFWorkbook workbook = new HSSFWorkbook(); // 創建工作簿對象 HSSFSheet sheet = workbook.createSheet(title); // 創建工作表 // 產生表格標題行 HSSFRow rowm = sheet.createRow(0); HSSFCell cellTiltle = rowm.createCell(0); //sheet樣式定義【getColumnTopStyle()/getStyle()均為自定義方法 - 在下面 - 可擴展】 HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//獲取列頭樣式對象 HSSFCellStyle style = this.getStyle(workbook); //單元格樣式對象 sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1))); cellTiltle.setCellStyle(columnTopStyle); cellTiltle.setCellValue(title); // 定義所需列數 int columnNum = rowName.length; HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置創建行(最頂端的行開始的第二行) // 將列頭設置到sheet的單元格中 for(int n=0;n<columnNum;n++){ HSSFCell cellRowName = rowRowName.createCell(n); //創建列頭對應個數的單元格 cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //設置列頭單元格的數據類型 HSSFRichTextString text = new HSSFRichTextString(rowName[n]); cellRowName.setCellValue(text); //設置列頭單元格的值 cellRowName.setCellStyle(columnTopStyle); //設置列頭單元格樣式 } //將查詢出的數據設置到sheet對應的單元格中 for(int i=0;i<dataList.size();i++){ Object[] obj = dataList.get(i);//遍歷每個對象 HSSFRow row = sheet.createRow(i+3);//創建所需的行數 for(int j=0; j<obj.length; j++){ HSSFCell cell = null; //設置單元格的數據類型 if(j == 0){ cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC); cell.setCellValue(i+1); }else{ cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING); if(!"".equals(obj[j]) && obj[j] != null){ cell.setCellValue(obj[j].toString()); //設置單元格的值 } } cell.setCellStyle(style); //設置單元格樣式 } } //讓列寬隨着導出的列長自動適應 for (int colNum = 0; colNum < columnNum; colNum++) { int columnWidth = sheet.getColumnWidth(colNum) / 256; for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { HSSFRow currentRow; //當前行未被使用過 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { HSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { int length = currentCell.getStringCellValue().getBytes().length; if (columnWidth < length) { columnWidth = length; } } } } if(colNum == 0){ sheet.setColumnWidth(colNum, (columnWidth-2) * 256); }else{ sheet.setColumnWidth(colNum, (columnWidth+4) * 256); } } if(workbook !=null){ try { String fileName = "Excel-Signup" + System.currentTimeMillis() + ".xls"; String headStr = "attachment; filename=\"" + fileName + "\""; response =getResponse(); response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", headStr); OutputStream out = response.getOutputStream(); workbook.write(out); } catch (IOException e) { e.printStackTrace(); } } }catch(Exception e){ e.printStackTrace(); } } /* * 列頭單元格樣式 */ public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) { // 設置字體 HSSFFont font = workbook.createFont(); //設置字體大小 font.setFontHeightInPoints((short)11); //字體加粗 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //設置字體名字 font.setFontName("Courier New"); //設置樣式; HSSFCellStyle style = workbook.createCellStyle(); //設置底邊框; style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //設置底邊框顏色; style.setBottomBorderColor(HSSFColor.BLACK.index); //設置左邊框; style.setBorderLeft(HSSFCellStyle.BORDER_THIN); //設置左邊框顏色; style.setLeftBorderColor(HSSFColor.BLACK.index); //設置右邊框; style.setBorderRight(HSSFCellStyle.BORDER_THIN); //設置右邊框顏色; style.setRightBorderColor(HSSFColor.BLACK.index); //設置頂邊框; style.setBorderTop(HSSFCellStyle.BORDER_THIN); //設置頂邊框顏色; style.setTopBorderColor(HSSFColor.BLACK.index); //在樣式用應用設置的字體; style.setFont(font); //設置自動換行; style.setWrapText(false); //設置水平對齊的樣式為居中對齊; style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //設置垂直對齊的樣式為居中對齊; style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } /* * 列數據信息單元格樣式 */ public HSSFCellStyle getStyle(HSSFWorkbook workbook) { // 設置字體 HSSFFont font = workbook.createFont(); //設置字體大小 //font.setFontHeightInPoints((short)10); //字體加粗 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //設置字體名字 font.setFontName("Courier New"); //設置樣式; HSSFCellStyle style = workbook.createCellStyle(); //設置底邊框; style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //設置底邊框顏色; style.setBottomBorderColor(HSSFColor.BLACK.index); //設置左邊框; style.setBorderLeft(HSSFCellStyle.BORDER_THIN); //設置左邊框顏色; style.setLeftBorderColor(HSSFColor.BLACK.index); //設置右邊框; style.setBorderRight(HSSFCellStyle.BORDER_THIN); //設置右邊框顏色; style.setRightBorderColor(HSSFColor.BLACK.index); //設置頂邊框; style.setBorderTop(HSSFCellStyle.BORDER_THIN); //設置頂邊框顏色; style.setTopBorderColor(HSSFColor.BLACK.index); //在樣式用應用設置的字體; style.setFont(font); //設置自動換行; style.setWrapText(false); //設置水平對齊的樣式為居中對齊; style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //設置垂直對齊的樣式為居中對齊; style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } }
com.jonychen.HttpKit.getResponse
/** * Copyright (c) 2015-2016, Chill Zhuang 庄騫 (smallchill@163.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jonychen.util.core; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; public class HttpKit { public static String getIp(){ return HttpKit.getRequest().getRemoteHost(); } /** * 獲取所有請求的值 */ public static Map<String, String> getRequestParameters() { HashMap<String, String> values = new HashMap<>(); HttpServletRequest request = HttpKit.getRequest(); Enumeration enums = request.getParameterNames(); while ( enums.hasMoreElements()){ String paramName = (String) enums.nextElement(); String paramValue = request.getParameter(paramName); values.put(paramName, paramValue); } return values; } /** * 獲取 HttpServletRequest */ public static HttpServletResponse getResponse() { HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); return response; } /** * 獲取 包裝防Xss Sql注入的 HttpServletRequest * @return request */ public static HttpServletRequest getRequest() { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); return new WafRequestWrapper(request); } /** * 向指定URL發送GET方法的請求 * * @param url 發送請求的URL * @param param 請求參數 * @return URL 所代表遠程資源的響應結果 */ public static String sendGet(String url, Map<String, String> param) { String result = ""; BufferedReader in = null; try { String para = ""; for (String key : param.keySet()) { para += (key + "=" + param.get(key) + "&"); } if (para.lastIndexOf("&") > 0) { para = para.substring(0, para.length() - 1); } String urlNameString = url + "?" + para; URL realUrl = new URL(urlNameString); // 打開和URL之間的連接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立實際的連接 connection.connect(); // 獲取所有響應頭字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍歷所有的響應頭字段 //for (String key : map.keySet()) { // System.out.println(key + "--->" + map.get(key)); //} // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 發送POST方法的請求 * * @param url 發送請求的 URL * @param param 請求參數 * @return 所代表遠程資源的響應結果 */ public static String sendPost(String url, Map<String, String> param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { String para = ""; for (String key : param.keySet()) { para += (key + "=" + param.get(key) + "&"); } if (para.lastIndexOf("&") > 0) { para = para.substring(0, para.length() - 1); } String urlNameString = url + "?" + para; URL realUrl = new URL(urlNameString); // 打開和URL之間的連接 URLConnection conn = realUrl.openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(param); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }
三、項目中寫Controller邏輯層進行調用工具類導出即可
@RequestMapping(value = "/export",method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody @ApiOperation(value = "導出報表", httpMethod = "GET", notes = "導出報表,前端寫一個導出地址調用此接口即可") public void signupExport(HttpServletRequest request, HttpServletResponse response) throws Exception { //獲取數據 List<SignupInfo> list = signupService.getSignupList(); logger.info("獲取全部列表數據"+JSONArray.toJSON(list)); String title = "匯總表"; String[] rowsName = new String[]{"序號", "姓名", "性別","手機號碼", "單位名稱", "省", "備注"}; List<Object[]> dataList = new ArrayList<>(); Object[] objs = null; for (int i = 0; i < list.size(); i++) { SignupfdfdsInfo signupInfo= list.get(i); objs = new Object[rowsName.length]; objs[0] = signupInfo.getId(); objs[1] = signupInfo.getUserName(); objs[2] = signupInfo.getSex(); objs[3]=signupInfo.getMobile(); objs[4] = signupInfo.getCompany(); objs[5] = signupInfo.getProvince(); objs[6] = signupInfo.getRemark(); dataList.add(objs); } ExportExcel ex = new ExportExcel(title, rowsName, dataList); ex.export(); }
可能遇到的異常:NPE(原因:導出的數據中沒有值,數據庫中存的值都要有默認值,我varchar型存的是無,int型的是0)