Apache POI xls column Remove

前端 未结 5 432
孤城傲影
孤城傲影 2020-12-17 17:47

I don\'t find how to remove a column with the Apache POI API.
I would appreciate a sample code or help on this point.

5条回答
  •  醉梦人生
    2020-12-17 18:36

    The answer of cporte is perfectly fine but imho a bit hard to read.


    The Idea:

    For every row, delete the cell representing the column which shall be deleted and move all cells to the right of this column one to the left.


    The simplified Implementation:

    //Variables for completeness
    Sheet sheet;
    int columnToDelete;
    
    for (int rId = 0; rId <= sheet.getLastRowNum(); rId++) {
        Row row = sheet.getRow(rId);
        for (int cID = columnToDelete; cID < row.getLastCellNum(); cID++) {
            Cell cOld = row.getCell(cID);
            if (cOld != null) {
                row.removeCell(cOld);
            }
            Cell cNext = row.getCell(cID + 1);
            if (cNext != null) {
                Cell cNew = row.createCell(cID, cNext.getCellType());
                cloneCell(cNew, cNext);
                sheet.setColumnWidth(cID, sheet.getColumnWidth(cID + 1));
            }
        }
    }
    


    The clone cell method copied from the other answer for completeness:

    private static void cloneCell( Cell cNew, Cell cOld ){
        cNew.setCellComment( cOld.getCellComment() );
        cNew.setCellStyle( cOld.getCellStyle() );
    
        switch ( cNew.getCellType() ){
            case Cell.CELL_TYPE_BOOLEAN:{
                cNew.setCellValue( cOld.getBooleanCellValue() );
                break;
            }
            case Cell.CELL_TYPE_NUMERIC:{
                cNew.setCellValue( cOld.getNumericCellValue() );
                break;
            }
            case Cell.CELL_TYPE_STRING:{
                cNew.setCellValue( cOld.getStringCellValue() );
                break;
            }
            case Cell.CELL_TYPE_ERROR:{
                cNew.setCellValue( cOld.getErrorCellValue() );
                break;
            }
            case Cell.CELL_TYPE_FORMULA:{
                cNew.setCellFormula( cOld.getCellFormula() );
                break;
            }
        }
    
    }
    

提交回复
热议问题