POI读取excel格式兼容问题解决办法(.xlsx、.xls)

使用apache poi读取excel时为了兼容excel .xlsx和.xls格式,用WorkbookFactory替换HSSF(HSSFWorkbook)和XSSF(XSSFWorkbook)解决格式兼容问题。

依赖包:

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>4.1.2</version>
		</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
      <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.1.2</version>
      </dependency>

依赖类

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;

用法:

WorkbookFactory.create(InputStream in) API读取excel:

// Handles both XSSF and HSSF automatically
Workbook workbook = WorkbookFactory.create(new FileInputStream(file)); 
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
//to do
}

或使用Workbook对HSSFWorkbook、XSSFWorkbook引用进行泛化。

.xls格式:

Workbook wb = new HSSFWorkbook();

.xlsx格式:

Workbook wb = new XSSFWorkbook();