時間:2017年07月06日星期四
說明:本文部份內容均來自慕課網。@慕課網:http://www.imooc.com
教學源碼:無
學習源碼:https://github.com/zccodere/s...前端
基礎知識java
struts2框架(上傳下載功能) xml解析技術(導入模板) JQuery EasyUI(前臺美觀)
課程目錄mysql
實現方式 定製導入模版 導入文件 導出文件 總結
讀寫Excel三種經常使用技術git
POI JXL FASTEXCEL
什麼是POIgithub
Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能
什麼是HSSFweb
HSSF是Horrible SpreadSheet Format的縮寫,也即「討厭的電子表格格式」。經過HSSF,你能夠用純Java代碼來讀取、寫入、修改Excel文件
POI經常使用APIspring
HSSF-讀寫Microsoft Excel格式檔案的功能 XSSF-讀寫Microsoft Excel OOMXML格式檔案的功 HWPF-讀寫Microsoft Word格式檔案的功能 HSLF-讀寫Microsoft PowerPoint格式檔案的功能 HDGF-讀寫Microsoft VIsio格式檔案的功能
iTextsql
經過iText不只能夠生成PDF或rtf的文檔,並且能夠將XML、Html文件轉化爲PDF文件。下載iText.jar文件後,只須要在系統的classpath中加入iText.jar的路徑,在程序中就可使用iText類庫了
JXL數據庫
Java Excel是一個開源項目,能夠讀取Excel文件的內容、建立新的Excel文件、更新已經存在的Excel文件。包括常見格式的設置:字體、顏色、背景、合併單元格等。
POI與JXL對比:POIapache
效率高 操做相對複雜 支持公式,宏,圖形圖表,一些企業應用上會很是實用 可以修飾單元格屬性 支持字體、數字、日期操做
POI與JXL對比:JXL
效率低 操做簡單 部分支持 可以修飾單元格屬性,格式支持不如POI強大 支持字體、數字、日期操做
FastExcel
FastExcel是一個採用純Java開發的excel文件讀寫組件,支持Excel97-2003文件格式。FastExcel只能讀取單元格的字符信息,而其它屬性如顏色、字體等就不支持了,所以FastExcel只須要很小的內存。
實例練習
分別經過POI和JXL兩種方式實現對Excel文件讀寫操做,經過代碼體會兩種方式異同
相關概念
工做簿:至關於Excel文件 工做表:至關於Sheet頁 行記錄:Row 單元格Cell:一個單元格
建立一個名爲myexcelone的maven項目,並添加JXL依賴,POM文件以下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.myimooc</groupId> <artifactId>myexcelone</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>myexcelone</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- 支持 Excel操做 JXL --> <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6.12</version> </dependency> <!-- 支持Excel 操做 POI --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <!-- 支持簡化文件操做 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <!-- 支持高版本Excel操做 POI 的XSSF start --> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-examples</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans --> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>2.6.0</version> </dependency> <!-- https://mvnrepository.com/artifact/dom4j/dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- 支持高版本Excel操做 POI 的XSSF end --> <!-- 導入模塊定製,支持xml解析 start --> <!-- https://mvnrepository.com/artifact/org.jdom/jdom --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom</artifactId> <version>2.0.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency> <!-- 導入模塊定製,支持xml解析 end --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
代碼演示:
package com.myimooc.one; import java.io.File; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; /** * 經過 JXL 建立 Excel 文件 * @author ZhangCheng on 2017-07-06 * */ public class JxlCreateExcel { public static void main(String[] args) { try { create(); System.out.println("建立成功"); } catch (Exception e) { System.out.println("建立失敗,異常爲:" + e); } } /** * 功能:建立 Excel 文件 * @throws Exception */ public static void create()throws Exception{ // 定義 數組存表頭 String[] title = {"id","name","sex"}; // 定義Excel文件路徑 File file = new File("d://jxl_test.xls"); // 建立文件 file.createNewFile(); // 建立工做簿 WritableWorkbook workBook = Workbook.createWorkbook(file); // 建立sheet頁 WritableSheet sheet = workBook.createSheet("sheet1", 0); Label label = null; // 第一行設置表頭列名 for (int i = 0; i < title.length; i++) { // 幾列、幾行、名稱 label = new Label(i, 0, title[i]); // 往sheet頁中添加單元格 sheet.addCell(label); } // 追加數據 for (int i = 1; i < 10; i++) { label = new Label(0,i,"a"+i); sheet.addCell(label); label = new Label(1,i,"user"+i); sheet.addCell(label); label = new Label(2,i,"男"); sheet.addCell(label); } // 寫入數據 workBook.write(); // 釋放資源 workBook.close(); } }
代碼演示:
package com.myimooc.one; import java.io.File; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; /** * 經過 JXL 解析 Excel 文件 * @author ZhangCheng on 2017-07-06 * */ public class JxlReadExcel { public static void main(String[] args) { try { read(); System.out.println("解析成功"); } catch (Exception e) { System.out.println("解析失敗,異常爲:" + e); } } /** * 功能:解析 Excel 文件 * @throws Exception */ public static void read()throws Exception{ // 指定要解析excel文件的路徑 File file = new File("d:/jxl_test.xls"); // 建立 WorkBook,並指定路徑 Workbook workBook = Workbook.getWorkbook(file); // 獲取工做表sheet Sheet sheet = workBook.getSheet(0); // 獲取數據-循環行 for (int i = 0; i < sheet.getRows(); i++) { // 循環列 for (int j = 0; j < sheet.getColumns(); j++) { // 獲取每個單元格 Cell cell = sheet.getCell(j, i); System.out.print(cell.getContents()+"\t"); } System.out.println(); } // 釋放資源 workBook.close(); } }
在POM文件中添加以下相關依賴
<!-- 支持Excel 操做 POI --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <!-- 支持簡化文件操做 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
代碼演示:
package com.myimooc.one; import java.io.File; import java.io.FileOutputStream; import org.apache.commons.io.FileUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** * 經過 POI 建立 Excel 文件 * @author ZhangCheng on 2017-07-06 * */ public class PoiCreateExcel { public static void main(String[] args) { try { create(); System.out.println("建立成功"); } catch (Exception e) { System.out.println("建立失敗,異常爲:" + e); } } /** * 功能:建立 Excel 文件 * @throws Exception */ public static void create()throws Exception{ // 定義Excel文件路徑 File file = new File("d:/poi_test.xls"); // 建立文件 file.createNewFile(); // 定義 數組存表頭 String[] title = {"id","name","sex"}; // 建立Excel工做簿 HSSFWorkbook workBook = new HSSFWorkbook(); // 建立工做表sheet HSSFSheet sheet = workBook.createSheet(); // 建立第一行 HSSFRow row = sheet.createRow(0); HSSFCell cell = null; // 將表頭寫入第一行 for (int i = 0; i < title.length; i++) { cell = row.createCell(i); cell.setCellValue(title[i]); } // 追加數據 for (int i = 1; i < 10; i++) { HSSFRow nextRow = sheet.createRow(i); HSSFCell cell2 = nextRow.createCell(0); cell2.setCellValue("a"+i); cell2 = nextRow.createCell(1); cell2.setCellValue("user"+i); cell2 = nextRow.createCell(2); cell2.setCellValue("男"); } // 將Excel內容寫入文件 FileOutputStream stream = FileUtils.openOutputStream(file); workBook.write(stream); // 釋放資源 stream.close(); workBook.close(); } }
代碼演示:
package com.myimooc.one; import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** * 經過 POI 解析 Excel 文件 * @author ZhangCheng on 2017-07-06 * */ public class PoiReadExcel { public static void main(String[] args) { try { read(); System.out.println("解析成功"); } catch (Exception e) { System.out.println("解析失敗,異常爲:" + e); } } /** * 功能:解析 Excel 文件 * @throws Exception */ public static void read()throws Exception{ // 指定須要解析excel文件的路徑 File file = new File("d:/poi_test.xls"); // 建立工做簿 HSSFWorkbook workBook = new HSSFWorkbook(FileUtils.openInputStream(file)); // 讀取sheet頁 HSSFSheet sheet = workBook.getSheetAt(0); // 讀取工做表中的數據 int firstRowNum = sheet.getFirstRowNum(); int lastRowNum = sheet.getLastRowNum(); for (int i = firstRowNum; i < lastRowNum; i++) { // 循環讀取每一行數據 HSSFRow row = sheet.getRow(i); // 獲取當前行最後單元格列號 int lastCellNum = row.getLastCellNum(); for (int j = 0; j < lastCellNum; j++) { // 循環讀取當前行中的每個單元格 HSSFCell cell = row.getCell(j); String value = cell.getStringCellValue(); System.out.print(value+"\t"); } System.out.println(); } // 釋放資源 workBook.close(); } }
在POM文件中添加如下相關依賴:
<!-- 支持高版本Excel操做 POI 的XSSF start --> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-examples</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans --> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>2.6.0</version> </dependency> <!-- https://mvnrepository.com/artifact/dom4j/dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- 支持高版本Excel操做 POI 的XSSF end -->
代碼演示:
package com.myimooc.one; import java.io.File; import java.io.FileOutputStream; import org.apache.commons.io.FileUtils; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * 經過 POI 的 XSSF 建立高版本的 Excel 文件 * @author ZhangCheng on 2017-07-06 * */ public class PoiXssfCreateExcel { public static void main(String[] args) { try { create(); System.out.println("建立成功"); } catch (Exception e) { System.out.println("建立失敗,異常爲:" + e); } } /** * 功能:建立 Excel 文件 * @throws Exception */ public static void create()throws Exception{ // 定義Excel文件路徑 File file = new File("d:/poisxxf_test.xlsx"); // 建立文件 file.createNewFile(); // 定義 數組存表頭 String[] title = {"id","name","sex"}; // 建立Excel工做簿 XSSFWorkbook workBook = new XSSFWorkbook(); // 建立工做表sheet XSSFSheet sheet = workBook.createSheet(); // 建立第一行 XSSFRow row = sheet.createRow(0); XSSFCell cell = null; // 將表頭寫入第一行 for (int i = 0; i < title.length; i++) { cell = row.createCell(i); cell.setCellValue(title[i]); } // 追加數據 for (int i = 1; i < 10; i++) { XSSFRow nextRow = sheet.createRow(i); XSSFCell cell2 = nextRow.createCell(0); cell2.setCellValue("a"+i); cell2 = nextRow.createCell(1); cell2.setCellValue("user"+i); cell2 = nextRow.createCell(2); cell2.setCellValue("男"); } // 將Excel內容寫入文件 FileOutputStream stream = FileUtils.openOutputStream(file); workBook.write(stream); // 釋放資源 stream.close(); workBook.close(); } }
使用場景
用戶想導入excel文件,在這以前,首先須要下載一個導入模版,按照模版規則填寫數據。而後,在把這個excel文件導入到系統之中。根據業務的不一樣,導出的excel模版也是各類各樣的。
利用xml解析技術,肯定模版樣式
肯定模版列 定義標題(合併單元格) 定義列名(表頭) 定義數據區域單元格樣式
XML配置模版樣式代碼演示:
<?xml version="1.0" encoding="UTF-8"?> <excel id="student" code="student" name="學生信息導入"> <colgroup> <col index="A" width='17em'></col> <col index="B" width='17em'></col> <col index="C" width='17em'></col> <col index="D" width='17em'></col> <col index="E" width='17em'></col> <col index="F" width='17em'></col> </colgroup> <title> <tr height="16px"> <td rowspan="1" colspan="6" value="學生信息導入" /> </tr> </title> <thead> <tr height="16px"> <th value="編號" /> <th value="姓名" /> <th value="年齡" /> <th value="性別" /> <th value="出生日期" /> <th value=" 愛好" /> </tr> </thead> <tbody> <tr height="16px" firstrow="2" firstcol="0" repeat="5"> <td type="string" isnullable="false" maxlength="30" /><!--用戶編號 --> <td type="string" isnullable="false" maxlength="50" /><!--姓名 --> <td type="numeric" format="##0" isnullable="false" /><!--年齡 --> <td type="enum" format="男,女" isnullable="true" /><!--性別 --> <td type="date" isnullable="false" maxlength="30" /><!--出生日期 --> <td type="enum" format="足球,籃球,乒乓球" isnullable="true" /><!--愛好 --> </tr> </tbody> </excel>
在POM文件中添加xml解析相關依賴
<!-- 導入模塊定製,支持xml解析 start --> <!-- https://mvnrepository.com/artifact/org.jdom/jdom --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom</artifactId> <version>2.0.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency> <!-- 導入模塊定製,支持xml解析 end -->
代碼演示:
// 獲取項目根路徑 String rootPath = System.getProperty("user.dir"); // 獲取解析xml文件路徑 String path = rootPath + "/src/main/resources/student2.xml"; System.out.println(path); File file = new File(path); // 解析xml文件 SAXBuilder builder = new SAXBuilder(); Document parse = builder.build(file); // 建立excel HSSFWorkbook wb = new HSSFWorkbook(); // 建立sheet HSSFSheet sheet = wb.createSheet("sheet0"); // 獲取xml文件根節點 Element root = parse.getRootElement(); // 獲取模版名稱 String templateName = root.getAttribute("name").getValue(); int rownum = 0; int column = 0; // 設置列寬 Element colgroup = root.getChild("colgroup"); setColumnWidth(sheet,colgroup); // 設置標題 Element title = root.getChild("title"); List<Element> trs = title.getChildren("tr"); for (int i = 0; i < trs.size(); i++) { Element tr = trs.get(i); List<Element> tds = tr.getChildren("td"); // 建立一行 HSSFRow row = sheet.createRow(rownum); // 設置樣式 HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); for (column = 0; column < tds.size(); column++) { Element td = tds.get(column); // 建立單元格 HSSFCell cell = row.createCell(column); Attribute rowSpan = td.getAttribute("rowspan"); Attribute colSpan = td.getAttribute("colspan"); Attribute value = td.getAttribute("value"); if(value != null){ String val = value.getValue(); cell.setCellValue(val); int rspan = rowSpan.getIntValue() - 1; int cspan = colSpan.getIntValue() - 1; // 設置字體 HSSFFont font = wb.createFont(); font.setFontName("仿宋_GB2312");// 字體格式 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 字體加粗 //font.setFontHeight((short) 12);// 字體大小 font.setFontHeightInPoints((short) 12); cellStyle.setFont(font); cell.setCellStyle(cellStyle); // 合併單元格 sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan)); } } rownum ++; }
代碼演示:
// 設置表頭 Element thead = root.getChild("thead"); trs = thead.getChildren("tr"); for (int i = 0; i < trs.size(); i++) { Element tr = trs.get(i); HSSFRow row = sheet.createRow(rownum); List<Element> ths = tr.getChildren("th"); for (column = 0; column < ths.size(); column++) { Element th = ths.get(column); Attribute valueAttr = th.getAttribute("value"); HSSFCell cell = row.createCell(column); if(valueAttr != null){ String value = valueAttr.getValue(); cell.setCellValue(value); } } rownum ++; }
代碼演示:
// 設置數據區域樣式 Element tbody = root.getChild("tbody"); Element tr = tbody.getChild("tr"); int repeat = tr.getAttribute("repeat").getIntValue(); List<Element> tds = tr.getChildren("td"); for (int i = 0; i < repeat; i++) { HSSFRow row = sheet.createRow(rownum); for (column = 0; column < tds.size(); column++) { Element td = tds.get(column); HSSFCell cell = row.createCell(column); setType(wb,cell,td); } rownum ++; }
本節完整代碼以下
1.exce模版配置xml文件
<?xml version="1.0" encoding="UTF-8"?> <excel id="student" code="student" name="學生信息導入"> <colgroup> <col index="A" width='17em'></col> <col index="B" width='17em'></col> <col index="C" width='17em'></col> <col index="D" width='17em'></col> <col index="E" width='17em'></col> <col index="F" width='17em'></col> </colgroup> <title> <tr height="16px"> <td rowspan="1" colspan="6" value="學生信息導入" /> </tr> </title> <thead> <tr height="16px"> <th value="編號" /> <th value="姓名" /> <th value="年齡" /> <th value="性別" /> <th value="出生日期" /> <th value=" 愛好" /> </tr> </thead> <tbody> <tr height="16px" firstrow="2" firstcol="0" repeat="5"> <td type="string" isnullable="false" maxlength="30" /><!--用戶編號 --> <td type="string" isnullable="false" maxlength="50" /><!--姓名 --> <td type="numeric" format="##0" isnullable="false" /><!--年齡 --> <td type="enum" format="男,女" isnullable="true" /><!--性別 --> <td type="date" isnullable="false" maxlength="30" /><!--出生日期 --> <td type="enum" format="足球,籃球,乒乓球" isnullable="true" /><!--愛好 --> </tr> </tbody> </excel>
2.CreateTemplate類
package com.myimooc.one; import java.io.File; import java.io.FileOutputStream; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.DVConstraint; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFDataValidation; 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.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddressList; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; /** * 建立 Excel 模版文件 * @author ZhangCheng on 2017-07-06 * */ public class CreateTemplate { public static void main(String[] args) { try { create(); System.out.println("建立成功"); } catch (Exception e) { System.out.println("建立失敗,異常爲:" + e); e.printStackTrace(); } } /** * 功能:建立 Excel 模版文件 * @throws Exception */ @SuppressWarnings("deprecation") public static void create()throws Exception{ // 獲取項目根路徑 String rootPath = System.getProperty("user.dir"); // 獲取解析xml文件路徑 String path = rootPath + "/src/main/resources/student2.xml"; System.out.println(path); File file = new File(path); // 解析xml文件 SAXBuilder builder = new SAXBuilder(); Document parse = builder.build(file); // 建立excel HSSFWorkbook wb = new HSSFWorkbook(); // 建立sheet HSSFSheet sheet = wb.createSheet("sheet0"); // 獲取xml文件根節點 Element root = parse.getRootElement(); // 獲取模版名稱 String templateName = root.getAttribute("name").getValue(); int rownum = 0; int column = 0; // 設置列寬 Element colgroup = root.getChild("colgroup"); setColumnWidth(sheet,colgroup); // 設置標題 Element title = root.getChild("title"); List<Element> trs = title.getChildren("tr"); for (int i = 0; i < trs.size(); i++) { Element tr = trs.get(i); List<Element> tds = tr.getChildren("td"); // 建立一行 HSSFRow row = sheet.createRow(rownum); // 設置樣式 HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); for (column = 0; column < tds.size(); column++) { Element td = tds.get(column); // 建立單元格 HSSFCell cell = row.createCell(column); Attribute rowSpan = td.getAttribute("rowspan"); Attribute colSpan = td.getAttribute("colspan"); Attribute value = td.getAttribute("value"); if(value != null){ String val = value.getValue(); cell.setCellValue(val); int rspan = rowSpan.getIntValue() - 1; int cspan = colSpan.getIntValue() - 1; // 設置字體 HSSFFont font = wb.createFont(); font.setFontName("仿宋_GB2312");// 字體格式 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 字體加粗 //font.setFontHeight((short) 12);// 字體大小 font.setFontHeightInPoints((short) 12); cellStyle.setFont(font); cell.setCellStyle(cellStyle); // 合併單元格 sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan)); } } rownum ++; } // 設置表頭 Element thead = root.getChild("thead"); trs = thead.getChildren("tr"); for (int i = 0; i < trs.size(); i++) { Element tr = trs.get(i); HSSFRow row = sheet.createRow(rownum); List<Element> ths = tr.getChildren("th"); for (column = 0; column < ths.size(); column++) { Element th = ths.get(column); Attribute valueAttr = th.getAttribute("value"); HSSFCell cell = row.createCell(column); if(valueAttr != null){ String value = valueAttr.getValue(); cell.setCellValue(value); } } rownum ++; } // 設置數據區域樣式 Element tbody = root.getChild("tbody"); Element tr = tbody.getChild("tr"); int repeat = tr.getAttribute("repeat").getIntValue(); List<Element> tds = tr.getChildren("td"); for (int i = 0; i < repeat; i++) { HSSFRow row = sheet.createRow(rownum); for (column = 0; column < tds.size(); column++) { Element td = tds.get(column); HSSFCell cell = row.createCell(column); setType(wb,cell,td); } rownum ++; } // 生成excel導入模版 File templateFile = new File("d:/" + templateName + ".xls"); templateFile.delete(); templateFile.createNewFile(); FileOutputStream stream = FileUtils.openOutputStream(templateFile); wb.write(stream); stream.close(); } /** * 功能:設置單元格樣式 * @param wb * @param cell * @param td */ @SuppressWarnings("deprecation") private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) { Attribute typeAttr = td.getAttribute("type"); String type = typeAttr.getValue(); HSSFDataFormat format = wb.createDataFormat(); HSSFCellStyle cellStyle = wb.createCellStyle(); if("NUMERIC".equalsIgnoreCase(type)){ cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); Attribute formatAttr = td.getAttribute("format"); String formatValue = formatAttr.getValue(); formatValue = StringUtils.isNoneBlank(formatValue)?formatValue:"#,##0.00"; cellStyle.setDataFormat(format.getFormat(formatValue)); }else if("STRING".equalsIgnoreCase(type)){ cell.setCellValue(""); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cellStyle.setDataFormat(format.getFormat("@")); }else if("DATE".equalsIgnoreCase(type)){ cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cellStyle.setDataFormat(format.getFormat("yyyy-MM-dd")); }else if("ENUM".equalsIgnoreCase(type)){ CellRangeAddressList regions = new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex()); Attribute enumAttr = td.getAttribute("format"); String enumValue = enumAttr.getValue(); // 加載下拉列表內容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(enumValue.split(",")); // 數據有效性對象 HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint); wb.getSheetAt(0).addValidationData(dataValidation); } cell.setCellStyle(cellStyle); } /** * 功能:設置工做表列寬 * @param sheet 工做表 * @param colgroup */ private static void setColumnWidth(HSSFSheet sheet, Element colgroup) { List<Element> cols = colgroup.getChildren("col"); for (int i = 0; i < cols.size(); i++) { // 獲取每一列的設置 Element col = cols.get(i); Attribute width = col.getAttribute("width"); // 寬度單位 String unit = width.getValue().replaceAll("[0-9,\\.]", ""); String value = width.getValue().replaceAll(unit, ""); int v = 0; if(StringUtils.isBlank(unit) || "px".equals(unit)){ v = Math.round(Float.parseFloat(value) *37F); }else if("em".endsWith(unit)){ v = Math.round(Float.parseFloat(value) *267.5F); } // 設置寬度 sheet.setColumnWidth(i, v); } } }
教學使用環境
Struts2 Jquery EasyUI MySql數據庫
我的學習環境
Spring Boot Jquery EasyUI MySql數據庫
建立一個名爲myexcelweb的項目,POM文件以下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.myimooc</groupId> <artifactId>myexcelweb</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>myexcelweb</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 支持Excel 操做 POI --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <!-- 支持簡化文件操做 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <!-- 支持文件上傳 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- 支持高版本Excel操做 POI 的XSSF start --> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-examples</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans --> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>2.6.0</version> </dependency> <!-- https://mvnrepository.com/artifact/dom4j/dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> </dependency> <!-- 支持高版本Excel操做 POI 的XSSF end --> <!-- 導入模塊定製,支持xml解析 start --> <!-- https://mvnrepository.com/artifact/org.jdom/jdom --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom</artifactId> <version>2.0.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency> <!-- 導入模塊定製,支持xml解析 end --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
說明:因爲代碼量太大,這裏僅展現部分頁面效果。具體源碼可到我github地址查看。
課程視頻的第四章和第五章是純代碼講解,我也不知道該怎樣來組織須要展現的內容了。
後端結構圖
前端結構圖
部分代碼:
package com.myimooc.myexcelweb.web.controller; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.myimooc.myexcelweb.domain.model.ImportData; import com.myimooc.myexcelweb.domain.model.ImportDataDetail; import com.myimooc.myexcelweb.domain.vo.Template; import com.myimooc.myexcelweb.service.ImportDataDeatilService; import com.myimooc.myexcelweb.service.ImportDataService; import com.myimooc.myexcelweb.util.CreateTemplateUtils; import com.myimooc.myexcelweb.util.DateUtils; /** * 數據導入相關 rest 接口 * @author ZhangCheng on 2017-07-08 * */ @RestController public class ImportDataController { private static Logger logger = LoggerFactory.getLogger(ImportDataController.class); @Autowired private ImportDataService importDataService; @Autowired private ImportDataDeatilService importDataDeatilService; /** * 功能:獲取導入列表數據 */ @RequestMapping("importdata-list") public Object importdataList(){ Map<String,Object> respData = new HashMap<String,Object>(); List<ImportData> importDataList = importDataService.list(); respData.put("total", importDataList.size()); respData.put("rows", importDataList); return importDataList; } /** * 功能:獲取導入數據模版 */ @RequestMapping("importdata-templates") public Object importdataTemplates(){ List<Template> list = new ArrayList<Template>(); Template t = new Template(); t.setTemplateId("student"); t.setTemplateName("student"); list.add(t); return list; } /** * 功能:數據導入 */ @SuppressWarnings("deprecation") @PostMapping("importdata-upload") public Object importdataUpload(MultipartFile file){ if(null == file){ return "上傳失敗,文件爲空"; } try { String fileName = file.getName(); String filePath = getClass().getClassLoader().getResource("config/excel/").getPath()+fileName; File excelFile = new File(filePath); FileUtils.writeByteArrayToFile(excelFile, file.getBytes()); ImportData importData = new ImportData(); Long importDataId = DateUtils.getTimeInstant(); importData.setId(importDataId); importData.setImport_data_type("student"); importData.setImport_status(1+""); importData.setImport_date(DateUtils.nowToString()); importDataService.save(importData); // 建立工做簿 HSSFWorkbook workBook = new HSSFWorkbook(file.getInputStream()); // 讀取sheet頁 HSSFSheet sheet = workBook.getSheetAt(0); // 讀取工做表中的數據 int firstRowNum = 1; int lastRowNum = sheet.getLastRowNum(); List<ImportDataDetail> importDataDetailList = new ArrayList<ImportDataDetail>(); for (int i = firstRowNum; i < lastRowNum; i++) { // 循環讀取每一行數據 HSSFRow row = sheet.getRow(i); // 獲取當前行最後單元格列號 int lastCellNum = row.getLastCellNum(); ImportDataDetail importDataDetail = new ImportDataDetail(); for (int j = 0; j < lastCellNum; j++) { // 循環讀取當前行中的每個單元格 HSSFCell cell = row.getCell(j); String value = ""; int type = cell.getCellType(); if(HSSFCell.CELL_TYPE_NUMERIC == type){ value = cell.getNumericCellValue() + ""; System.out.print(value+"\t"); }else{ value = cell.getStringCellValue(); System.out.print(value+"\t"); } System.out.print(value+"\t"); switch(j){ case 0: importDataDetail.setCol0(value); case 1: importDataDetail.setCol1(value); case 2: importDataDetail.setCol2(value); case 3: importDataDetail.setCol3(value); case 4: importDataDetail.setCol4(value); case 5: importDataDetail.setCol5(value); case 6: importDataDetail.setCol6(value); } importDataDetail.setDeal_status(1+""); importDataDetail.setImport_id(importDataId); importDataDetail.setId(DateUtils.getTimeInstant()+Math.round(DateUtils.getTimeInstant())); } System.out.println(); importDataDetailList.add(importDataDetail); } // 釋放資源 workBook.close(); importDataDeatilService.save(importDataDetailList); importData = importDataService.findOne(importDataId); importData.setDeal_date(DateUtils.nowToString()); importData.setDeal_status(1+""); importDataService.save(importData); return "上傳成功"; } catch (IOException e) { e.printStackTrace(); } return "上傳失敗"; } /** * 功能:下載導入數據模版 */ @RequestMapping("download") public void download(HttpServletRequest request,HttpServletResponse response,String templateId){ String fileName = "student.xls"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename="+fileName); String xmlPath = getClass().getClassLoader().getResource("config/excel/student.xml").getPath(); String filePath = getClass().getClassLoader().getResource("config/excel/").getPath(); File xmlFile = new File(xmlPath); File excelFile = new File(filePath + fileName); try { CreateTemplateUtils.create(xmlFile,excelFile); logger.info("建立成功:{}",excelFile.getName()); InputStream in = FileUtils.openInputStream(excelFile); int b; while((b=in.read())!= -1) { response.getOutputStream().write(b); } } catch (Exception e) { logger.info("建立失敗,異常爲:{}",e); e.printStackTrace(); } } }
文件導出實現過程 獲取列表表頭信息 獲取符合查詢條件的數據 生成Excel文件
這裏是使用easyui進行前端開發。
package com.myimooc.myexcelweb.web.controller; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.myimooc.myexcelweb.domain.model.Student; import com.myimooc.myexcelweb.service.StudentService; /** * 學生信息相關 rest 接口 * @author ZhangCheng on 2017-07-08 * */ @RestController public class StudentController { private static Logger logger = LoggerFactory.getLogger(ImportDataController.class); @Autowired private StudentService studentService; /** * 功能:獲取學生信息列表 */ @RequestMapping("student-list") public Object studentList(){ logger.info("獲取學生信息"); Map<String,Object> respData = new HashMap<String,Object>(); List<Student> studentList = studentService.list(); respData.put("total", studentList.size()); respData.put("rows", studentList); return respData; } /** * 功能:導出學生信息列表爲excel */ @RequestMapping("student-export") public void studentExport(HttpServletRequest request,HttpServletResponse response,String templateId){ String fileName = "學生信息.xls"; String enfileName = ""; response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream"); try { enfileName = URLEncoder.encode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } response.setHeader("Content-Disposition", "attachment;filename="+enfileName); List<Student> studentList = studentService.list(); // 定義 數組存表頭 String[] title = {"編號","姓名","年齡","性別","出生日期","愛好"}; // 建立Excel工做簿 HSSFWorkbook workBook = new HSSFWorkbook(); // 建立工做表sheet HSSFSheet sheet = workBook.createSheet("學生信息"); // 建立第一行 HSSFRow row = sheet.createRow(0); HSSFCell cell = null; // 將表頭寫入第一行 for (int i = 0; i < title.length; i++) { cell = row.createCell(i); cell.setCellValue(title[i]); } // 追加數據 for (int i = 1; i < studentList.size(); i++) { Student student = studentList.get(i); HSSFRow nextRow = sheet.createRow(i); HSSFCell cell2 = nextRow.createCell(0); cell2.setCellValue(student.getStunum()); cell2 = nextRow.createCell(1); cell2.setCellValue(student.getStuname()); cell2 = nextRow.createCell(2); cell2.setCellValue(student.getStuage()); cell2 = nextRow.createCell(3); cell2.setCellValue(student.getStusex()); cell2 = nextRow.createCell(4); cell2.setCellValue(student.getStubirthday()); cell2 = nextRow.createCell(5); cell2.setCellValue(student.getStuhobby()); } String filePath = getClass().getClassLoader().getResource("config/excel/").getPath(); File excelFile = new File(filePath + fileName); try { // 將Excel內容寫入文件 FileOutputStream stream = FileUtils.openOutputStream(excelFile); workBook.write(stream); // 釋放資源 stream.close(); workBook.close(); logger.info("建立成功:{}",excelFile.getName()); InputStream in = FileUtils.openInputStream(excelFile); int b; while((b=in.read())!= -1) { response.getOutputStream().write(b); } } catch (Exception e) { logger.info("建立失敗,異常爲:{}",e); e.printStackTrace(); } } }
課程總結
讀寫Excel幾種經常使用技術 模版定製原理 文件導入導出