用java分页写一个读写大文件excel分成若干份的工具类
时间: 2023-05-16 19:06:54 浏览: 76
好的,以下是一个用Java分页读写大文件Excel并分成若干份的工具类的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;
public class ExcelSplitter {
private static final int DEFAULT_PAGE_SIZE = 10000;
public static void split(File inputFile, int pageSize) throws IOException {
FileInputStream fis = new FileInputStream(inputFile);
Workbook workbook = new HSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = sheet.getLastRowNum() + 1;
int pageCount = (rowCount + pageSize - 1) / pageSize;
List<Workbook> workbooks = new ArrayList<>();
for (int i = 0; i < pageCount; i++) {
Workbook newWorkbook = new HSSFWorkbook();
Sheet newSheet = newWorkbook.createSheet();
workbooks.add(newWorkbook);
int startRow = i * pageSize;
int endRow = Math.min(startRow + pageSize, rowCount);
for (int j = startRow; j < endRow; j++) {
Row oldRow = sheet.getRow(j);
Row newRow = newSheet.createRow(j - startRow);
for (int k = 0; k < oldRow.getLastCellNum(); k++) {
Cell oldCell = oldRow.getCell(k);
Cell newCell = newRow.createCell(k);
newCell.setCellValue(oldCell.getStringCellValue());
}
}
}
fis.close();
for (int i = 0; i < workbooks.size(); i++) {
File outputFile = new File(inputFile.getParentFile(), inputFile.getName() + "." + (i + 1) + ".xls");
FileOutputStream fos = new FileOutputStream(outputFile);
workbooks.get(i).write(fos);
fos.close();
}
}
public static void split(File inputFile) throws IOException {
split(inputFile, DEFAULT_PAGE_SIZE);
}
}
```
使用示例:
```java
ExcelSplitter.split(new File("input.xls"), 5000);
```
这将把名为"input.xls"的文件分成若干份,每份最多包含5000行数据,并保存为"input.xls.1.xls"、"input.xls.2.xls"等文件。如果不指定分页大小,则默认为10000行。