用java写一个读取大文件excel的工具类
时间: 2023-05-13 12:07:14 浏览: 227
读取大数据量的excel文件
好的,可以的。以下是一个简单的Java工具类,可以读取大文件Excel:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public static ArrayList<ArrayList<String>> readExcel(File file) throws IOException {
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
FileInputStream fis = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
ArrayList<String> rowData = new ArrayList<String>();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
rowData.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
rowData.add(Double.toString(cell.getNumericCellValue()));
break;
case Cell.CELL_TYPE_BOOLEAN:
rowData.add(Boolean.toString(cell.getBooleanCellValue()));
break;
default:
rowData.add("");
break;
}
}
data.add(rowData);
}
workbook.close();
fis.close();
return data;
}
}
```
这个工具类使用了Apache POI库,可以读取XLSX格式的Excel文件。它会将每一行的数据存储在一个ArrayList中,然后将所有的行数据存储在一个ArrayList<ArrayList<String>>中返回。
阅读全文