1.POI簡介html
Jakarta POI 是一套用於訪問微軟格式文檔的Java API.
組件HWPF用於操做Word的;
組件HSSF用於操做Excel格式文件.
2.經常使用組件
HSSFWorkbook -- excel的文檔對象
HSSFSheet -- excel的表單
HSSFRow -- excel的行
HSSFCell -- excel的格子單元
HSSFHeader -- sheet頭
HSSFFooter -- sheet尾(只有打印的時候才能看到效果)
HSSFDataFormat -- 日期格式
HSSFCellStyle -- cell樣式
HSSFFont -- excel字體
HSSFColor -- 顏色
HSSFDateUtil -- 日期
HSSFPrintSetup -- 打印
HSSFErrorConstants -- 錯誤信息表
合併單元格,構造參數依次表示起始行,截止行,起始列,截止列
eg:sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
設置單元格樣式時,先建立樣式,再指定到單元格。
樣式可指定對齊方式、背景填充方式及顏色、上下左右邊框樣式及顏色
設置單元格的填充方式,以及前景顏色和背景顏色時注意:
a.若是須要前景顏色或背景顏色,必定要指定填充方式,二者順序無所謂;
b.若是同時存在前景顏色和背景顏色,前景顏色的設置要寫在前面;
c.前景顏色不是字體顏色。 java
3.結構說明
Excel <-- 一 工做空間(workbook)
workbook <-- 多 工做表(sheet)
sheet <-- 多 行(row) + 多列(cell)web
4.操做步驟
a、用HSSFWorkbook打開或者建立Excel文件對象
b、用HSSFWorkbook對象返回或者建立Sheet對象
c、用Sheet對象返回行對象,用行對象獲得Cell對象
d、對Cell對象讀寫spring
5.實例
第一種方法 固定導出字段導出excel;
第二種方法 用配置的方式將導出字段存儲數庫中導出excel,可重用;數據庫
pom.xmlapache
<!-- json轉換工具 --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <!-- easypoi 導入導出插件--> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>3.0.3</version> </dependency> <!-- POI,excel導入須要的 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
IExportExcleService.java 接口json
package com.wulss.jakartapoi.hssf; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public interface IExportExcelService { /** * 第一種 直接導出excle * @param req * @param resp * @param list 要導出的數據 */ public void exportExcelWithSimple(HttpServletRequest req,HttpServletResponse resp,List<UserConsumeDetailRecord> list); /** * 第二種 根據exportKey查詢出要導出的字段,並匹配list每一個類中字段來導出excel,只需維護數據庫,便可實現該方法的重用 * @param exportKey 數據庫中存儲的導出英文名 * @param fileName 文件名 * @param list 要導出的數據 * @param req * @param resp */ public void exportExcelWithDispose(String exportKey,String fileName,List<?> list,HttpServletRequest req,HttpServletResponse resp); }
ExportExcleServiceImpl.java 實現類mybatis
package com.wulss.jakartapoi.hssf; import java.text.SimpleDateFormat; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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.util.CellRangeAddress; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import net.sf.json.JSONArray; import net.sf.json.JSONObject; @Service public class ExportExcelServiceImpl extends ExportExcelBaseService implements IExportExcelService{ @Autowired private ExportMapper exportMapper; @Override public void exportExcelWithSimple(HttpServletRequest req,HttpServletResponse resp,List<UserConsumeDetailRecord> list){ String fileName = "我的消費明細表" + UUID.randomUUID().toString(); try { //工做空間 HSSFWorkbook workbook = new HSSFWorkbook(); //第1張工做表 HSSFSheet sheet1 = workbook.createSheet("我的消費明細"); sheet1.setDefaultRowHeightInPoints(20);//行高 sheet1.setDefaultColumnWidth(20);//列寬 //行標題 HSSFRow titleRow = sheet1.createRow(0); titleRow.createCell(0).setCellValue("我的消費明細表"); sheet1.addMergedRegion(new CellRangeAddress(0,0,0,4));////合併單元格 //行表頭 HSSFRow headRow = sheet1.createRow(sheet1.getLastRowNum() + 1); headRow.createCell(0).setCellValue("序號"); headRow.createCell(headRow.getLastCellNum()).setCellValue("用戶姓名"); headRow.createCell(headRow.getLastCellNum()).setCellValue("消費金額"); headRow.createCell(headRow.getLastCellNum()).setCellValue("消費時間"); headRow.createCell(headRow.getLastCellNum()).setCellValue("消費項目"); //行表頭單元格設置樣式 for(int h = 0; h < headRow.getLastCellNum() ; h ++) { headRow.getCell(h).setCellStyle(super.getCellStyle(workbook)); } //行數據體 int index = 1; HSSFRow bodyRow = null; for(UserConsumeDetailRecord bean:list) { bodyRow = sheet1.createRow(sheet1.getLastRowNum() + 1); bodyRow.createCell(0).setCellValue(index ++ ); bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(bean.getUserName()); bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(bean.getConsumeAmount()); bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(bean.getConsumeDate()));//.split("\\.")[0] bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(bean.getConsumeTitle()); } //輸出 super.outExcelStream(resp, workbook, fileName); //將生成的excel文件寫到磁盤 // FileOutputStream fos = new FileOutputStream(fileName + ".xls"); // workbook.write(fos); // fos.close(); //從磁盤刪除刪除文件 // super.deleteFileDir(fileName + ".xls"); }catch(Exception e){ e.printStackTrace(); } } @Override public void exportExcelWithDispose(String exportKey,String fileName,List<?> list,HttpServletRequest req,HttpServletResponse resp){ //查詢一表 級聯 獲取多表集合 List<ExportFieldBean> fieldBeanList = exportMapper.getExportByExportKey(exportKey).getFieldBeanList(); try { //工做空間 HSSFWorkbook workbook = new HSSFWorkbook(); //第1張工做表 HSSFSheet sheet1 = workbook.createSheet("我的消費明細"); sheet1.setDefaultRowHeightInPoints(20);//行高 sheet1.setDefaultColumnWidth(20);//列寬 //行表頭 HSSFRow headRow = sheet1.createRow(0); headRow.createCell(0).setCellValue("序號"); headRow.getCell(0).setCellStyle(super.getCellStyle(workbook)); //建立行表頭單元格並設置樣式 for(ExportFieldBean fieldBean:fieldBeanList) { headRow.createCell(headRow.getLastCellNum()).setCellValue(fieldBean.getExportName());//賦值 headRow.getCell(headRow.getLastCellNum()).setCellStyle(super.getCellStyle(workbook));//樣式 } //建立行數據體 int index = 1; HSSFRow bodyRow = null; JSONArray jsonArray = JSONArray.fromObject(list);// --賦值(先轉json, 再賦值, 通用性高) for(Object obj:jsonArray) { bodyRow = sheet1.createRow(sheet1.getLastRowNum() + 1); bodyRow.createCell(0).setCellValue(index ++ ); for(ExportFieldBean fieldBean:fieldBeanList) { bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(((JSONObject)obj).get(fieldBean.getExportCode()) + "");//賦值 // bodyRow.getCell(bodyRow.getLastCellNum()).setCellStyle(super.getCellStyle(workbook));//樣式 } } //輸出 super.outExcelStream(resp, workbook, fileName); }catch(Exception e){ e.printStackTrace(); } } }
ExportExcelBaseService.java 基礎類app
package com.wulss.jakartapoi.hssf; import java.io.File; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.stereotype.Component; @Component public class ExportExcelBaseService { /** * 獲取設置好的樣式 * @param workbook 工做空間 * @return */ public HSSFCellStyle getCellStyle(HSSFWorkbook workbook) { HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//單元格-垂直居中 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//單元格-水平居中 cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS);//背景色-方塊填充 cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);//前背景色-天藍 cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);//後背景色-淺黃 cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT);//底邊框樣式-傾斜斷點 cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index);//底邊框顏色-暗紅 cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));//日期顯示格式 // headRowCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@")); cellStyle.setFont(this.getFont(workbook));//設置字體 return cellStyle; } /** * 獲取設置好的字體 * @param workbook 工做空間 * @return */ public HSSFFont getFont(HSSFWorkbook workbook) { HSSFFont fontStyle = workbook.createFont(); fontStyle.setFontName("宋體");//名稱-宋體 fontStyle.setFontHeightInPoints((short)13);//高度-13 fontStyle.setColor(HSSFColor.WHITE.index);//顏色-白色 fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗 fontStyle.setItalic(true);//斜體 fontStyle.setUnderline(HSSFFont.U_SINGLE);//下劃線 return fontStyle; } /** * 經過流的方式輸出excle到頁面 * @param response 響應 * @param workbook 工做空間 * @param fileName 文件名 */ public void outExcelStream(HttpServletResponse response, Workbook workbook, String fileName){ OutputStream os = null; try { os = response.getOutputStream(); response.setContentType("application/x-download"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls"); workbook.write(os); os.flush(); }catch (Exception e) { e.printStackTrace(); }finally { if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } } //刪除單個文件夾 public void deleteFileDir(String fileName) { File file = new File(fileName); DeleteAll(file); } public void DeleteAll(File dir) { if (dir.isFile()) { dir.delete(); return; } else { File[] files = dir.listFiles(); for (File file : files) { DeleteAll(file); } } dir.delete(); } }
ExportExcelController.javadom
package com.wulss.jakartapoi.hssf; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/exportExlce") public class ExportExcelController { @Autowired IExportExcelService iExportExcelService; @RequestMapping(value="/withSimple",method=RequestMethod.GET) public String withSimple(HttpServletRequest req,HttpServletResponse resp) { List<UserConsumeDetailRecord> list = new ArrayList<>(); UserConsumeDetailRecord record = null; for(int i=0;i<10;i++) { record = new UserConsumeDetailRecord(); record.setUserName("奧雷里亞諾"); record.setConsumeAmount(6.66); record.setConsumeDate(new Date()); record.setConsumeTitle("喝酒吃肉"); list.add(record); } iExportExcelService.exportExcelWithSimple(req, resp, list); return "success"; } @RequestMapping(value="/withDispose",method=RequestMethod.GET) public String WithDispose(HttpServletRequest req,HttpServletResponse resp) { List<UserConsumeDetailRecord> list = new ArrayList<>(); UserConsumeDetailRecord record = null; for(int i=0;i<10;i++) { record = new UserConsumeDetailRecord(); record.setUserName("奧雷里亞諾"); record.setConsumeAmount(6.66); record.setConsumeDate(new Date()); record.setConsumeTitle("喝酒吃肉"); list.add(record); } iExportExcelService.exportExcelWithDispose("consume_detail", "我的消費明細表" + UUID.randomUUID().toString(), list, req, resp); return "success"; } }
第二種方法涉及到的建表語句
CREATE TABLE `export` ( `id` int(32) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵', `export_code` varchar(255) DEFAULT NULL COMMENT '導出主題英文名', `export_name` varchar(255) DEFAULT NULL COMMENT '導出主題中文名' PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='導出主題表'; CREATE TABLE `export_field` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵', `export_id` int(11) unsigned DEFAULT NULL COMMENT '導出主表ID', `field_code` varchar(55) DEFAULT NULL COMMENT '字段英文名', `field_name` varchar(64) DEFAULT NULL COMMENT '字段中文名', `sort` int(11) unsigned DEFAULT '1' COMMENT '排序字段' PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='導出字段表';
數據截圖
表一
表二
涉及到的 UserConsumeDetailRecord.java 、ExportBean.java、ExportFieldBean.java、ExportMapper.java等,mybatis映射文件就不貼出來了
/** * * @Descript TODO (用戶消費實體) * @author Administrator * @date 2019年5月24日 * */ public class UserConsumeDetailRecord { private int id; private int userId; private String userName; private String userTel; private String consumeTitle; private Date consumeDate; private Double consumeAmount; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserTel() { return userTel; } public void setUserTel(String userTel) { this.userTel = userTel; } public String getConsumeTitle() { return consumeTitle; } public void setConsumeTitle(String consumeTitle) { this.consumeTitle = consumeTitle; } public Date getConsumeDate() { return consumeDate; } public void setConsumeDate(Date consumeDate) { this.consumeDate = consumeDate; } public Double getConsumeAmount() { return consumeAmount; } public void setConsumeAmount(Double consumeAmount) { this.consumeAmount = consumeAmount; } }
/** * * @Descript TODO (導出主題表) * @author Administrator * @date 2019年5月27日 * */ public class ExportBean { private Integer id; private String exportCode; private String exportName; private List<ExportFieldBean> fieldBeanList; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getExportCode() { return exportCode; } public void setExportCode(String exportCode) { this.exportCode = exportCode; } public String getExportName() { return exportName; } public void setExportName(String exportName) { this.exportName = exportName; } public List<ExportFieldBean> getFieldBeanList() { return fieldBeanList; } public void setFieldBeanList(List<ExportFieldBean> fieldBeanList) { this.fieldBeanList = fieldBeanList; } }
/** * * @Descript TODO (導出字段表) * @author Administrator * @date 2019年5月27日 * */ public class ExportFieldBean { private Integer id; private Integer exportId; private String exportCode; private String exportName; private Integer sort; private ExportBean exportBean; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getExportId() { return exportId; } public void setExportId(Integer exportId) { this.exportId = exportId; } public String getExportCode() { return exportCode; } public void setExportCode(String exportCode) { this.exportCode = exportCode; } public String getExportName() { return exportName; } public void setExportName(String exportName) { this.exportName = exportName; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public ExportBean getExportBean() { return exportBean; } public void setExportBean(ExportBean exportBean) { this.exportBean = exportBean; } }
@Mapper public interface ExportMapper { ExportBean getExportByExportKey(String exportKey); }
其餘更詳細的能夠參考此文章http://www.javashuo.com/article/p-gunwkpny-r.html