这篇文章展示了如何使用jXLS将Excel文件解析为JavaBeans列表。
这是我编写的通用实用程序方法:
/**
* Parses an excel file into a list of beans.
*
* @param <T> the type of the bean
* @param xlsFile the excel data file to parse
* @param jxlsConfigFile the jxls config file describing how to map rows to beans
* @return the list of beans or an empty list there are none
* @throws Exception if there is a problem parsing the file
*/
public static <T> List<T> parseExcelFileToBeans(final File xlsFile,final File jxlsConfigFile)throws Exception {final XLSReader xlsReader = ReaderBuilder.buildFromXML(jxlsConfigFile);final List<T> result = new ArrayList<>();final Map<String, Object> beans = new HashMap<>();beans.put("result", result);try (InputStream inputStream = new BufferedInputStream(new FileInputStream(xlsFile))) {xlsReader.read(inputStream, beans);}return result;
}
例:
考虑以下包含人员信息的Excel文件:
名字 | 姓 | 年龄 |
乔 | 博客 | 25 |
约翰 | 母鹿 | 30 |
创建以下Person
Bean,将每个Excel行绑定到:
package model;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;}
}
创建一个jXLS配置文件,该文件告诉jXLS如何处理您的Excel文件并将行映射到Person
对象:
<workbook><worksheet name="Sheet1"><section startRow="0" endRow="0" /><loop startRow="1" endRow="1" items="result" var="person" varType="model.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>
现在,您可以使用此单行代码将Excel文件解析为Person
对象的列表:
List<Person> persons = Utils.parseExcelFileToBeans(new File("/path/to/personData.xls"),new File("/path/to/personConfig.xml"));
相关文章:
使用OpenCSV将CSV文件解析为JavaBeans
翻译自: https://www.javacodegeeks.com/2014/07/parsing-an-excel-file-into-javabeans-using-jxls.html