這一段時間,由於項目上線基於穩定,所以我這邊在基於我們一期迭代的分支上優化一部分我們之前沒有做的功能,報表導出。本身之前用的是3.5的版本,但是由於同事要寫導入,寫的代碼只有4.1.0的版本支持,所以無奈之下,只能自己看源碼把之前的工具類重寫一波。下面我們來看一下實現步驟。
1.導入jar
<!-- poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency>
2.編輯工具類
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.CellType; 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.ss.util.CellRangeAddress; public class ExportExcelUtil { /** * 創建表格標題 * * @param wb * Excel文檔對象 * @param sheet * 工作表對象 * @param headString * 標題名稱 * @param col * 標題占用列數 */ public static void createHeadTittle(HSSFWorkbook wb, HSSFSheet sheet, String headString, int col) { HSSFRow row = sheet.createRow(0); // 創建Excel工作表的行 HSSFCell cell = row.createCell(0); // 創建Excel工作表指定行的單元格 row.setHeight((short) 1000); // 設置高度 cell.setCellType(CellType.STRING); // 定義單元格為字符串類型 cell.setCellValue(new HSSFRichTextString(headString)); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, col)); // 指定標題合並區域 // 定義單元格格式,添加單元格表樣式,並添加到工作簿 HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER); // 指定單元格水平居中對齊 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 指定單元格垂直居中個對齊 cellStyle.setWrapText(true); // 指定單元格自動換行 // 設置單元格字體 HSSFFont font = wb.createFont(); font.setBold(true);//設置字體為粗體 font.setFontName("微軟雅黑"); font.setColor(HSSFColorPredefined.BLACK.getIndex()); font.setFontHeightInPoints((short) 16); // 字體大小 cellStyle.setFont(font); cell.setCellStyle(cellStyle); } /** * 創建表頭 * * @param wb * Excel文檔對象 * @param sheet * 工作表對象 * @param thead * 表頭內容 * @param sheetWidth * 每一列寬度 */ public static void createThead(HSSFWorkbook wb, HSSFSheet sheet, String[] thead, int[] sheetWidth) { HSSFRow row1 = sheet.createRow(1); row1.setHeight((short) 600); // 定義單元格格式,添加單元格表樣式,並添加到工作簿 HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中對齊 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中對齊 cellStyle.setWrapText(true); //設置背景色灰色25% cellStyle.setFillForegroundColor(HSSFColorPredefined.GREY_25_PERCENT.getIndex()); // 設置背景色 cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cellStyle.setBorderRight(BorderStyle.THIN); // 設置右邊框類型 cellStyle.setRightBorderColor(HSSFColorPredefined.BLACK.getIndex()); // 設置右邊框顏色 // 設置單元格字體 HSSFFont font = wb.createFont(); font.setBold(true);//設置字體為粗體 font.setFontName("宋體"); font.setFontHeightInPoints((short) 10); cellStyle.setFont(font); // 設置表頭內容 for (int i = 0; i < thead.length; i++) { HSSFCell cell1 = row1.createCell(i); cell1.setCellType(CellType.STRING);//定義單元格為字符串類型 cell1.setCellValue(new HSSFRichTextString(thead[i])); cell1.setCellStyle(cellStyle); } // 設置每一列寬度 for (int i = 0; i < sheetWidth.length; i++) { sheet.setColumnWidth(i, sheetWidth[i]); } } /** * 填入數據 * * @param wb * // Excel文檔對象 * @param sheet * // 工作表對象 * @param result * // 表數據 */ public static void createTable(HSSFWorkbook wb, HSSFSheet sheet, List<LinkedHashMap<String, String>> result) { // 定義單元格格式,添加單元格表樣式,並添加到工作薄 HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setWrapText(true); // 單元格字體 HSSFFont font = wb.createFont(); font.setFontName("宋體"); font.setFontHeightInPoints((short) 10); cellStyle.setFont(font); cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中 // 循環插入數據 for (int i = 0; i < result.size(); i++) { HSSFRow row = sheet.createRow(i + 2); row.setHeight((short) 400); // 設置高度 HSSFCell cell = null; int j = 0; for (String key : (result.get(i).keySet())) { cell = row.createCell(j); cell.setCellStyle(cellStyle); cell.setCellValue(new HSSFRichTextString(result.get(i).get(key))); j++; } } } }
低版本工具類
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.util.CellRangeAddress; public class ExportExcelUtil3 { /** * 創建表格標題 * * @param wb * Excel文檔對象 * @param sheet * 工作表對象 * @param headString * 標題名稱 * @param col * 標題占用列數 */ @SuppressWarnings("deprecation") public static void createHeadTittle(HSSFWorkbook wb, HSSFSheet sheet, String headString, int col) { HSSFRow row = sheet.createRow(0); // 創建Excel工作表的行 HSSFCell cell = row.createCell(0); // 創建Excel工作表指定行的單元格 row.setHeight((short) 1000); // 設置高度 cell.setCellType(HSSFCell.ENCODING_UTF_16); // 定義單元格為字符串類型 cell.setCellValue(new HSSFRichTextString(headString)); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, col)); // 指定標題合並區域 // 定義單元格格式,添加單元格表樣式,並添加到工作簿 HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格居中對齊 cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 指定單元格垂直居中個對齊 cellStyle.setWrapText(true); // 指定單元格自動換行 // 設置單元格字體 HSSFFont font = wb.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); font.setFontName("微軟雅黑"); font.setFontHeightInPoints((short) 16); // 字體大小 cellStyle.setFont(font); cell.setCellStyle(cellStyle); } /** * 創建表頭 * * @param wb * Excel文檔對象 * @param sheet * 工作表對象 * @param thead * 表頭內容 * @param sheetWidth * 每一列寬度 */ @SuppressWarnings("deprecation") public static void createThead(HSSFWorkbook wb, HSSFSheet sheet, String[] thead, int[] sheetWidth) { HSSFRow row1 = sheet.createRow(1); row1.setHeight((short) 600); // 定義單元格格式,添加單元格表樣式,並添加到工作簿 HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); cellStyle.setWrapText(true); cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); // 設置背景色 cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); // 設置右邊框類型 cellStyle.setRightBorderColor(HSSFColor.BLACK.index); // 設置右邊框顏色 // 設置單元格字體 HSSFFont font = wb.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); font.setFontName("宋體"); font.setFontHeightInPoints((short) 10); cellStyle.setFont(font); // 設置表頭內容 for (int i = 0; i < thead.length; i++) { HSSFCell cell1 = row1.createCell(i); cell1.setCellType(HSSFCell.ENCODING_UTF_16); cell1.setCellValue(new HSSFRichTextString(thead[i])); cell1.setCellStyle(cellStyle); } // 設置每一列寬度 for (int i = 0; i < sheetWidth.length; i++) { sheet.setColumnWidth(i, sheetWidth[i]); } } /** * 填入數據 * * @param wb * // Excel文檔對象 * @param sheet * // 工作表對象 * @param result * // 表數據 */ @SuppressWarnings("deprecation") public static void createTable(HSSFWorkbook wb, HSSFSheet sheet, List<LinkedHashMap<String, String>> result) { // 定義單元格格式,添加單元格表樣式,並添加到工作薄 HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setWrapText(true); // 單元格字體 HSSFFont font = wb.createFont(); font.setFontName("宋體"); font.setFontHeightInPoints((short) 10); cellStyle.setFont(font); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中 // 循環插入數據 for (int i = 0; i < result.size(); i++) { HSSFRow row = sheet.createRow(i + 2); row.setHeight((short) 400); // 設置高度 HSSFCell cell = null; int j = 0; for (String key : (result.get(i).keySet())) { cell = row.createCell(j); cell.setCellStyle(cellStyle); cell.setCellValue(new HSSFRichTextString(result.get(i).get(key))); j++; } } } public static void main(String[] args) { //測試hashmap treemap linkedhashmap之間的順序 /*Map<String, String> map=new HashMap<>(); System.out.println("hashmap排序"); add_keyvalue(map); TreeMap<String, String> map2=new TreeMap<>(); System.out.println("treemap排序"); add_keyvalue(map2); LinkedHashMap<String, String> map3=new LinkedHashMap<>(); System.out.println("linkedhash排序"); add_keyvalue(map3);*/ // 1.封裝數據 List<ExportExcelView> list = new LinkedList<>(); ExportExcelView b1 = new ExportExcelView(); b1.setDeclsno("201810251706470169854601"); b1.setDecdt("2018-09-22"); b1.setEleacno("1209394999"); b1.setCustName("張三"); b1.setEntName("正信廣電"); b1.setSaleName("郭啟銘"); b1.setSaleTel("17342064227"); b1.setRealsumretbal("1000"); b1.setDecutionFee("100"); ExportExcelView b2 = new ExportExcelView(); b2.setDeclsno("201810251706470176052618"); b2.setDecdt("2018-09-22"); b2.setEleacno("1209394999"); b2.setCustName("趙四"); b2.setEntName("正信廣電"); b2.setSaleName("郭啟銘"); b2.setSaleTel("17342064227"); b2.setRealsumretbal("2000"); b2.setDecutionFee("200"); list.add(b1); list.add(b2); // 實體類轉換為map List<LinkedHashMap<String, String>> result = new ArrayList<>(); LinkedHashMap<String, String> map = new LinkedHashMap<>(); for (ExportExcelView e : list) { map.put("declsno", e.getDeclsno()); map.put("decdt", e.getDecdt()); map.put("eleacno", e.getEleacno()); map.put("custName",e.getCustName()); map.put("entName",e.getEntName()); map.put("saleName",e.getSaleName()); map.put("saleTel",e.getSaleTel()); map.put("realsumretbal",e.getRealsumretbal()); map.put("decutionFee",e.getDecutionFee()); result.add(map); } // 2.定義變量值 創建Excel文件 String fileName = "正信廣電_201809代扣費用表.xls"; // 定義文件名 String headString = "正信廣電_201809代扣費用表"; // 定義表格標題 String sheetName = "正信廣電_201809代扣費用表"; // 定義工作表表名 String filePath = "D:\\"; // 文件本地保存路徑 String[] thead = { "扣款流水", "扣款日期", "發電戶號", "用戶姓名", "開發商", "業務員姓名","業務員手機號","扣款金額(元)", "代扣費用(元)" }; int[] sheetWidth = { 7500, 4000, 3000, 3000, 4000, 3000, 5000, 5000,5000}; // 定義每一列寬度 HSSFWorkbook wb = new HSSFWorkbook(); // 創建Excel文檔對象 HSSFSheet sheet = wb.createSheet(sheetName); // 創建工作表 // 3.生成表格 // ①創建表格標題 createHeadTittle(wb, sheet, headString, 8); // result.get(0).size() - 1為表格占用列數,從0開始 // ②創建表頭 createThead(wb, sheet, thead, sheetWidth); // ③填入數據 createTable(wb, sheet, result); FileOutputStream fos; try { fos = new FileOutputStream(new File(filePath + fileName)); wb.write(fos); fos.close(); wb.close(); System.out.println("導出excel成功"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } public static void add_keyvalue(Map<String, String> map){ map.put("351", "11"); map.put("512", "222"); map.put("853", "333"); map.put("125", "333"); map.put("341", "333"); Iterator<String> iterator=map.keySet().iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } }
3.測試導出
①.導出對象
import lombok.Data; @Data public class ExportExcelView { private String declsno; private String decdt; private String eleacno; private String custName; private String entName; private String saleName; private String saleTel; private String realsumretbal; private String decutionFee; }
②.寫入報表
public static void main(String[] args) { // 1.封裝數據 List<ExportExcelView> list = new LinkedList<>(); ExportExcelView b1 = new ExportExcelView(); b1.setDeclsno("201810251706470169854601"); b1.setDecdt("2018-09-22"); b1.setEleacno("1209394999"); b1.setCustName("張三"); b1.setEntName("正信廣電"); b1.setSaleName("郭啟銘"); b1.setSaleTel("17342064227"); b1.setRealsumretbal("1000"); b1.setDecutionFee("100"); ExportExcelView b2 = new ExportExcelView(); b2.setDeclsno("201810251706470176052618"); b2.setDecdt("2018-09-22"); b2.setEleacno("1209394999"); b2.setCustName("趙四"); b2.setEntName("正信廣電"); b2.setSaleName("郭啟銘"); b2.setSaleTel("17342064227"); b2.setRealsumretbal("2000"); b2.setDecutionFee("200"); list.add(b1); list.add(b2); // 實體類轉換為map List<LinkedHashMap<String, String>> result = new ArrayList<>(); LinkedHashMap<String, String> map = new LinkedHashMap<>(); for (ExportExcelView e : list) { map.put("declsno", e.getDeclsno()); map.put("decdt", e.getDecdt()); map.put("eleacno", e.getEleacno()); map.put("custName",e.getCustName()); map.put("entName",e.getEntName()); map.put("saleName",e.getSaleName()); map.put("saleTel",e.getSaleTel()); map.put("realsumretbal",e.getRealsumretbal()); map.put("decutionFee",e.getDecutionFee()); result.add(map); } // 2.定義變量值 創建Excel文件 String fileName = "正信廣電_201809代扣費用表.xls"; // 定義文件名 String headString = "正信廣電_201809代扣費用表"; // 定義表格標題 String sheetName = "正信廣電_201809代扣費用表"; // 定義工作表表名 String filePath = "D:\\"; // 文件本地保存路徑 String[] thead = { "扣款流水", "扣款日期", "發電戶號", "用戶姓名", "開發商", "業務員姓名","業務員手機號","扣款金額(元)", "代扣費用(元)" }; int[] sheetWidth = { 7500, 4000, 3000, 3000, 4000, 3000, 5000, 5000,5000}; // 定義每一列寬度 HSSFWorkbook wb = new HSSFWorkbook(); // 創建Excel文檔對象 HSSFSheet sheet = wb.createSheet(sheetName); // 創建工作表 // 3.生成表格 // ①創建表格標題 createHeadTittle(wb, sheet, headString, 8); // ②創建表頭 createThead(wb, sheet, thead, sheetWidth); // ③填入數據 createTable(wb, sheet, result); FileOutputStream fos; try { fos = new FileOutputStream(new File(filePath + fileName)); wb.write(fos); fos.close(); System.out.println("導出excel成功"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
③.運行效果
④.導出並下載
/** * 輸出創建的Excel * @param fileName * @param wb * @param resp */ private void respOutPutExcel(String fileName, HSSFWorkbook wb, HttpServletResponse resp) { ByteArrayOutputStream os = new ByteArrayOutputStream(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { wb.write(os); System.out.println("導出excel成功"); byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); // 設置response參數,可以打開下載頁面 resp.reset(); resp.setContentType("application/vnd.ms-excel;charset=utf-8"); resp.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out = resp.getOutputStream(); bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); }finally { try { if (bis != null) bis.close(); if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } } }
頁面寫法
/** * 導出報表 * @returns */ function exportExcel(){ //這里獲得一些要前台查詢的數據 這里不能用ajax的方式,用ajax方式請求,會直接輸出流 location.href= prefix +"/listOutPutExcel; }
<button id="outPutExcel" type="button" class="btn btn-primary" onclick="exportExcel()">導出</button>