本文將介紹Java Poi包的使用,并實現Excel報表的導入導出。
前提摘要:在系統的管理后臺當中中,Excel報表的導入導出已經是不不可避免的場景。值得一提的是支付寶和微信支付的批量轉賬也需要相應格式的Excel文檔支持,這個文檔就需要從我們的業務訂單系統中相應的導出的[手動滑稽]。
Apache POI[^1] 基本介紹
Apache POI 是創建和維護操作各種符合Office Open XML(OOXML)標準和微軟的OLE 2復合文檔格式(OLE2)的Java API。用它可以使用Java讀取和創建,修改MS Excel文件.而且,還可以使用Java讀取和創建MS Word和MSPowerPoint文件。Apache POI 提供Java操作Excel解決方案(適用于Excel97-2008)。
Excel導出
- 定義數據模型
參考財付通的批量提現Excel的格式,定義模型如下
private int recordId; //提現id
private String cname; //提現人名稱
private String cbank; //提現銀行的code
private String cnum; //提現卡號
private int money; //提現金額
private int type = 1; //類別
private String comment = "現金提現"; //備注
- 定義接口
IExcelExport
package cn.daimaniu.blog.poi;
import java.util.List;
public interface IExcelExport<T> {
/**
* 獲取Excel的Header
*
* @return
*/
String[] getHeader();
/**
* 返回Excel的header大小
*
* @return
*/
int getHeaderSize();
/**
* 導出的標題
*
* @return
*/
String getTitle();
/**
* 是否包含 特殊的Field的處理
*
* @param filedName
* @return
*/
boolean containSpecialField(String filedName);
/**
* 獲取 特殊的Field的處理后的值
*
* @param filedName
* @return
*/
String getSpecialFieldValue(String filedName);
/**
* 獲取數據源
*
* @return
*/
List<T> getPoiList();
/**
* 設置數據源
*/
void setPoiList(List<T> data);
}
接口主要定義了model的set和get,生成文件名稱,excel第一行的標題定義
- 實現接口
RecordExport
package cn.daimaniu.blog.poi.impl;
import cn.daimaniu.blog.poi.IExcelExport;
import cn.daimaniu.blog.poi.model.RecordPoi;
import org.apache.commons.lang.StringUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class RecordExport implements IExcelExport<RecordPoi> {
List<RecordPoi> poiList = new ArrayList<>();
private String title;
String[] headers = {"序號", "收款人姓名", "銀行名稱", "銀行卡號", "付款金額", "到賬方式", "備注"};
public String[] getHeader() {
return headers;
}
public int getHeaderSize() {
return headers.length;
}
public String getTitle() {
if (StringUtils.isEmpty(title)) {
return formatDate(new Date(), "yyyy-MM-dd_HH-mm-ss") + "-提現記錄.xls";
} else {
return title;
}
}
private String formatDate(Date date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
public boolean containSpecialField(String filedName) {
return false;
}
public String getSpecialFieldValue(String filedName) {
return null;
}
public List<RecordPoi> getPoiList() {
return this.poiList;
}
public void setPoiList(List<RecordPoi> data) {
this.poiList = data;
}
}
- ExcelUtil工具類
public static <T> void export(IExcelExport<T> excelExport, OutputStream out, String pattern) {
//讀取配置
String[] headers = excelExport.getHeader();
Collection<T> dataset = excelExport.getPoiList();
if (dataset == null || dataset.isEmpty()) {
//空數據 直接退出
return;
}
// 聲明一個工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一個表格
HSSFSheet sheet = workbook.createSheet(excelExport.getTitle());
// 設置表格默認列寬度為15個字節
sheet.setDefaultColumnWidth(15);
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setFillForegroundColor(HSSFColor.WHITE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.BLACK.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字體應用到當前的樣式
style.setFont(font);
// 生成并設置另一個樣式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.WHITE.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一個字體
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應用到當前的樣式
style2.setFont(font2);
// 聲明一個畫圖的頂級管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 產生表格標題行
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 遍歷集合數據,產生數據行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = it.next();
// 利用反射,根據javabean屬性的先后順序,動態調用getXxx()方法得到屬性值
Field[] fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[]{});
Object value = getMethod.invoke(t, new Object[]{});
// 判斷值的類型后進行強制類型轉換
String textValue = null;
if (excelExport.containSpecialField(fieldName)) {
textValue = excelExport.getSpecialFieldValue(fieldName);
} else if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
} else if (value instanceof Long) {
Date date = new Date((Long) value);
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
} else if (value instanceof byte[]) {
// 有圖片時,設置行高為60px;
row.setHeightInPoints(60);
// 設置圖片所在列寬度為80px,注意這里單位的一個換算
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
1023, 255, (short) 6, index, (short) 6, index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
} else {
// 其它數據類型都當作字符串簡單處理
if (value == null) {
textValue = "";
} else {
textValue = value.toString();
}
}
// 如果不是圖片數據,就利用正則表達式判斷textValue是否全部由數字組成
if (textValue != null) {
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是數字當作double處理
cell.setCellValue(Double.parseDouble(textValue));
} else {
HSSFRichTextString richString = new HSSFRichTextString(
textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLACK.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
// 清理資源
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
導出類,傳入IExcelExport接口(泛型),允許使用不同Model的Export實現,實現不同數據源的導出。
export方法 利用反射,根據javabean屬性的先后順序,動態調用getXxx()方法得到屬性值,通過excelExport.containSpecialField
判斷是否需要 自定義字段的特殊處理。其它的Style Font的設置可參考官方文檔。
- 執行數據測試
mvn test -Dtest=ExcelTest#TestExcel
測試將執行一個模擬數據的導出功能,并將導出的Excel重新解析 并打印出來。
導出效果:
Excel導入
- 定義接口
IExcelConsumer
public interface IExcelConsumer {
/**
* 消費excel sheet
*
* @param sheet
*/
void consume(Sheet sheet);
}
- 實現消費接口
RecordComsumer
package cn.daimaniu.blog.poi.impl.consumer;
import cn.daimaniu.blog.poi.IExcelConsumer;
import cn.daimaniu.blog.poi.model.RecordPoi;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import java.util.ArrayList;
import java.util.List;
public class RecordComsumer implements IExcelConsumer {
@Override
public void consume(Sheet sheet) {
List<RecordPoi> recordPois = new ArrayList<>();
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
if (i % 500 == 0) {
//在這里 處理 提取出來的數據
// recordPoiMapper.batchInsert(recordPois);
System.out.println("Excel解析出 size:" + recordPois.size() + "recordPois:" + recordPois.toString());
recordPois = null;
recordPois = new ArrayList<>();
}
Row row = sheet.getRow(i);
RecordPoi recordPoi = new RecordPoi();
recordPoi.setRecordId(Integer.parseInt(row.getCell(0).getStringCellValue()));
recordPoi.setCname(row.getCell(1).getStringCellValue());
recordPoi.setCbank(row.getCell(2).getStringCellValue());
recordPoi.setCnum(row.getCell(3).getStringCellValue());
recordPoi.setMoney(Integer.parseInt(row.getCell(4).getStringCellValue()));
recordPoi.setType(Integer.parseInt(row.getCell(5).getStringCellValue()));
recordPoi.setComment(row.getCell(6).getStringCellValue());
recordPois.add(recordPoi);
}
if (recordPois != null && recordPois.size() > 0) {
//在這里 處理 500除余,提取出來的數據
// recordPoiMapper.batchInsert(recordPois);
System.out.println("Excel解析出 size:" + recordPois.size() + "recordPois:" + recordPois.toString());
recordPois = null;
}
}
}
消費類只要依次讀取Excel Row的Column數據,重寫到Model對象中即可。
Notice:在Excel導入過程中,一定要注意數據的有效性判斷,比如Null,數據格式判斷(Text,String,numeric,Date的區別...)
- 執行數據測試
mvn test -Dtest=ExcelTest#TestExcel
測試將執行一個模擬數據的導出功能,并將導出的Excel重新解析 并打印出來。
打印效果:
參考列表
- 菜鳥筆記源碼
- [^1]Apache Poi
本文源代碼地址:https://github.com/daimaniu/cainiaobiji ,歡迎star 和 fork。
下期預告
下期預告(9月12號):Java日期處理實踐。
歡迎大家關注我,每周兩篇原創技術文章。菜鳥筆記 下周一不見不散