java批量导入本地excel数据
时间: 2023-09-04 14:15:44 浏览: 77
可以使用Apache POI库来实现Java批量导入本地Excel数据。以下是一个示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelImporter {
public static void main(String[] args) {
String filePath = "path/to/excel.xlsx";
List<List<String>> data = readExcel(filePath);
// 处理导入的数据
}
public static List<List<String>> readExcel(String filePath) {
List<List<String>> data = new ArrayList<>();
try (FileInputStream inputStream = new FileInputStream(new File(filePath));
Workbook workbook = WorkbookFactory.create(inputStream)) {
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
List<String> rowData = new ArrayList<>();
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
rowData.add(cell.getStringCellValue());
break;
case NUMERIC:
rowData.add(String.valueOf((int) cell.getNumericCellValue()));
break;
case BOOLEAN:
rowData.add(String.valueOf(cell.getBooleanCellValue()));
break;
default:
rowData.add("");
break;
}
}
data.add(rowData);
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
```
这段代码读取指定路径下的Excel文件,将每行数据转化为一个字符串列表,再将每行数据添加到一个列表中返回。你可以根据需要修改代码来适应你的具体场景。
阅读全文