首页 > 解决方案 > 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());
        }
    }
}

标签: javaexcelapache-poi

解决方案


推荐阅读