以前通常会把java bean list 输出为EXCEL文件,作为报表供客户下载,有时候也需要读入客户准备好的Excel文档,并将这些数据导入到数据库中,或者做其他处理, 一般来说导入 excel 文件到内存中应该比较容易,但jxls这个库提供了另外一种处理方式,通过配置文件配置指定导入的column和对应的pojo类的属性.虽然自己也可以做到,但人家已经实现了,还是很方便的, 唯一郁闷的是 导入的jar包比较多,比较变态.
主要用到的工具 jxls:
http://jxls.sourceforge.net/1. 一个公用的处理方法, 将导入的excel文件转为 java bean list:
程序代码
package com.yihaomen.parseexceltojavabeanlist;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.jxls.reader.ReaderBuilder;
import net.sf.jxls.reader.XLSReader;
public class Util<T> {
public List<T> parseExcelFileToBeans(File xlsFile,
File jxlsConfigFile)
throws Exception {
XLSReader xlsReader = ReaderBuilder.buildFromXML(jxlsConfigFile);
List<T> result = new ArrayList<T>();
Map<String, Object> beans = new HashMap<String, Object>();
beans.put("result", result);
InputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(xlsFile));
xlsReader.read(inputStream, beans);
}catch(Exception e){
e.printStackTrace();
}finally{
if (inputStream !=null){
inputStream.close();
}
}
return result;
}
}
要转换的java bean 的定义如下:
程序代码
package com.yihaomen.parseexceltojavabeanlist;
public class Person {
private String firstName;
private String lastName;
private int age;
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
重点是配置文件的处理,看 excel 文件 与 java bean之间的 对应关系:
程序代码
<workbook>
<worksheet name="Sheet1">
<section startRow="0" endRow="0" />
<loop startRow="1" endRow="1" items="result" var="person" varType="com.yihaomen.parseexceltojavabeanlist.Person">
<section startRow="1" endRow="1">
<mapping row="1" col="0">person.firstName</mapping>
<mapping row="1" col="1">person.lastName</mapping>
<mapping row="1" col="2">person.age</mapping>
</section>
<loopbreakcondition>
<rowcheck offset="0">
<cellcheck offset="0" />
</rowcheck>
</loopbreakcondition>
</loop>
</worksheet>
</workbook>
测试代码如下:
程序代码
package com.yihaomen.parseexceltojavabeanlist;
import java.io.File;
import java.util.List;
public class TestApp {
public static void main(String[] args) throws Exception {
String path = System.getProperty("user.dir");
Util util = new Util<Person>();
String excelFilePath = path + File.separator + "personData.xls";
String configFilePath = path + File.separator + "personConfig.xml";
List<Person> persons = util.parseExcelFileToBeans(new File(excelFilePath),
new File(configFilePath));
for(Person p : persons){
System.out.println(p.getFirstName());
}
}
}
Excel 文件内容如下:
程序代码
FirstName LastName Age
Joe Bloggs 25
John Doe 30
除非申明,文章均为
一号门原创,转载请注明本文地址,谢谢!