java - Apache POI 将一行从 Excel 文件复制到另一个新的 Excel 文件
问题描述
我正在使用 JAVA 8 和 Apache POI 3.17。我有一个 Excel 文件,我只想保留几行并删除其他行。但是我的 Excel 有 40K 行,并且一一删除它们很长(将近 30 分钟:/)
所以我尝试改变我做这件事的方式。现在我认为最好只在excel源中获取我需要的行并复制到另一个新的。但到目前为止我所尝试的并不有效。
我有我所有的行,并想保留在一个列表中。但这不起作用并为我创建了一个空白的 excel:
public void createExcelFileFromLog (Path logRejetFilePath, Path fichierInterdits) throws IOException {
Map<Integer, Integer> mapLigneColonne = getRowAndColumnInError(logRejetFilePath);
Workbook sourceWorkbook = WorkbookFactory.create(new File(fichierInterdits.toAbsolutePath().toString()));
Sheet sourceSheet = sourceWorkbook.getSheetAt(0);
List<Row> listLignes = new ArrayList<Row>();
// get Rows from source Excel
for (Map.Entry<Integer, Integer> entry : mapLigneColonne.entrySet()) {
listLignes.add(sourceSheet.getRow(entry.getKey()-1));
}
// The new Excel
Workbook workbookToWrite = new XSSFWorkbook();
Sheet sheetToWrite = workbookToWrite.createSheet("Interdits en erreur");
// Copy Rows
Integer i = 0;
for (Row row : listLignes) {
copyRow(sheetToWrite, row, i);
i++;
}
FileOutputStream fos = new FileOutputStream(config.getDossierTemporaire() + "Interdits_en_erreur.xlsx");
workbookToWrite.write(fos);
workbookToWrite.close();
sourceWorkbook.close();
}
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
newRow = sourceRow;
}
编辑:更改 copyRow 的方法会更好,但日期格式很奇怪,原始行中的空白单元格消失了。
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
Integer i = 0;
for (Cell cell : sourceRow) {
if(cell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(cell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(cell.getStringCellValue());
}
i++;
}
}
编辑2:保持空白单元格
private static void copyRow(Sheet newSheet, Row sourceRow, Integer newRowNum, Integer cellToColor) {
Row newRow = newSheet.createRow(newRowNum);
//Integer i = 0;
int lastColumn = Math.max(sourceRow.getLastCellNum(), 0);
for(int i = 0; i < lastColumn; i++) {
Cell oldCell = sourceRow.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if(oldCell == null) {
newRow.createCell(i).setCellValue("");
} else if (oldCell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(oldCell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(oldCell.getStringCellValue());
}
}
}
解决方案
推荐阅读
- html - 排列单选按钮
- javascript - 如何从 Mapbox 的 Terrain-RGB 中调用高程组件?
- python - 'str' 和 'Node' 的实例之间不支持'<'?
- c# - 如何保存 GUID ID mongodb
- javascript - 获取剑道电子表格中特定列的值
- java - 如何解决 Plaid API 的错误 - “类型回调不是通用的;它不能被参数化......”
- c++ - 如何使用基于模板的类和智能指针?
- typescript - 为什么我在这里收到“类型上不存在属性”错误?
- c - 按整数而不是浮点数对数组进行排序时遇到问题。多个错误
- r - 如何解释 summaryRprof 产生的输出?