本文主要是介绍使用Apache POI解析excel,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.使用Apache POI解析excel,包括.xls和.xlsx
- Apache POI 针对Workbook有两种不同实现方式,分别是HSSFWorkbook(解析.xls文件)和XSSFWorkbook(解析.xlsx文件)
2.Maven依赖:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version>
</dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version>
</dependency>
3.写一份既可以解析.xls又可以解析.xlsx文件的代码
public class Leo_Test
{public static void main(String[] args) throws IOException, EncryptedDocumentException, InvalidFormatException{FileInputStream fis = new FileInputStream(new File("C:\\Leo_Test_EntitlementModel.xls"));Workbook workbook = WorkbookFactory.create(fis);for(int i=0;i<workbook.getNumberOfSheets();i++){Sheet sheet = workbook.getSheetAt(i);Iterator<Row> rowIterator = sheet.iterator();while(rowIterator.hasNext()){Row row = rowIterator.next();Iterator<Cell> cellIterator = row.iterator();while(cellIterator .hasNext()){Cell cell = cellIterator.next();DataFormatter dataFormatter = new DataFormatter();String cellValue = dataFormatter.formatCellValue(cell);System.out.println(cellValue);}}}}
}
4.结果
5.参考文档:
- https://www.callicoder.com/java-read-excel-file-apache-poi/
- https://howtodoinjava.com/apache-commons/readingwriting-excel-files-in-java-poi-tutorial/
这篇关于使用Apache POI解析excel的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!