使用java簡單的從數據庫中查詢數據,而後寫入到excel中,數據的類型爲 List<Map<String, Object>>格式的數據。html
首先下載POI的jar包,網址:https://poi.apache.org/download.html#POI-3.16-beta2java
而後導入jar包到工程下數據庫
:apache
此外還須要 commons-collections4-4.1.jar 和 xmlbeans-2.6.0.jar 兩個額外的jar包,由於我使用的是 3.15 版本的,因此 commons-collections4-4.1.jar 須要使用 4.1 版本的,原來使用的是 4.0 ,報錯了。app
這兩個包能夠在這裏下載:xss
https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans/2.6.0測試
https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1字體
導入的類:spa
import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFComment; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
由於須要解析成爲 .xlsx 格式的 Excel 文件,因此須要的是 XSSFWorkbook.excel
準備數據:
public static List<Map<String, Object>> getData() { List<Map<String, Object>> data = new ArrayList<>(); // 使用 LinkedHashMap 保證有序,即標題和數據對應上 Map<String, Object> map1 = new LinkedHashMap<>(); map1.put("id", 1); map1.put("name", "張三"); map1.put("age", 23); map1.put("sex", "男"); Map<String, Object> map2 = new LinkedHashMap<>(); map2.put("id", 2); map2.put("name", "李四"); map2.put("age", 20); map2.put("sex", "女"); Map<String, Object> map3 = new LinkedHashMap<>(); map3.put("id", 3); map3.put("name", "王五"); map3.put("age", 19); map3.put("sex", "男"); Map<String, Object> map4 = new LinkedHashMap<>(); map4.put("id", 4); map4.put("name", "趙六"); map4.put("age", 18); map4.put("sex", "女"); Map<String, Object> map5 = new LinkedHashMap<>(); map5.put("id", 5); map5.put("name", "小七"); map5.put("age", 22); map5.put("sex", "男"); data.add(map1); data.add(map2); data.add(map3); data.add(map4); data.add(map5); return data; }
PS : 懶得去鏈接數據庫查詢了,就本身隨便搞了一個。
下面就是把數據寫到 Excel 文件中,只能建立一個 sheet。
/** * 導出Excel * @param sheetName 表格 sheet 的名稱 * @param headers 標題名稱 * @param dataList 須要顯示的數據集合 * @param exportExcelName 導出excel文件的名字 */ public static void exportExcel(String sheetName, List<Map<String, Object>> dataList, String[] headers,String exportExcelName) { // 聲明一個工做薄 XSSFWorkbook workbook = new XSSFWorkbook(); // 生成一個表格 XSSFSheet sheet = workbook.createSheet(sheetName); // 設置表格默認列寬度爲15個字節 sheet.setDefaultColumnWidth(15); // 生成表格中非標題欄的樣式 XSSFCellStyle style = workbook.createCellStyle(); // 設置這些樣式 style.setFillForegroundColor(HSSFColor.WHITE.index);//背景色 style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setBorderBottom(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); style.setBorderTop(BorderStyle.THIN); style.setAlignment(HorizontalAlignment.CENTER); // 生成表格中非標題欄的字體 XSSFFont font = workbook.createFont(); font.setColor(HSSFColor.BLACK.index); font.setFontHeightInPoints((short) 12); font.setBold(true); // 把字體應用到當前的樣式 style.setFont(font); // 設置表格標題欄的樣式 XSSFCellStyle titleStyle = workbook.createCellStyle(); titleStyle.setFillForegroundColor(HSSFColor.BLUE_GREY.index); titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); titleStyle.setBorderBottom(BorderStyle.THIN); titleStyle.setBorderLeft(BorderStyle.THIN); titleStyle.setBorderRight(BorderStyle.THIN); titleStyle.setBorderTop(BorderStyle.THIN); titleStyle.setAlignment(HorizontalAlignment.CENTER); titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 設置標題欄字體 XSSFFont titleFont = workbook.createFont(); titleFont.setColor(HSSFColor.WHITE.index); titleFont.setFontHeightInPoints((short) 12); titleFont.setBold(true); // 把字體應用到當前的樣式 titleStyle.setFont(titleFont); // 產生表格標題行 XSSFRow row = sheet.createRow(0); for (short i = 0; i < headers.length; i++) { XSSFCell cell = row.createCell(i); cell.setCellStyle(titleStyle); XSSFRichTextString text = new XSSFRichTextString(headers[i]); cell.setCellValue(text); } // 遍歷集合數據,產生數據行 Iterator<Map<String, Object>> it = dataList.iterator(); int index = 0; while (it.hasNext()) { index++; row = sheet.createRow(index); Map<String, Object> data = it.next(); int i = 0; for(String key : data.keySet()){ XSSFCell cell = row.createCell(i); cell.setCellStyle(style); XSSFRichTextString text = new XSSFRichTextString(data.get(key)+""); cell.setCellValue(text); i++; } } try { OutputStream out = null; String tmpPath = "G:\\excel\\" + exportExcelName + ".xlsx"; out = new FileOutputStream(tmpPath); workbook.write(out); } catch (IOException e) { e.printStackTrace(); }finally{ if(workbook != null){ try { workbook.close(); } catch (IOException e) { e.printStackTrace(); } } if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
測試:
public static void main(String[] args) { List<Map<String, Object>> data = MyExecl.getData(); String sheetName = "學生表"; String[] headers = {"ID","名稱","年齡","性別"}; String exportExcelName = "student"; MyExecl.exportExcel(sheetName, data, headers, exportExcelName); }
結果:
/** * 建立每一個 sheet 頁的數據 */ private void createSheetData(HSSFWorkbook aWorkbook, String[] aTitles, String aSheetName, List<String[]> aRowData) { HSSFSheet tmpSheet = aWorkbook.createSheet(aSheetName); // 設置sheet的標題 HSSFRow tmpTitileRow = tmpSheet.createRow(0); for (int i = 0; i < aTitles.length; i++) { tmpTitileRow.createCell(i).setCellValue(aTitles[i]); } // 遍歷填充每行的數據 HSSFRow tmpRow = null; int tmpRowNumber = 1; for (String[] rowData : aRowData) { tmpRow = tmpSheet.createRow(tmpRowNumber); for (int i = 0; i < rowData.length; i++) { tmpRow.createCell(i).setCellValue(rowData[i]); } tmpRowNumber++; } } /** * 設置響應頭 */ private void setResponseHeader(HttpServletResponse aResponse, String aFileName){ try { try { aFileName = new String(aFileName.getBytes(), "ISO8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } aResponse.setContentType("application/octet-stream;charset=ISO8859-1"); aResponse.setHeader("Content-Disposition", "attachment;filename=" + aFileName); aResponse.addHeader("Pargam", "no-cache"); aResponse.addHeader("Cache-Control", "no-cache"); } catch (Exception e) { e.printStackTrace(); } }
測試:
/** * 經過頁面導出 * @param aResponse * @throws IOException */ public void export(HttpServletResponse aResponse) throws IOException { HSSFWorkbook tmpWorkbook = new HSSFWorkbook(); String[] tmpUserTitles = {"姓名", "性別", "年齡", "工做"}; List<String[]> tmpUsers = getUsers(); createSheetData(tmpWorkbook, tmpUserTitles, "用戶信息", tmpUsers); setResponseHeader(aResponse, "用戶信息表.xls"); OutputStream tmpOutputStream = aResponse.getOutputStream(); tmpWorkbook.write(tmpOutputStream); tmpOutputStream.flush(); tmpOutputStream.close(); } /** * 導出,不經過頁面導出 */ public void export() throws IOException { HSSFWorkbook tmpWorkbook = new HSSFWorkbook(); String[] tmpUserTitles = {"姓名", "性別", "年齡", "工做"}; List<String[]> tmpUsers = getUsers(); createSheetData(tmpWorkbook, tmpUserTitles, "用戶信息", tmpUsers); String[] tmpAddressTitles = {"城市", "區域"}; List<String[]> getAddress = getAddress(); createSheetData(tmpWorkbook, tmpAddressTitles, "地址信息", getAddress); OutputStream tmpOutputStream = new FileOutputStream("E:\\" + System.currentTimeMillis() + ".xls"); tmpWorkbook.write(tmpOutputStream); tmpOutputStream.flush(); tmpOutputStream.close(); } /** * 測試數據 */ private List<String[]> getAddress(){ List<String[]> address = new ArrayList<>(); for(int i = 1; i <= 5; i++){ String[] addr = new String[2]; addr[0] = "四川"; addr[1] = "高新 - " + i; address.add(addr); } return address; } /** * 測試數據 */ private List<String[]> getUsers(){ List<String[]> users = new ArrayList<>(); for(int i = 0; i < 10; i++){ String[] user = new String[4]; user[0] = "zhangsan - " + i; user[1] = "男"; user[2] = "2" + i; user[3] = "Java - " + i; users.add(user); } return users; }
@SuppressWarnings("resource") private void download(HttpServletResponse resp) throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("用戶表"); XSSFRow row = sheet.createRow(0); XSSFDrawing p=sheet.createDrawingPatriarch(); XSSFCell cel0 = row.createCell(13); XSSFComment comment=p.createCellComment(new XSSFClientAnchor(0,0,0,0,(short)0,0,(short)2,4)); comment.setString(new XSSFRichTextString("選填項\r\n最多512個字符")); cel0.setCellValue("名稱"); cel0.setCellComment(comment); XSSFCell cel1 = row.createCell(14); XSSFComment comment1=p.createCellComment(new XSSFClientAnchor(0,0,0,0,(short)1,0,(short)3,4)); comment1.setString(new XSSFRichTextString("選填項\r\n最多512個字符")); cel1.setCellValue("年齡"); cel1.setCellComment(comment1); // 批註相關 XSSFCell tmpCell = null; XSSFComment tmpComment = null; XSSFRichTextString tmpVal = new XSSFRichTextString("選填項\r\n最多512個字符"); int dx1 = 80; int dx2 = 140; short col1 = 15; // 批註開始的列,即15列 short col2 = 17; // 批註結束的列,即17列 // 動態建立列和列上的批註 for(int i = 1; i <= 5; i++) { tmpCell = row.createCell(row.getLastCellNum()); tmpComment = p.createCellComment(new XSSFClientAnchor(dx1,0,dx2,0, col1,0, col2,4)); tmpCell.setCellValue("擴展裂-" + i); tmpComment.setString(tmpVal); col1++; col2++; } setResponseHeader(resp, "用戶表.xlsx"); OutputStream tmpOutputStream = resp.getOutputStream(); workbook.write(tmpOutputStream); tmpOutputStream.flush(); tmpOutputStream.close(); }
注意: 建立批註的類 XSSFClientAnchor 的構造參數有四個 :
public XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2){....}
它們的做用以下:
dx1,dy1 :起始單元格中的 x, y 座標.
dx2,dy2 :結束單元格中的 x , y 座標
col1,row1 :指定起始的單元格,下標從0開始
col2,,row2 :指定結束的單元格 ,下標從0開始