有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Apache POI将Excel文件中的一行复制到另一个新Excel文件中

我正在使用Java8和ApachePOI3.17。我有一个Excel文件,我只想保留几行,删除其他行。但我的Excel有4万行,一行一行删除相当长(将近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());
        }
    }
}

共 (0) 个答案