java實現Excel數據導出:
目前,比較常用的實現Java導入、導出Excel的技術有兩種Jakarta POI和Java Excel
Jakarta POI 是一套用於訪問微軟格式文檔的Java API。Jakarta POI有很多組件組成,其中有用於操作Excel格式文件的HSSF和用於操作Word的HWPF,在各種組件中目前只有用於操作Excel的HSSF相對成熟。官方主頁http://poi.apache.org/index.html,API文檔http://poi.apache.org/apidocs/index.html
Jakarta POI HSSF API組件
HSSF(用於操作Excel的組件)提供給用戶使用的對象在rg.apache.poi.hssf.usermodel包中,主要部分包括Excel對象,樣式和格式,還有輔助操作。有以下幾種對象:
2.3 基本操作步驟
首先,理解一下一個Excel的文件的組織形式,一個Excel文件對應於一個workbook(HSSFWorkbook),一個workbook可以有多個sheet(HSSFSheet)組成,一個sheet是由多個row(HSSFRow)組成,一個row是由多個cell(HSSFCell)組成。
基本操作步驟:
下面來看一個動態生成Excel文件的例子:
1 //創建HSSFWorkbook對象
2 HSSFWorkbook wb = new HSSFWorkbook(); 3 //創建HSSFSheet對象
4 HSSFSheet sheet = wb.createSheet("sheet0"); 5 //創建HSSFRow對象
6 HSSFRow row = sheet.createRow(0); 7 //創建HSSFCell對象
8 HSSFCell cell=row.createCell(0); 9 //設置單元格的值
10 cell.setCellValue("單元格中的中文"); 11 //輸出Excel文件
12 FileOutputStream output=new FileOutputStream("d:\\workbook.xls"); 13 wkb.write(output); 14 output.flush();
HSSF讀取文件同樣還是使用這幾個對象,只是把相應的createXXX方法變成了getXXX方法即可。可見只要理解了其中原理,不管是讀還是寫亦或是特定格式都可以輕松實現,正所謂知其然更要知其所以然。
2:導出Excel應用實例:
<!--導出文件-->
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
3:導出表格的工具類:
excelUtil:
package com.zhl.push.Utils; import com.google.common.base.Strings; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.util.CellRangeAddress; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.math.BigDecimal; import java.util.List; import java.util.Map; public class ExcelExportUtil { //表頭 private String title; //各個列的表頭 private String[] heardList; //各個列的元素key值 private String[] heardKey; //需要填充的數據信息 private List<Map> data; //字體大小 private int fontSize = 14; //行高 private int rowHeight = 30; //列寬 private int columWidth = 200; //工作表 private String sheetName = "sheet1"; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String[] getHeardList() { return heardList; } public void setHeardList(String[] heardList) { this.heardList = heardList; } public String[] getHeardKey() { return heardKey; } public void setHeardKey(String[] heardKey) { this.heardKey = heardKey; } public List<Map> getData() { return data; } public void setData(List<Map> data) { this.data = data; } public int getFontSize() { return fontSize; } public void setFontSize(int fontSize) { this.fontSize = fontSize; } public int getRowHeight() { return rowHeight; } public void setRowHeight(int rowHeight) { this.rowHeight = rowHeight; } public int getColumWidth() { return columWidth; } public void setColumWidth(int columWidth) { this.columWidth = columWidth; } public String getSheetName() { return sheetName; } public void setSheetName(String sheetName) { this.sheetName = sheetName; } /** * 開始導出數據信息 * */ public byte[] exportExport(HttpServletRequest request, HttpServletResponse response) throws IOException { //檢查參數配置信息 checkConfig(); //創建工作簿 HSSFWorkbook wb = new HSSFWorkbook(); //創建工作表 HSSFSheet wbSheet = wb.createSheet(this.sheetName); //設置默認行寬 wbSheet.setDefaultColumnWidth(20); // 標題樣式(加粗,垂直居中) HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中 HSSFFont fontStyle = wb.createFont(); fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); fontStyle.setBold(true); //加粗 fontStyle.setFontHeightInPoints((short)16); //設置標題字體大小 cellStyle.setFont(fontStyle); //在第0行創建rows (表標題) HSSFRow title = wbSheet.createRow((int) 0); title.setHeightInPoints(30);//行高 HSSFCell cellValue = title.createCell(0); cellValue.setCellValue(this.title); cellValue.setCellStyle(cellStyle); wbSheet.addMergedRegion(new CellRangeAddress(0,0,0,(this.heardList.length-1))); //設置表頭樣式,表頭居中 HSSFCellStyle style = wb.createCellStyle(); //設置單元格樣式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //設置字體 HSSFFont font = wb.createFont(); font.setFontHeightInPoints((short) this.fontSize); style.setFont(font); //在第1行創建rows HSSFRow row = wbSheet.createRow((int) 1); //設置列頭元素 HSSFCell cellHead = null; for (int i = 0; i < heardList.length; i++) { cellHead = row.createCell(i); cellHead.setCellValue(heardList[i]); cellHead.setCellStyle(style); } //設置每格數據的樣式 (字體紅色) HSSFCellStyle cellParamStyle = wb.createCellStyle(); HSSFFont ParamFontStyle = wb.createFont(); cellParamStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); cellParamStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); ParamFontStyle.setColor(HSSFColor.DARK_RED.index); //設置字體顏色 (紅色) ParamFontStyle.setFontHeightInPoints((short) this.fontSize); cellParamStyle.setFont(ParamFontStyle); //設置每格數據的樣式2(字體藍色) HSSFCellStyle cellParamStyle2 = wb.createCellStyle(); cellParamStyle2.setAlignment(HSSFCellStyle.ALIGN_CENTER); cellParamStyle2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); HSSFFont ParamFontStyle2 = wb.createFont(); ParamFontStyle2.setColor(HSSFColor.BLUE.index); //設置字體顏色 (藍色) ParamFontStyle2.setFontHeightInPoints((short) this.fontSize); cellParamStyle2.setFont(ParamFontStyle2); //開始寫入實體數據信息 int a = 2; for (int i = 0; i < data.size(); i++) { HSSFRow roww = wbSheet.createRow((int) a); Map map = data.get(i); HSSFCell cell = null; for (int j = 0; j < heardKey.length; j++) { cell = roww.createCell(j); cell.setCellStyle(style); Object valueObject = map.get(heardKey[j]); String value = null; if (valueObject == null) { valueObject = ""; } if (valueObject instanceof String) { //取出的數據是字符串直接賦值 value = (String) map.get(heardKey[j]); } else if (valueObject instanceof Integer) { //取出的數據是Integer value = String.valueOf(((Integer) (valueObject)).floatValue()); } else if (valueObject instanceof BigDecimal) { //取出的數據是BigDecimal value = String.valueOf(((BigDecimal) (valueObject)).floatValue()); } else { value = valueObject.toString(); } //設置單個單元格的字體顏色 if(heardKey[j].equals("ddNum") || heardKey[j].equals("sjNum")){ if((Long)map.get("ddNum")!=null){ if((Long)map.get("sjNum")==null){ cell.setCellStyle(cellParamStyle); } else if((Long) map.get("ddNum") != (Long) map.get("sjNum")){ if ((Long) map.get("ddNum") > (Long) map.get("sjNum")) { cell.setCellStyle(cellParamStyle); } if ((Long) map.get("ddNum") < (Long) map.get("sjNum")) { cell.setCellStyle(cellParamStyle2); } }else { cell.setCellStyle(style); } } } cell.setCellValue(Strings.isNullOrEmpty(value) ? "" : value); } a++; } //導出數據 try { //設置Http響應頭告訴瀏覽器下載這個附件 response.setHeader("Content-Disposition", "attachment;Filename=" + System.currentTimeMillis() + ".xls"); OutputStream outputStream = response.getOutputStream(); wb.write(outputStream); outputStream.close(); return wb.getBytes(); } catch (Exception ex) { ex.printStackTrace(); throw new IOException("導出Excel出現嚴重異常,異常信息:" + ex.getMessage()); } } /** * 檢查數據配置問題 * * @throws IOException 拋出數據異常類 */ protected void checkConfig() throws IOException { if (heardKey == null || heardList.length == 0) { throw new IOException("列名數組不能為空或者為NULL"); } if (fontSize < 0 || rowHeight < 0 || columWidth < 0) { throw new IOException("字體、寬度或者高度不能為負值"); } if (Strings.isNullOrEmpty(sheetName)) { throw new IOException("工作表表名不能為NULL"); } } }
service :
@Override public void queryProjectInfoBySchemeId(HttpServletResponse response, HttpServletRequest request, String schemeId, String pushDate) throws IOException { List<Map> maps = pushMonitorDao.queryProjectInfoBySchemeId(schemeId, pushDate); if(maps!=null && maps.size()>0){ String companyName = pushMonitorDao.queryCompanyNameBySchemeId(schemeId); String sheetTitle = companyName; String [] title = new String[]{"城市","項目名字","合同","實際"}; //設置表格表頭字段 String [] properties = new String[]{"city","projectName","ddNum","sjNum"}; // 查詢對應的字段 ExcelExportUtil excelExport2 = new ExcelExportUtil(); excelExport2.setData(maps); excelExport2.setHeardKey(properties); excelExport2.setFontSize(14); excelExport2.setSheetName(sheetTitle); excelExport2.setTitle(sheetTitle); excelExport2.setHeardList(title); excelExport2.exportExport(request, response); } }
由於上面的代碼不夠靈活,下面加以改進:
ExcelExportUtil:
package com.zhl.push.Utils; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Map; public class ExcelExportUtil { //excel表對象 private Workbook workbook; //工作表對象 private Sheet sheet; //標題 private String title; //sheet各個列的表頭 private String[] headList; //各個列的元素key值 private String[] headKey; //sheet需要填充的數據信息 private List<Map> data; //工作表名稱 // private String sheetName = "sheet1"; //工作表列寬 private Integer columnWidth=20; //工作表行高 private Integer rowHeight=10; //字體大小 private int fontSize = 14; public int getFontSize() { return fontSize; } public void setFontSize(int fontSize) { this.fontSize = fontSize; } public Integer getColumnWidth() { return columnWidth; } public void setColumnWidth(Integer columnWidth) { this.columnWidth = columnWidth; } public Integer getRowHeight() { return rowHeight; } public void setRowHeight(Integer rowHeight) { this.rowHeight = rowHeight; } public Workbook getWorkbook() { return workbook; } public void setWorkbook(Workbook workbook) { this.workbook = workbook; } public Sheet getSheet() { return sheet; } public void setSheet(Sheet sheet) { this.sheet = sheet; } public String[] getHeadKey() { return headKey; } public void setHeadKey(String[] headKey) { this.headKey = headKey; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String[] getHeadList() { return headList; } public void setHeadList(String[] headList) { this.headList = headList; } public List<Map> getData() { return data; } public void setData(List<Map> data) { this.data = data; } /** * @return * * @Author * @Description //TODO 插入數據到表格(body) * @Date 2019/7/26 17:28 * @Param startRow: 開始插入數據的行 */ public void writeMainData(Integer startRow) throws IOException { //設置每格數據的樣式 (字體紅色) CellStyle fontRed = ExcelStyleUtilFor2003.getFontStyle(this.workbook, this.fontSize, HSSFColor.RED.index); //設置每格數據的樣式2(字體藍色) CellStyle fontBlue = ExcelStyleUtilFor2003.getFontStyle(this.workbook, this.fontSize, HSSFColor.BLUE.index); //設置body樣式 CellStyle bodyStyle = ExcelStyleUtilFor2003.getBodyStyle(this.workbook, this.fontSize); //開始寫入實體數據信息 if (data.size() > 0 && null != data.get(0)) { for (int i = 0; i < data.size(); i++) { Row row = this.sheet.createRow(startRow); Map map = data.get(i); map.put("index",i); map.put("des","無"); for (int j = 0; j < headKey.length; j++) { Cell cell = row.createCell(j); //設置單個單元格的字體顏色 if (headKey[j].equals("ddNum") || headKey[j].equals("sjNum")) { if (null != map.get("ddNum") && Integer.parseInt(map.get("ddNum").toString()) != 0) { if (null == map.get("sjNum") || Integer.parseInt(map.get("sjNum").toString()) == 0) { cell.setCellStyle(fontRed); } else if (Integer.parseInt(map.get("ddNum").toString()) != Integer.parseInt(map.get("sjNum").toString())) { if (Integer.parseInt((String) map.get("ddNum")) > Integer.parseInt((String) map.get("sjNum"))) { cell.setCellStyle(fontRed); } else { cell.setCellStyle(fontBlue); } } else { cell.setCellStyle(bodyStyle); } } else { if (Integer.parseInt(map.get("ddNum").toString()) < Integer.parseInt(map.get("sjNum").toString())) { cell.setCellStyle(fontBlue); } else { cell.setCellStyle(bodyStyle); } } cell.setCellValue(Integer.parseInt(map.get(headKey[j]).toString())); } else { Object value = map.get(headKey[j]); if (null == value) { String valueN = ""; cell.setCellValue(valueN); } else if (value instanceof Integer) { Integer valueInt = Integer.valueOf(value.toString()); cell.setCellValue(valueInt); } else if (value instanceof String) { String valueStr = String.valueOf(value); cell.setCellValue(valueStr); } } } startRow++; } } } /** * @return * @param null * @Author * @Description //TODO 添加表格標題 * @Date 2019/7/26 17:58 * @Param */ public void writeTitle() throws IOException { checkConfig(); //設置默認行寬 this.sheet.setDefaultColumnWidth(20); //在第0行創建rows (表標題) Row title = this.sheet.createRow(0); title.setHeightInPoints(this.rowHeight);//行高 Cell cell = title.createCell(0); cell.setCellValue(this.title); CellStyle cellStyle = ExcelStyleUtilFor2003.getTitleStyle(this.workbook,true,16); cell.setCellStyle(cellStyle); ExcelStyleUtilFor2003.mergeCell(sheet,0,0,0, (this.headList.length - 1)); } /** * @Author * @Description //TODO 添加表頭 * @Date 2019/7/26 15:41 * @Param headRowNum: 添加表頭所在行數 * @return * */ public void writeTableHead(String[] head, CellStyle cellStyle,Integer headRowNum) { Row row = this.sheet.createRow(headRowNum); if (head.length > 0) { for (int i = 0; i < head.length; i++) { Cell cell = row.createCell(i); cell.setCellValue(head[i]); cell.setCellStyle(cellStyle); } } } /** * 檢查數據配置問題 * * @throws IOException 拋出數據異常類 */ protected void checkConfig() throws IOException { if (headKey == null || headList.length == 0) { throw new IOException("列名數組不能為空或者為NULL"); } if (fontSize < 0) { throw new IOException("字體不能為負值"); } } /** * @Author * @Description //TODO 寫入拼接好的數據,不需要通過表頭key值來對應 * @Date 2019/7/27 11:01 * @Param * @return * @param null */ public void writeMainData(List<List<String>> datas,Integer startRow){ if(datas.size()>0){ for(List<String> data : datas){ Row row = this.sheet.createRow(startRow); for(int i =0; i<data.size(); i++){ Cell cell = row.createCell(i); cell.setCellValue(data.get(i)); CellStyle cellStyle = ExcelStyleUtilFor2003.setCellBorder(this.workbook); cell.setCellStyle(cellStyle); } startRow++; } } } public static void setResponseInfo(HttpServletResponse response, Workbook wb) throws IOException { //導出數據 try { //設置Http響應頭告訴瀏覽器下載這個附件 response.setHeader("Content-Disposition", "attachment;Filename=" + System.currentTimeMillis() + ".xls"); OutputStream outputStream = response.getOutputStream(); wb.write(outputStream); outputStream.close(); } catch (Exception ex) { ex.printStackTrace(); throw new IOException("導出Excel出現嚴重異常,異常信息:" + ex.getMessage()); } } }
我們把樣式單獨提取成一個工具類:
package com.zhl.push.Utils; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; /** * @Author * @ClassName ExcelStyleUtilFor2003 * @Description TODO * @Date 2019/7/26 14:16 * @Version 1.0 */ public class ExcelStyleUtilFor2003 { /** * @return * @param null * @Author * @Description //TODO 樣式居中 * @Date 2019/7/26 14:51 * @Param */ public static void center(CellStyle cellStyle) { cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中 } /** * @return * @param null * @Author * @Description //TODO 單元格合並 * @Date 2019/7/26 14:54 * @Param wbSheet :工作表對象 * firstRow :合並的開始行 * lastRow:合並的結束行 * firstCol: 合並的開始列 * lastColL: 合並的結束列 */ public static void mergeCell(Sheet wbSheet, int firstRow, int lastRow, int firstCol, int lastCol) { wbSheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol)); } /** * @return * * @Author * @Description //TODO 標題樣式 :加粗,垂直居中 * @Date 2019/7/26 14:21 * @Param */ public static CellStyle getTitleStyle(Workbook wb, Boolean isBold, int FontISize) { // 標題樣式(加粗,垂直居中) CellStyle cellStyle = wb.createCellStyle(); center(cellStyle); Font font = wb.createFont(); font.setBold(isBold); //加粗 font.setFontHeightInPoints((short) FontISize); //設置標題字體大小 cellStyle.setFont(font); return cellStyle; } /** * @return * * @Author * @Description //TODO 表頭樣式 * @Date 2019/7/26 14:30 * @Param */ public static CellStyle getHeadStyle(Workbook wb, int fontSize) { CellStyle cellStyle = wb.createCellStyle(); cellStyle.setFillForegroundColor(HSSFColor.AQUA.index);//設置表頭的背景顏色 cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cellStyle.setFillBackgroundColor(HSSFColor.AQUA.index); //設置表頭的背景顏色 center(cellStyle); //設置字體 Font font = setFont(wb, fontSize); cellStyle.setFont(font); return cellStyle; } /** * @return * @param null * @Author * @Description //TODO body通用樣式: 居中,設置字體大小 * @Date 2019/7/26 15:11 * @Param */ public static CellStyle getBodyStyle(Workbook wb, int fontSize) { CellStyle cellStyle = wb.createCellStyle(); //設置單元格樣式 center(cellStyle); Font font = setFont(wb, fontSize); cellStyle.setFont(font); return cellStyle; } /** * @return * @param null * @Author * @Description //TODO 設置單元格字體居中、並設置字體顏色 * @Date 2019/7/26 15:26 * @Param */ public static CellStyle getFontStyle(Workbook wb, int fontSize, short color) { CellStyle cellStyle = wb.createCellStyle(); Font font = setFont(wb, fontSize, color); center(cellStyle); cellStyle.setFont(font); return cellStyle; } /** * @return * @param null * @Author * @Description //TODO 設置單元格字體 * @Date 2019/7/26 15:16 * @Param */ public static Font setFont(Workbook wb, int fontSize, short color) { //設置字體 Font font = wb.createFont(); font.setColor(color); font.setFontHeightInPoints((short) fontSize); return font; } public static Font setFont(Workbook wb, int fontSize) { //設置字體 Font font = wb.createFont(); font.setFontHeightInPoints((short) fontSize); return font; } /** * @Author * @Description //TODO 設置cell邊框 * @Date 2019/7/27 16:16 * @Param * @return * @param null */ public static CellStyle setCellBorder(Workbook workbook){ CellStyle cellStyle = workbook.createCellStyle(); //設置了邊框屬性 cellStyle.setBorderBottom(BorderStyle.THIN); //下邊框 cellStyle.setBorderLeft(BorderStyle.THIN);//左邊框 cellStyle.setBorderTop(BorderStyle.THIN);//上邊框 cellStyle.setBorderRight(BorderStyle.THIN);//右邊框 //設置邊框顏色黑色 cellStyle.setTopBorderColor(HSSFColor.BLACK.index); cellStyle.setBottomBorderColor(HSSFColor.BLACK.index); cellStyle.setLeftBorderColor(HSSFColor.BLACK.index); cellStyle.setRightBorderColor(HSSFColor.BLACK.index); return cellStyle; } }
=======================================================
如果需要使用模板來導出excel可以使用jxls:
官網:http://jxls.sourceforge.net/
可以參考博客: https://www.cnblogs.com/foxlee1024/p/7616987.html
https://blog.csdn.net/sinat_15769727/article/details/78898894