1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java实现读取excel表格中的数据 兼容xls和xlsx

java实现读取excel表格中的数据 兼容xls和xlsx

时间:2024-01-28 18:32:03

相关推荐

java实现读取excel表格中的数据 兼容xls和xlsx

前言

利用 java 实现读取 excel 表格中的数据,兼容 xls 与 xlsx 格式,不用额外做区分,写不同的实现方法。

引入的依赖包

<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.17</version></dependency>

java 代码实现

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;import org.apache.poi.ss.usermodel.*;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.List;/*** @author yuhuofei* @version 1.0* @description 读取excel表格中的数据,并处理,兼容xls和xlsx* @date /9/10 19:40*/public class ExcelUtil {public static List<List<String>> readExcel(String excelFilePath) {List<List<String>> result = new ArrayList<>();if (excelFilePath.endsWith(".xlsx") || excelFilePath.endsWith(".xls")) {result = handleData(excelFilePath);}return result;}//读取后缀是xlsx的excel表格public static List<List<String>> handleData(String excelFilePath) {List<List<String>> result = new ArrayList<>();try (InputStream inputStream = new FileInputStream(excelFilePath);Workbook xssfWorkbook = WorkbookFactory.create(inputStream)) {//循环每一页,并处理当前的循环页for (Sheet sheet : xssfWorkbook) {if (sheet == null) {continue;}for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {//Row表示每一行的数据Row row = sheet.getRow(rowNum);if (null != row) {int minColIx = row.getFirstCellNum();int maxColIx = row.getLastCellNum();List<String> rowList = new ArrayList<>();//遍历该行,并获取每一个cell的数据for (int colIx = minColIx; colIx < maxColIx; colIx++) {Cell cell = row.getCell(colIx);if (cell == null) {continue;}rowList.add(cell.toString());}result.add(rowList);}}}} catch (IOException | InvalidFormatException e) {System.out.println(e);}return result;}public static void main(String[] args) {String path1 = "D:/demo/test/Desktop/test01.xls";List<List<String>> list1 = readExcel(path1);System.out.println(list1);String path2 = "D:/demo/test/Desktop/test02.xlsx";List<List<String>> list2 = readExcel(path2);System.out.println(list2);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。