excel表转换成java集合
时间: 2023-08-17 13:05:33 浏览: 92
读取Excel文件将数据存入map集合
4星 · 用户满意度95%
要将Excel表转换为Java集合,您可以使用Apache POI库来读取Excel文件,并将数据存储到Java集合中。下面是一个基本的示例代码:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExcelToJavaCollection {
public static void main(String[] args) {
String excelFilePath = "path/to/your/excel_file.xlsx";
try (FileInputStream fis = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheetAt(0);
List<Map<String, String>> data = new ArrayList<>();
Row headerRow = sheet.getRow(0);
for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row currentRow = sheet.getRow(rowIndex);
Map<String, String> rowMap = new HashMap<>();
for (int columnIndex = 0; columnIndex < headerRow.getLastCellNum(); columnIndex++) {
Cell cell = currentRow.getCell(columnIndex);
String header = headerRow.getCell(columnIndex).getStringCellValue();
String value = "";
if (cell != null) {
switch (cell.getCellType()) {
case STRING:
value = cell.getStringCellValue();
break;
case NUMERIC:
value = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
value = String.valueOf(cell.getBooleanCellValue());
break;
// Add more cases for other cell types if needed
}
}
rowMap.put(header, value);
}
data.add(rowMap);
}
// Use 'data' list containing the Excel data in your Java code
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请确保将"path/to/your/excel_file.xlsx"替换为实际的Excel文件路径。此示例假设您的Excel表的第一行是标题行,随后的行是数据行。在Java集合中,每行数据将存储为一个`Map<String, String>`,其中键是标题,值是对应的单元格值。
阅读全文