java的实体类固定如何获取多的xlsx的所有数据
时间: 2024-02-03 08:15:47 浏览: 54
要获取多个xlsx文件的所有数据,可以使用Apache POI库来读取Excel文件。具体步骤如下:
1. 引入Apache POI库的依赖,例如在Maven项目中可以添加以下依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 创建一个Excel文件读取器,例如:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelReader {
public static List<List<String>> readExcel(File file) throws IOException {
List<List<String>> data = new ArrayList<>();
try (FileInputStream inputStream = new FileInputStream(file)) {
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row row = sheet.getRow(rowIndex);
if (row == null) {
continue;
}
List<String> rowData = new ArrayList<>();
for (int columnIndex = 0; columnIndex < row.getLastCellNum(); columnIndex++) {
Cell cell = row.getCell(columnIndex, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
String cellValue = "";
if (cell != null) {
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA:
cellValue = String.valueOf(cell.getCellFormula());
break;
default:
cellValue = "";
}
}
rowData.add(cellValue);
}
data.add(rowData);
}
}
return data;
}
}
```
3. 遍历所有要读取的Excel文件,例如:
```java
import java.io.File;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
File[] files = new File("./data").listFiles();
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".xlsx")) {
List<List<String>> data = ExcelReader.readExcel(file);
System.out.println("File: " + file.getName());
for (List<String> rowData : data) {
System.out.println(rowData);
}
System.out.println();
}
}
}
}
```
其中,"./data"是存放所有要读取的Excel文件的目录。
阅读全文