封裝poi匯入篇
阿新 • • 發佈:2018-11-25
前言
有封裝的想法好久了,專案中有不少地方需要使用匯入功能,匯入雖說不能,但是每次都要為了特定類寫一個特定方法,很麻煩,我很討厭一直寫這種東西了,正好趁著這次機會就寫一個可以解決這種問題的小專案。
maven
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.0</version> </dependency> <dependency>
基礎工具類
package cc.vvxtoys.vhelper.excelhelper.util; import java.math.BigDecimal; import java.text.SimpleDateFormat; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFCell; public class LoaderUtil { public static String getValue(Cell cell) { switch (cell.getCellType()) { case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()).trim(); case NUMERIC: if(HSSFDateUtil.isCellDateFormatted(cell)){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return String.valueOf(sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()))).trim(); } BigDecimal bd = new BigDecimal(String.valueOf(cell.getNumericCellValue()).trim()); return bd.toPlainString(); default: return String.valueOf(cell.getStringCellValue()).trim(); } } // 空行 public static boolean isBlank(Row row) { for (int i = 0; i < row.getLastCellNum(); i++) { Cell cell = row.getCell(i); if (cell != null && cell.getCellType() != CellType.BLANK) { return false; } } return true; } public static boolean isEmpty(Object obj) { if (obj instanceof Cell) { Cell cell = (Cell) obj; return getValue(cell) == null || "".equals(getValue(cell)); } return obj == null || obj.toString().trim().equals(""); } }
實體
package cc.vvxtoys.vhelper.excelhelper.loader; import java.lang.reflect.Array; import java.util.stream.BaseStream; import java.util.stream.IntStream; import java.util.stream.Stream; /** * @author vvxtoys * @date 2018年10月30日上午11:34:23 * @Description: TODO * @version V1.0 */ public class ExcelLoader<T> { private int version; //excel版本 private Class<T> clazz; //解析型別 javaben或者map private String path; //路徑 private int startRow; //解析開始條數 private int endRow; //解析結束條數 private int[] indexs; //對應列下標 private String[] colums; //列名 private String sheetName; //工作表名 private int sheetIndex; //工作表下標 private int sheetMaxIndex; //最大工作表下標 public static class Builder<T> { private int version; private Class<T> clazz; private String path; private int startRow; private int endRow; private int[] indexs; private String[] colums; private String sheetName; private int sheetIndex = -1;//預設值 private int sheetMaxIndex; public Builder(String path){ verifyPath(path); } public Builder(Class<T> clazz, String path) { this.clazz = clazz; verifyPath(path); } public void verifyPath(String path){ this.path = path; if(path.endsWith(".xlsx")){ this.version = 1; }else if(path.endsWith(".xls")){ this.version = 0; }else{ throw new IllegalArgumentException("path is unavailable!"); } } public Builder<T> setStartRow(int startRow){ this.startRow = startRow; return this; } public Builder<T> setEndRow(int endRow){ this.endRow = endRow; return this; } public Builder<T> setIndexs(int[] indexs){ this.indexs = indexs; return this; } public Builder<T> setColums(String[] colums){ this.colums = colums; return this; } public Builder<T> setSheetName(String sheetName){ this.sheetName = sheetName; return this; } public Builder<T> setSheetIndex(int sheetIndex){ this.sheetIndex = sheetIndex; return this; } public Builder<T> setSheetMaxIndex(int sheetMaxIndex){ this.sheetMaxIndex = sheetMaxIndex; return this; } public ExcelLoader<T> builder() { if(endRow == 0){ endRow = version == 0?65535:1048575;//對應xls、xlsx } return new ExcelLoader<T>(this); } } private ExcelLoader(Builder<T> builder) { this.clazz = builder.clazz; this.path = builder.path; this.version = builder.version; this.colums = builder.colums; this.indexs = builder.indexs; this.sheetName = builder.sheetName; this.startRow = builder.startRow; this.endRow = builder.endRow; this.sheetMaxIndex = builder.sheetMaxIndex; this.sheetIndex = builder.sheetIndex; } private void generatorColums(int len){ colums = new String[len]; //1.8 IntStream.range(0,len).forEach(i -> Array.set(colums, i, "C"+i)); //1.7 // for(int i=0;i<len;i++){ // colums[i] = "C"+i; // } } private void generatorIndexs(int len){ //1.8 indexs = IntStream.range(0, len).toArray(); //1.7 // indexs = new int[len]; // for(int i=0;i<len;i++){ // indexs[i] = i; // } } public void generator(int len){ if (this.indexs == null) { generatorIndexs(len); } if(this.colums == null){ generatorColums(len); } } public String getPath(){ return this.path; } public int getVersion() { return version; } public int getStartRow() { return startRow; } public int getEndRow() { return endRow; } public int[] getIndexs() { return indexs; } public String[] getColums() { return colums; } public String getSheetName() { return sheetName; } public int getSheetIndex() { return sheetIndex; } public int getSheetMaxIndex() { return sheetMaxIndex; } public Class<T> getClazz() { return clazz; } public int parserType(){ if(this.clazz == null){ return 0;//轉換為map } return 1;//轉換為javabean } }
處理類
package cc.vvxtoys.vhelper.excelhelper.loader;
import java.io.FileInputStream;
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 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.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;
import cc.vvxtoys.vhelper.common.utils.BeanUtil;
import cc.vvxtoys.vhelper.excelhelper.util.LoaderUtil;
public class Loader<T> {
private ExcelLoader<T> el;
public Loader(ExcelLoader<T> el) {
this.el = el;
}
public List<?> parsingExcel() {
if (el.getVersion() == 0) {
return parsingExcelByXls();
} else {
return parsingExcelByXlsx();
}
}
/**
* @author vvxtoys
* @date 2018年11月1日上午10:26:01
* @Description: 解析優先順序
* 1.sheetName sheet頁名
* 2.index sheet下標
* 3.maxindex sheet最大下標
*/
private List<?> parsingExcelByXls() {
List<T> list = new ArrayList<T>();// bean list
List<Map<String, Object>> resultList = new ArrayList<>();// map list
HSSFWorkbook workbook = null;
try {
int maxIndex = el.getSheetMaxIndex();// sheet頁最大下標
int index = el.getSheetIndex();// sheet頁下標
InputStream is = new FileInputStream(el.getPath());
workbook = new HSSFWorkbook(is);
HSSFSheet sheet = null;
int len = 0;// 自動生成陣列引數
int sheetMaxNumber = workbook.getNumberOfSheets();// sheet個數
if (el.getSheetName() != null) {
sheet = workbook.getSheet(el.getSheetName());
maxIndex = 1;// 不用遍歷所有sheet頁
} else if (index != -1) {
if (index < 0 || index > sheetMaxNumber) {
throw new IndexOutOfBoundsException("index is out of bounds");
}
sheet = workbook.getSheetAt(index);
maxIndex = 1;
} else {
if (maxIndex < 1) {
maxIndex = 1;
} else if (maxIndex > sheetMaxNumber) {
maxIndex = sheetMaxNumber;
}
}
if (el.getColums() == null || el.getIndexs() == null) {
int startRow = el.getStartRow();
int startIndex = 0;
if (startRow <= 0) {
startIndex = 0;
} else {
startIndex = startRow - 1;
}
if (sheet == null) {
len = workbook.getSheetAt(0).getRow(startIndex).getPhysicalNumberOfCells();
} else {
len = sheet.getRow(startIndex).getPhysicalNumberOfCells();
}
if (len == 0) {
throw new IllegalArgumentException("start column is blank");
}
el.generator(len);
}
for (int s = 0; s < maxIndex; s++) {
if (sheet == null) {
sheet = workbook.getSheetAt(s);
}
int sheetMaxRow = sheet.getLastRowNum();// 行數
int startRow = el.getStartRow();
int endRow = el.getEndRow();
int startIndex = 0;
int endIndex = 0;
if (startRow <= 0) {
startIndex = 0;
} else {
startIndex = startRow - 1;
}
if (endRow > sheetMaxRow) {
endIndex = sheetMaxRow + 1;
} else {
endIndex = endRow;
}
for (int rowNum = startIndex; rowNum < endIndex; rowNum++) {
HSSFRow row = sheet.getRow(rowNum);
if (LoaderUtil.isBlank(row)) {// 空行
continue;
}
Map<String, Object> result = new HashMap<>();
for (int i = 0; i < el.getColums().length; i++) {
HSSFCell cell = row.getCell(el.getIndexs()[i]);
if (!LoaderUtil.isEmpty(cell)) {
result.put(el.getColums()[i], LoaderUtil.getValue(cell));
}
}
resultList.add(result);
}
}
if (el.parserType() == 0) {
return resultList;
} else {
Class<T> clazz = el.getClazz();
for (Map<String, Object> m : resultList) {
list.add(BeanUtil.mapToBean(m, clazz));
}
}
} catch (IOException e) {
e.printStackTrace();
}
// finally {
// if (workbook != null) {
// try {
// workbook.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
return list;
}
private List<?> parsingExcelByXlsx() {
List<T> list = new ArrayList<T>();// bean list
List<Map<String, Object>> resultList = new ArrayList<>();// map list
XSSFWorkbook workbook = null;
try {
int maxIndex = el.getSheetMaxIndex();// sheet頁最大下標
int index = el.getSheetIndex();// sheet頁下標
InputStream is = new FileInputStream(el.getPath());
workbook = new XSSFWorkbook(is);
XSSFSheet sheet = null;
int len = 0;// 自動生成陣列引數
int sheetMaxNumber = workbook.getNumberOfSheets();// sheet個數
if (el.getSheetName() != null) {
sheet = workbook.getSheet(el.getSheetName());
maxIndex = 1;// 不用遍歷所有sheet頁
} else if (index != -1) {
if (index < 0 || index > sheetMaxNumber) {
throw new IndexOutOfBoundsException("index is out of bounds");
}
sheet = workbook.getSheetAt(index);
maxIndex = 1;
} else {
if (maxIndex < 1) {
maxIndex = 1;
} else if (maxIndex > sheetMaxNumber) {
maxIndex = sheetMaxNumber;
}
}
if (el.getColums() == null || el.getIndexs() == null) {
int startRow = el.getStartRow();
int startIndex = 0;
if (startRow <= 0) {
startIndex = 0;
} else {
startIndex = startRow - 1;
}
if (sheet == null) {
len = workbook.getSheetAt(0).getRow(startIndex).getPhysicalNumberOfCells();
} else {
len = sheet.getRow(startIndex).getPhysicalNumberOfCells();
}
if (len == 0) {
throw new IllegalArgumentException("start column is blank");
}
el.generator(len);
}
for (int s = 0; s < maxIndex; s++) {
if (sheet == null) {
sheet = workbook.getSheetAt(s);
}
int sheetMaxRow = sheet.getLastRowNum();// 行數
int startRow = el.getStartRow();
int endRow = el.getEndRow();
int startIndex = 0;
int endIndex = 0;
if (startRow <= 0) {
startIndex = 0;
} else {
startIndex = startRow - 1;
}
if (endRow > sheetMaxRow) {
endIndex = sheetMaxRow + 1;
} else {
endIndex = endRow;
}
for (int rowNum = startIndex; rowNum < endIndex; rowNum++) {
XSSFRow row = sheet.getRow(rowNum);
if (LoaderUtil.isBlank(row)) {// 空行
continue;
}
Map<String, Object> result = new HashMap<>();
for (int i = 0; i < el.getColums().length; i++) {
XSSFCell cell = row.getCell(el.getIndexs()[i]);
if (!LoaderUtil.isEmpty(cell)) {
result.put(el.getColums()[i], LoaderUtil.getValue(cell));
}
}
resultList.add(result);
}
}
if (el.parserType() == 0) {
return resultList;
} else {
Class<T> clazz = el.getClazz();
for (Map<String, Object> m : resultList) {
list.add(BeanUtil.mapToBean(m, clazz));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
}
beanUtil
public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
if (map == null) {
return null;
}
T obj = null;
try{
obj = clazz.newInstance();
BeanUtils.populate(obj, map);
}catch (Exception e) {
e.printStackTrace();
}
return obj;
}
呼叫類
package cc.vvxtoys.vhelper.excelhelper;
import java.util.List;
import cc.vvxtoys.vhelper.excelhelper.loader.ExcelLoader;
import cc.vvxtoys.vhelper.excelhelper.loader.Loader;
import cc.vvxtoys.vhelper.excelhelper.loader.ExcelLoader.Builder;
public class ExcelLoaderHelper{
Builder<?> builder;
public ExcelLoaderHelper(String path) {
builder = new Builder<>(path);
}
public ExcelLoaderHelper(String path,Class<?> clazz) {
builder = new Builder<>(clazz, path);
}
/**
* @author vvxtoys
* @date 2018年11月2日上午10:06:18
* @Description: 設定起始行
* @param startRow
*/
public void setStartRow(int startRow){
builder.setStartRow(startRow);
}
/**
* @author vvxtoys
* @date 2018年11月2日上午10:07:02
* @Description: 設定結束行
* @param endRow
*/
public void setEndRow(int endRow){
builder.setEndRow(endRow);
}
/**
* @author vvxtoys
* @date 2018年11月2日上午10:07:40
* @Description: 指定列下標
* @param indexs
*/
public void setIndexs(int[] indexs){
builder.setIndexs(indexs);
}
/**
* @author vvxtoys
* @date 2018年11月2日上午10:08:08
* @Description: 設定列名
* @param colums
* @return
*/
public void setColums(String[] colums){
builder.setColums(colums);
}
/**
* @author vvxtoys
* @date 2018年11月2日上午10:09:08
* @Description: 根據sheet名讀取
* @param sheetName
*/
public void setSheetName(String sheetName){
builder.setSheetName(sheetName);
}
/**
* @author vvxtoys
* @date 2018年11月2日上午10:09:25
* @Description: 讀取指定下標sheet
* @param sheetIndex
* @return
*/
public void setSheetIndex(int sheetIndex){
builder.setSheetIndex(sheetIndex);
}
/**
* @author vvxtoys
* @date 2018年11月2日上午10:10:34
* @Description: 設定可讀取最大sheet頁
* @param sheetMaxIndex
*/
public void setSheetMaxIndex(int sheetMaxIndex){
builder.setSheetMaxIndex(sheetMaxIndex);
}
@SuppressWarnings("rawtypes")
public List<?> loadExcelToMap(){
ExcelLoader<?> el = builder.builder();
Loader loader = new Loader<>(el);
return loader.parsingExcel();
}
@SuppressWarnings({"rawtypes"})
public List<?> loadExcelToBean(){
ExcelLoader<?> el = builder.builder();
if(el.getClazz() == null){
throw new IllegalArgumentException("cannot be cast to NULL");
}
Loader loader = new Loader<>(el);
return loader.parsingExcel();
}
}