我遇到了同样的问题,我知道使用标准实现(Apache POI)需要花费很多时间,所以在搜索和查找后,我找到了更好的方法(JXLS-Reader)。
首先使用/导入/包含jxls-reader库。
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-reader</artifactId>
<version>2.0.3</version>
</dependency>
然后创建一个XML文件,用于库与列和对象属性之间的对应关系,此XML以初始化列表作为参数,通过从Excel文件中提取的数据(Employee对象)填充它,在您的示例中,它将如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook>
<worksheet idx="0">
<section startRow="0" endRow="0" />
<loop startRow="1" endRow="1" items="employeeList" var="employee" varType="com.department.Employee">
<section startRow="1" endRow="1">
<mapping row="1" col="0">employee.empNo</mapping>
<mapping row="1" col="1">employee.empName</mapping>
</section>
<loopbreakcondition>
<rowcheck offset="0">
<cellcheck offset="0"></cellcheck>
</rowcheck>
</loopbreakcondition>
</loop>
</worksheet>
</workbook>
然后在Java中,初始化员工列表(将解析结果包括在内),然后通过输入的Excel文件和XML映射调用JXLS读取器,代码如下:
package com.department;
import java.io.BufferedInputStream;
import java.io.File;
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.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
public class ExcelProcessor {
private static Logger logger = LoggerFactory.getLogger(ExcelProcessor.class);
public void parseExcelFile(File excelFile) throws Exception{
final List<Employee> employeeList = new ArrayList<Employee>();
InputStream xmlMapping = new BufferedInputStream(ExcelProcessor.class.getClassLoader().getResourceAsStream("proBroMapping.xml"));
ReaderConfig.getInstance().setUseDefaultValuesForPrimitiveTypes(true);
ReaderConfig.getInstance().setSkipErrors(true);
InputStream inputXLS;
try{
XLSReader mainReader = ReaderBuilder.buildFromXML(xmlMapping);
inputXLS = new BufferedInputStream(new FileInputStream(excelFile));
final Map<String, Object> beans = new HashMap<String, Object>();
beans.put("employeeList", employeeList);
mainReader.read(inputXLS, beans);
System.out.println("Employee data are extracted successfully from the Excel file, number of Employees is: "+employeeList.size());
} catch(java.lang.OutOfMemoryError ex){
ex.printStackTrace();
throw new Exception(ex.getMessage());
} catch (IOException ex) {
logger.error(ex.getMessage());
throw new Exception(ex.getMessage());
} catch (SAXException ex) {
logger.error(ex.getMessage());
throw new Exception(ex.getMessage());
} catch (InvalidFormatException ex) {
logger.error(ex.getMessage());
throw new Exception(ex.getMessage());
} finally {
IOUtils.closeQuietly(inputStream);
}
}
}
希望这能帮助到遇到类似问题的任何人!