時間:2017年07月06日星期四
說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com
教學源碼:無
學習源碼:https://github.com/zccodere/s...
基礎知識
struts2框架(上傳下載功能) xml解析技術(導入模板) JQuery EasyUI(前臺美觀)
課程目錄
實現方式 定制導入模版 導入文件 導出文件 總結1-2 Excel解析的幾種實現方式
讀寫Excel三種常用技術
POI JXL FASTEXCEL
什么是POI
Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能
什么是HSSF
HSSF是Horrible SpreadSheet Format的縮寫,也即“討厭的電子表格格式”。通過HSSF,你可以用純Java代碼來讀取、寫入、修改Excel文件
POI常用API
HSSF-讀寫Microsoft Excel格式檔案的功能 XSSF-讀寫Microsoft Excel OOMXML格式檔案的功 HWPF-讀寫Microsoft Word格式檔案的功能 HSLF-讀寫Microsoft PowerPoint格式檔案的功能 HDGF-讀寫Microsoft VIsio格式檔案的功能
iText
通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。下載iText.jar文件后,只需要在系統的classpath中加入iText.jar的路徑,在程序中就可以使用iText類庫了
JXL
Java Excel是一個開源項目,可以讀取Excel文件的內容、創建新的Excel文件、更新已經存在的Excel文件。包括常見格式的設置:字體、顏色、背景、合并單元格等。
POI與JXL對比:POI
效率高 操作相對復雜 支持公式,宏,圖形圖表,一些企業應用上會非常實用 能夠修飾單元格屬性 支持字體、數字、日期操作
POI與JXL對比:JXL
效率低 操作簡單 部分支持 能夠修飾單元格屬性,格式支持不如POI強大 支持字體、數字、日期操作
FastExcel
FastExcel是一個采用純Java開發的excel文件讀寫組件,支持Excel97-2003文件格式。FastExcel只能讀取單元格的字符信息,而其它屬性如顏色、字體等就不支持了,因此FastExcel只需要很小的內存。1-3 學習目標及概念介紹
實例練習
分別通過POI和JXL兩種方式實現對Excel文件讀寫操作,通過代碼體會兩種方式異同
相關概念
工作簿:相當于Excel文件 工作表:相當于Sheet頁 行記錄:Row 單元格Cell:一個單元格第二章:實現原理 2-1 JXL創建Excel
創建一個名為myexcelone的maven項目,并添加JXL依賴,POM文件如下:
4.0.0 com.myimooc myexcelone 0.0.1-SNAPSHOT jar myexcelone http://maven.apache.org UTF-8 net.sourceforge.jexcelapi jxl 2.6.12 org.apache.poi poi 3.16 commons-io commons-io 2.5 org.apache.poi poi-scratchpad 3.16 org.apache.poi poi-ooxml 3.16 org.apache.poi poi-ooxml-schemas 3.16 org.apache.poi poi-examples 3.16 org.apache.poi poi-excelant 3.16 org.apache.xmlbeans xmlbeans 2.6.0 dom4j dom4j 1.6.1 org.jdom jdom 2.0.2 org.apache.commons commons-lang3 3.6 junit junit 3.8.1 test org.apache.maven.plugins maven-compiler-plugin 1.8 1.8
代碼演示:
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();
}
}
2-2 JXL解析Excel
代碼演示:
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()+" ");
}
System.out.println();
}
// 釋放資源
workBook.close();
}
}
2-3 POI創建Excel
在POM文件中添加如下相關依賴
org.apache.poi poi 3.16 commons-io commons-io 2.5
代碼演示:
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();
}
}
2-4 POI解析Excel
代碼演示:
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+" ");
}
System.out.println();
}
// 釋放資源
workBook.close();
}
}
2-5 XSSF創建高版本Excel
在POM文件中添加以下相關依賴:
org.apache.poi poi-scratchpad 3.16 org.apache.poi poi-ooxml 3.16 org.apache.poi poi-ooxml-schemas 3.16 org.apache.poi poi-examples 3.16 org.apache.poi poi-excelant 3.16 org.apache.xmlbeans xmlbeans 2.6.0 dom4j dom4j 1.6.1
代碼演示:
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();
}
}
第三章:導入模版定制
3-1 生成規則
使用場景
用戶想導入excel文件,在這之前,首先需要下載一個導入模版,按照模版規則填寫數據。然后,在把這個excel文件導入到系統之中。根據業務的不同,導出的excel模版也是各種各樣的。
利用xml解析技術,確定模版樣式
確定模版列 定義標題(合并單元格) 定義列名(表頭) 定義數據區域單元格樣式
XML配置模版樣式代碼演示:
3-2 設置列寬及標題
在POM文件中添加xml解析相關依賴
org.jdom jdom 2.0.2 org.apache.commons commons-lang3 3.6
代碼演示:
// 獲取項目根路徑
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 trs = title.getChildren("tr");
for (int i = 0; i < trs.size(); i++) {
Element tr = trs.get(i);
List 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 ++;
}
3-3 設置表頭
代碼演示:
// 設置表頭
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 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 ++;
}
3-4 數據區域樣式
代碼演示:
// 設置數據區域樣式
Element tbody = root.getChild("tbody");
Element tr = tbody.getChild("tr");
int repeat = tr.getAttribute("repeat").getIntValue();
List 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文件
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 trs = title.getChildren("tr");
for (int i = 0; i < trs.size(); i++) {
Element tr = trs.get(i);
List 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 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 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 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);
}
}
}
第四章:文件導入
4-1 環境搭建
教學使用環境
Struts2 Jquery EasyUI MySql數據庫
個人學習環境
Spring Boot Jquery EasyUI MySql數據庫
創建一個名為myexcelweb的項目,POM文件如下:
4-2 導入模版下載(上)4.0.0 com.myimooc myexcelweb 0.0.1-SNAPSHOT jar myexcelweb http://maven.apache.org org.springframework.boot spring-boot-starter-parent 1.5.1.RELEASE UTF-8 UTF-8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-freemarker org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java org.apache.poi poi 3.16 commons-io commons-io 2.5 commons-fileupload commons-fileupload 1.3.1 org.apache.poi poi-scratchpad 3.16 org.apache.poi poi-ooxml 3.16 org.apache.poi poi-ooxml-schemas 3.16 org.apache.poi poi-examples 3.16 org.apache.poi poi-excelant 3.16 org.apache.xmlbeans xmlbeans 2.6.0 dom4j dom4j org.jdom jdom 2.0.2 org.apache.commons commons-lang3 3.6 junit junit test org.apache.maven.plugins maven-compiler-plugin 1.8 1.8
說明:由于代碼量太大,這里僅展示部分頁面效果。具體源碼可到我github地址查看。
課程視頻的第四章和第五章是純代碼講解,我也不知道該怎樣來組織需要展示的內容了。
后端結構圖
前端結構圖
4-3 導入模版下載(下)部分代碼:
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 respData = new HashMap();
List importDataList = importDataService.list();
respData.put("total", importDataList.size());
respData.put("rows", importDataList);
return importDataList;
}
/**
* 功能:獲取導入數據模版
*/
@RequestMapping("importdata-templates")
public Object importdataTemplates(){
List list = new ArrayList();
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 importDataDetailList = new ArrayList();
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+" ");
}else{
value = cell.getStringCellValue();
System.out.print(value+" ");
}
System.out.print(value+" ");
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();
}
}
}
第五章:列表數據導出
5-1 數據導出實現過程
文件導出實現過程 獲取列表表頭信息 獲取符合查詢條件的數據 生成Excel文件5-2 獲取數據類及方法 5-3 前臺實現
這里是使用easyui進行前端開發。
5-4 后臺實現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 respData = new HashMap();
List 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 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();
}
}
}
第六章:課程總結
6-1 課程總結
課程總結
讀寫Excel幾種常用技術 模版定制原理 文件導入導出
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.hztianpu.com/yun/67334.html
摘要:時間年月日星期一說明本文部分內容均來自慕課網。多用于網絡加密。散列函數函數或消息摘要函數主要作用散列函數用來驗證數據的完整性。 時間:2017年4月10日星期一說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學示例源碼:https://github.com/zccodere/s...個人學習源碼:https://github.com/zccodere...
摘要:時間年月日星期三說明本文部分內容均來自慕課網。秘密密鑰,生成一個分組的秘密密鑰。 時間:2017年4月12日星期三說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學示例源碼:https://github.com/zccodere/s...個人學習源碼:https://github.com/zccodere/s... 第一章:概述 1-1 概述 非對稱...
時間:2017年4月11日星期二說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學示例源碼:https://github.com/zccodere/s...個人學習源碼:https://github.com/zccodere/s... 第一章:對稱加密算法DES 1-1 JAVA對稱加密算法DES 加密密鑰=解密密鑰 對稱加密算法 初等 DES --3D...
摘要:時間年月日星期日說明本文部分內容均來自慕課網。用戶可以在服務器端調用云存儲云檢索從而構建自己的存儲和檢索服務,甚至可以制作自己的數據管理臺。 時間:2017年08月13日星期日說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學源碼:無學習源碼:https://github.com/zccodere/s... 第一章:云圖產品介紹 1-1 云圖產品介紹...
摘要:時間年月日星期日說明本文部分內容均來自慕課網。用戶可以在服務器端調用云存儲云檢索從而構建自己的存儲和檢索服務,甚至可以制作自己的數據管理臺。 時間:2017年08月13日星期日說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學源碼:無學習源碼:https://github.com/zccodere/s... 第一章:云圖產品介紹 1-1 云圖產品介紹...
閱讀 1758·2021-11-23 10:01
閱讀 3284·2021-11-19 09:40
閱讀 3440·2021-10-18 13:24
閱讀 3706·2019-08-29 14:20
閱讀 3156·2019-08-26 13:39
閱讀 1520·2019-08-26 11:56
閱讀 2880·2019-08-23 18:03
閱讀 515·2019-08-23 15:35