基於poi,將excel錶轉化爲實體類列表的工具類
寫作很幸苦轉載請註明!!!!!
package com.fxx.bos.utils;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
public class GetBeanListByExcel {
/**
*
* @param filePath excel文件路徑
* @param cellKey excel文件每列對應實體類屬性名稱數組 如String[] cellKey = {"id","province","city","district","postcode"};
* @param c 實體類Class
* @return 根據excel表每行的記錄生成的實體類list
* @throws Exception
*/
public static <T>List<T> getBeanList(String filePath,String[] cellKey,Class<T> c) throws Exception{
//創建實體類對象容器
List<T> beanList = new ArrayList<T>();
//讀取excel文件
POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(filePath));
@SuppressWarnings("resource")
HSSFWorkbook xlsFile = new HSSFWorkbook(fs);
HSSFSheet sheet = xlsFile.getSheetAt(0);
//判斷屬性列表同excel文件列是否相符,避免數組範圍溢出
if(cellKey.length!=sheet.getRow(0).getLastCellNum()) {
throw new RuntimeException("傳入列名參數不符合條件!");
}
//創建屬性map
HashMap<String, String> valueMap = new HashMap<String, String>();
//遍歷excel文件
for (Row row : sheet) {
for(int i=0;i<cellKey.length;i++) {
valueMap.put(cellKey[i], row.getCell(i).getStringCellValue());
}
T t = c.newInstance();
//使用BeanUtils將封裝的屬性注入對象
BeanUtils.populate(t, valueMap);
//將對象添加至容器
beanList.add(t);
}
return beanList;
}
}