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文件的例子:
//創建HSSFWorkbook對象 HSSFWorkbook wb = new HSSFWorkbook(); //創建HSSFSheet對象 HSSFSheet sheet = wb.createSheet("sheet0"); //創建HSSFRow對象 HSSFRow row = sheet.createRow(0); //創建HSSFCell對象 HSSFCell cell=row.createCell(0); //設置單元格的值 cell.setCellValue("單元格中的中文"); //輸出Excel文件 FileOutputStream output=new FileOutputStream("d:\\workbook.xls"); wkb.write(output); output.flush();
HSSF讀取文件同樣還是使用這幾個對象,只是把相應的createXXX方法變成了getXXX方法即可。可見只要理解了其中原理,不管是讀還是寫亦或是特定格式都可以輕松實現,正所謂知其然更要知其所以然。
2:導出Excel應用實例:
詳細api請參考:https://blog.csdn.net/xunwei0303/article/details/53213130
3:導出表格的工具類:
excelUtil:
1 package com.zhl.push.Utils; 2 3 import com.google.common.base.Strings; 4 import org.apache.poi.hssf.usermodel.*; 5 import org.apache.poi.hssf.util.HSSFColor; 6 import org.apache.poi.ss.usermodel.VerticalAlignment; 7 import org.apache.poi.ss.util.CellRangeAddress; 8 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 import java.io.OutputStream; 13 import java.math.BigDecimal; 14 import java.util.List; 15 import java.util.Map; 16 17 public class ExcelExportUtil { 18 //表頭 19 private String title; 20 //各個列的表頭 21 private String[] heardList; 22 //各個列的元素key值 23 private String[] heardKey; 24 //需要填充的數據信息 25 private List<Map> data; 26 //字體大小 27 private int fontSize = 14; 28 //行高 29 private int rowHeight = 30; 30 //列寬 31 private int columWidth = 200; 32 //工作表 33 private String sheetName = "sheet1"; 34 35 public String getTitle() { 36 return title; 37 } 38 39 public void setTitle(String title) { 40 this.title = title; 41 } 42 43 public String[] getHeardList() { 44 return heardList; 45 } 46 47 public void setHeardList(String[] heardList) { 48 this.heardList = heardList; 49 } 50 51 public String[] getHeardKey() { 52 return heardKey; 53 } 54 55 public void setHeardKey(String[] heardKey) { 56 this.heardKey = heardKey; 57 } 58 59 public List<Map> getData() { 60 return data; 61 } 62 63 public void setData(List<Map> data) { 64 this.data = data; 65 } 66 67 public int getFontSize() { 68 return fontSize; 69 } 70 71 public void setFontSize(int fontSize) { 72 this.fontSize = fontSize; 73 } 74 75 public int getRowHeight() { 76 return rowHeight; 77 } 78 79 public void setRowHeight(int rowHeight) { 80 this.rowHeight = rowHeight; 81 } 82 83 public int getColumWidth() { 84 return columWidth; 85 } 86 87 public void setColumWidth(int columWidth) { 88 this.columWidth = columWidth; 89 } 90 91 public String getSheetName() { 92 return sheetName; 93 } 94 95 public void setSheetName(String sheetName) { 96 this.sheetName = sheetName; 97 } 98 99 /** 100 * 開始導出數據信息 101 * 102 */ 103 public byte[] exportExport(HttpServletRequest request, HttpServletResponse response) throws IOException { 104 //檢查參數配置信息 105 checkConfig(); 106 //創建工作簿 107 HSSFWorkbook wb = new HSSFWorkbook(); 108 //創建工作表 109 HSSFSheet wbSheet = wb.createSheet(this.sheetName); 110 //設置默認行寬 111 wbSheet.setDefaultColumnWidth(20); 112 113 // 標題樣式(加粗,垂直居中) 114 HSSFCellStyle cellStyle = wb.createCellStyle(); 115 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中 116 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中 117 HSSFFont fontStyle = wb.createFont(); 118 fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 119 fontStyle.setBold(true); //加粗 120 fontStyle.setFontHeightInPoints((short)16); //設置標題字體大小 121 cellStyle.setFont(fontStyle); 122 123 //在第0行創建rows (表標題) 124 HSSFRow title = wbSheet.createRow((int) 0); 125 title.setHeightInPoints(30);//行高 126 HSSFCell cellValue = title.createCell(0); 127 cellValue.setCellValue(this.title); 128 cellValue.setCellStyle(cellStyle); 129 wbSheet.addMergedRegion(new CellRangeAddress(0,0,0,(this.heardList.length-1))); 130 //設置表頭樣式,表頭居中 131 HSSFCellStyle style = wb.createCellStyle(); 132 //設置單元格樣式 133 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 134 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 135 //設置字體 136 HSSFFont font = wb.createFont(); 137 font.setFontHeightInPoints((short) this.fontSize); 138 style.setFont(font); 139 //在第1行創建rows 140 HSSFRow row = wbSheet.createRow((int) 1); 141 //設置列頭元素 142 HSSFCell cellHead = null; 143 for (int i = 0; i < heardList.length; i++) { 144 cellHead = row.createCell(i); 145 cellHead.setCellValue(heardList[i]); 146 cellHead.setCellStyle(style); 147 } 148 149 //設置每格數據的樣式 (字體紅色) 150 HSSFCellStyle cellParamStyle = wb.createCellStyle(); 151 HSSFFont ParamFontStyle = wb.createFont(); 152 cellParamStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 153 cellParamStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 154 ParamFontStyle.setColor(HSSFColor.DARK_RED.index); //設置字體顏色 (紅色) 155 ParamFontStyle.setFontHeightInPoints((short) this.fontSize); 156 cellParamStyle.setFont(ParamFontStyle); 157 //設置每格數據的樣式2(字體藍色) 158 HSSFCellStyle cellParamStyle2 = wb.createCellStyle(); 159 cellParamStyle2.setAlignment(HSSFCellStyle.ALIGN_CENTER); 160 cellParamStyle2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 161 HSSFFont ParamFontStyle2 = wb.createFont(); 162 ParamFontStyle2.setColor(HSSFColor.BLUE.index); //設置字體顏色 (藍色) 163 ParamFontStyle2.setFontHeightInPoints((short) this.fontSize); 164 cellParamStyle2.setFont(ParamFontStyle2); 165 //開始寫入實體數據信息 166 int a = 2; 167 for (int i = 0; i < data.size(); i++) { 168 HSSFRow roww = wbSheet.createRow((int) a); 169 Map map = data.get(i); 170 HSSFCell cell = null; 171 for (int j = 0; j < heardKey.length; j++) { 172 cell = roww.createCell(j); 173 cell.setCellStyle(style); 174 Object valueObject = map.get(heardKey[j]); 175 String value = null; 176 if (valueObject == null) { 177 valueObject = ""; 178 } 179 if (valueObject instanceof String) { 180 //取出的數據是字符串直接賦值 181 value = (String) map.get(heardKey[j]); 182 } else if (valueObject instanceof Integer) { 183 //取出的數據是Integer 184 value = String.valueOf(((Integer) (valueObject)).floatValue()); 185 } else if (valueObject instanceof BigDecimal) { 186 //取出的數據是BigDecimal 187 value = String.valueOf(((BigDecimal) (valueObject)).floatValue()); 188 } else { 189 value = valueObject.toString(); 190 } 191 //設置單個單元格的字體顏色 192 if(heardKey[j].equals("ddNum") || heardKey[j].equals("sjNum")){ 193 if((Long)map.get("ddNum")!=null){ 194 if((Long)map.get("sjNum")==null){ 195 cell.setCellStyle(cellParamStyle); 196 } else if((Long) map.get("ddNum") != (Long) map.get("sjNum")){ 197 if ((Long) map.get("ddNum") > (Long) map.get("sjNum")) { 198 cell.setCellStyle(cellParamStyle); 199 } 200 if ((Long) map.get("ddNum") < (Long) map.get("sjNum")) { 201 cell.setCellStyle(cellParamStyle2); 202 } 203 }else { 204 cell.setCellStyle(style); 205 } 206 } 207 } 208 cell.setCellValue(Strings.isNullOrEmpty(value) ? "" : value); 209 } 210 a++; 211 } 212 213 //導出數據 214 try { 215 //設置Http響應頭告訴瀏覽器下載這個附件 216 response.setHeader("Content-Disposition", "attachment;Filename=" + System.currentTimeMillis() + ".xls"); 217 OutputStream outputStream = response.getOutputStream(); 218 wb.write(outputStream); 219 outputStream.close(); 220 return wb.getBytes(); 221 } catch (Exception ex) { 222 ex.printStackTrace(); 223 throw new IOException("導出Excel出現嚴重異常,異常信息:" + ex.getMessage()); 224 } 225 226 } 227 228 /** 229 * 檢查數據配置問題 230 * 231 * @throws IOException 拋出數據異常類 232 */ 233 protected void checkConfig() throws IOException { 234 if (heardKey == null || heardList.length == 0) { 235 throw new IOException("列名數組不能為空或者為NULL"); 236 } 237 238 if (fontSize < 0 || rowHeight < 0 || columWidth < 0) { 239 throw new IOException("字體、寬度或者高度不能為負值"); 240 } 241 242 if (Strings.isNullOrEmpty(sheetName)) { 243 throw new IOException("工作表表名不能為NULL"); 244 } 245 } 246 }
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); } }
通用Excel文件導出工具類
1:Excel格式
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; 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.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.util.CellRangeAddress; /** * @作者 yan * @創建日期 * @版本 V1.0 * @描述 Excel 導出通用工具類 */ public class ExcelUtil { public static byte[] export(String sheetTitle, String[] title, List<Object> list) { HSSFWorkbook wb = new HSSFWorkbook();//創建excel表 HSSFSheet sheet = wb.createSheet(sheetTitle); sheet.setDefaultColumnWidth(20);//設置默認行寬 //表頭樣式(加粗,水平居中,垂直居中) HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中 //設置邊框樣式 cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框 cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框 cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框 cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框 HSSFFont fontStyle = wb.createFont(); fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); cellStyle.setFont(fontStyle); //標題樣式(加粗,垂直居中) HSSFCellStyle cellStyle2 = wb.createCellStyle(); cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中 cellStyle2.setFont(fontStyle); //設置邊框樣式 cellStyle2.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框 cellStyle2.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框 cellStyle2.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框 cellStyle2.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框 //字段樣式(垂直居中) HSSFCellStyle cellStyle3 = wb.createCellStyle(); cellStyle3.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中 //設置邊框樣式 cellStyle3.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框 cellStyle3.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框 cellStyle3.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框 cellStyle3.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框 //創建表頭 HSSFRow row = sheet.createRow(0); row.setHeightInPoints(20);//行高 HSSFCell cell = row.createCell(0); cell.setCellValue(sheetTitle); cell.setCellStyle(cellStyle); sheet.addMergedRegion(new CellRangeAddress(0,0,0,(title.length-1))); //創建標題 HSSFRow rowTitle = sheet.createRow(1); rowTitle.setHeightInPoints(20); HSSFCell hc; for (int i = 0; i < title.length; i++) { hc = rowTitle.createCell(i); hc.setCellValue(title[i]); hc.setCellStyle(cellStyle2); } byte result[] = null; ByteArrayOutputStream out = null; try { //創建表格數據 Field[] fields; int i = 2; for (Object obj : list) { fields = obj.getClass().getDeclaredFields(); HSSFRow rowBody = sheet.createRow(i); rowBody.setHeightInPoints(20); int j = 0; for (Field f : fields) { f.setAccessible(true); Object va = f.get(obj); if (null == va) { va = ""; } hc = rowBody.createCell(j); hc.setCellValue(va.toString()); hc.setCellStyle(cellStyle3); j++; } i++; } out = new ByteArrayOutputStream(); wb.write(out); result = out.toByteArray(); } catch (Exception ex) { Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex); } finally{ try { if(null != out){ out.close(); } } catch (IOException ex) { Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex); } finally{ try { wb.close(); } catch (IOException ex) { Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex); } } } return result; } }
4:依賴包
commons-io-2.4.jar
poi-3.15.jar
=======================================================
如果需要使用模板來導出excel可以使用jxls:
官網:http://jxls.sourceforge.net/
可以參考博客: https://www.cnblogs.com/foxlee1024/p/7616987.html
https://blog.csdn.net/sinat_15769727/article/details/78898894