java解析excel--並反射到實體類
阿新 • • 發佈:2019-01-07
今天分享一下使用java解析Excel03版和07版
參考了原文連結
使用maven需要新增兩個依賴:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11-beta1</version>
</dependency>
<!--07-->
<dependency >
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11-beta1</version>
</dependency>
首先新建一個Excel檔案,檔案第一行為列名,在程式中忽略,但是列名的順序必須和bean類中的屬性順序一致,否則反射會出錯。
所有的資料型別一定要參考bean屬性的方式插入。
直接上程式碼:
bean類
public class Users {
private String name;
private int age;
private double mm;
private String sex;
@Override
public String toString() {
return "Users [name=" + name + ", age=" + age + ", sex=" + sex
+ ", mm=" + mm + "]";
}
public double getMm () {
return mm;
}
public void setMm(double mm) {
this.mm = mm;
}
public String getName() {
return name;
}
public void setName(String name) {
System.err.println(name);
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
解析excel類03:
public class XslPaese {
@SuppressWarnings("rawtypes")
public LinkedList<Object> parse(String filePath , Class classObject) throws FileNotFoundException, IOException, IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException{
LinkedList<Object> list = new LinkedList<Object>();
Reflect reflect = new Reflect();
File file = new File(filePath);//獲取檔案
//解析xsl檔案
POIFSFileSystem pfs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook hwb = new HSSFWorkbook(pfs);
HSSFSheet hs = hwb.getSheetAt(0);//獲取第0個sheet頁的資料
int rowStart = hs.getFirstRowNum();//獲取第一行的行數 0
int rowEnd = hs.getLastRowNum();//獲取最後一行的行數-1
for(int i = rowStart+1; i <= rowEnd ; i++){//行的遍歷
Object obj = classObject.newInstance();
HSSFRow hr = hs.getRow(i);//獲取行
if(hr == null){
continue;
}
int cellStart = hr.getFirstCellNum();//獲取第一列
int cellEnd = hr.getLastCellNum();//獲取列的總數
for(int k = cellStart ; k < cellEnd ; k++ ){//列的遍歷
HSSFCell hc = hr.getCell(k);//獲取列
if(hc == null || hc.equals("")){
continue;
}
switch(hc.getCellType()){
case HSSFCell.CELL_TYPE_STRING://字串
obj = reflect.reflect(obj, k, hc.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_BOOLEAN://boolean型別
obj = reflect.reflect(obj, k, hc.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_NUMERIC://數字
obj = reflect.reflect(obj, k, hc.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA://公式
obj = reflect.reflect(obj, k, hc.getCellFormula());
break;
case HSSFCell.CELL_TYPE_BLANK://空值
obj = reflect.reflect(obj, k, null);
break;
case HSSFCell.CELL_TYPE_ERROR://錯誤
obj = reflect.reflect(obj, k, null);
break;
default:
break;
}
}
list.add(obj);
}
return list;
}
}
解析excel類07:
public class XlsxPaese {
@SuppressWarnings("rawtypes")
public LinkedList<Object> parse(String filePath , Class classObject) throws FileNotFoundException, IOException, InvalidFormatException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
LinkedList<Object> list = new LinkedList<Object>();
Reflect reflect = new Reflect();
File file = new File(filePath);//獲取檔案
XSSFWorkbook xw = new XSSFWorkbook(file);
XSSFSheet xs = xw.getSheetAt(0);//獲取xsl
int rowStart = xs.getFirstRowNum();//獲取第一行的行數 0
int rowEnd = xs.getLastRowNum();//獲取最後一行的行數-1
for(int i = rowStart+1; i <= rowEnd ; i++){//行的遍歷
Object obj = classObject.newInstance();
XSSFRow hr = xs.getRow(i);//獲取行
if(hr == null){
continue;
}
int cellStart = hr.getFirstCellNum();//獲取第一列
int cellEnd = hr.getLastCellNum();//獲取列的總數
for(int k = cellStart ; k < cellEnd ; k++ ){//列的遍歷
XSSFCell hc = hr.getCell(k);//獲取列
if(hc == null || hc.equals("")){
continue;
}
switch(hc.getCellType()){
case HSSFCell.CELL_TYPE_STRING://字串
obj = reflect.reflect(obj, k, hc.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_BOOLEAN://boolean型別
obj = reflect.reflect(obj, k, hc.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_NUMERIC://數字
obj = reflect.reflect(obj, k, hc.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA://公式
obj = reflect.reflect(obj, k, hc.getCellFormula());
break;
case HSSFCell.CELL_TYPE_BLANK://空值
obj = reflect.reflect(obj, k, null);
break;
case HSSFCell.CELL_TYPE_ERROR://錯誤
obj = reflect.reflect(obj, k, null);
break;
default:
break;
}
}
list.add(obj);
}
return list;
}
}
從上面的程式碼應該看的出03解析和07解析只是一兩個類的區別:
03:
POIFSFileSystem pfs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook hwb = new HSSFWorkbook(pfs);
//獲取工作頁面
HSSFSheet hs = hwb.getSheetAt(0);//獲取第0個sheet頁的資料
07:
XSSFWorkbook xw = new XSSFWorkbook(file);
XSSFSheet xs = xw.getSheetAt(0);//獲取xsl
獲取行列的類也是有區別的:
03與07其實就是 HSSFRow/HSSFCell改為XSSFRow/XSSFCell而已,其他的邏輯不變
反射類:
public class Reflect {
public Object reflect(Object obj,int paramNumber,Object value) throws InstantiationException, IllegalAccessException, IntrospectionException, IllegalArgumentException, InvocationTargetException{
Field[] fields = obj.getClass().getDeclaredFields();//獲取屬性名
//返回的是一個引數型別
String type = fields[paramNumber].getGenericType().toString();
//返回的是一個類物件
// Class classType = field.getType();
PropertyDescriptor pd = new PropertyDescriptor(fields[paramNumber].getName(), obj.getClass());
Method setmd = pd.getWriteMethod();//獲取某個屬性的set方法
if(type.equals("class java.lang.String")){
setmd.invoke(obj, value);//啟用
}else if(type.equals("int") || type.equals("class java.lang.Integer")){
String str = value.toString();
if(str.indexOf(".") == -1){
setmd.invoke(obj, value);
}else{
setmd.invoke(obj, Integer.parseInt(str.substring(0, str.indexOf("."))));
}
}else if("double".equals(type) || "class java.lang.Double".equals(type)){
setmd.invoke(obj, value);
}else{
setmd.invoke(obj, value);
}
return obj;
}
}
處理類:
為了能方便
public class Handler {
@SuppressWarnings("rawtypes")
public void handle(String filePath,Class clazz) throws FileNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, IOException, IntrospectionException, InvalidFormatException{
String str = filePath.substring(filePath.lastIndexOf(".")+1);
if(str.equals("xls")){
//03
XslPaese xp = new XslPaese();
xp.parse(filePath, clazz);
}else{
//07
XlsxPaese xp = new XlsxPaese();
xp.parse(filePath, clazz);
}
}
}
測試類:
public void testApp()
{
Handler hd = new Handler();
try {
hd.handle("C:/Users/seaskylight/Desktop/Book1.xlsx", Users.class);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
試試,理解一下,其實這樣寫還是存在很多的不合理,在實際使用上和目前使用上還是有很大的區別的