簡體   English   中英

如何使用Apache POI轉移特定單元格?

[英]How to shift specific cells using Apache POI?

我的Excel工作表包含同一工作表上的不同區域,如:

region1:                region2:       
John       2            A         1  
John       1            B         2  
Sue        1            C         3  
Sue        2            D         4  
Alice      5            E         5  
Bob        1            F         6  

我想在不影響其他區域的情況下將新項目添加到其中一個區域。 我嘗試使用rowShift()方法,但它也刪除了完整的行。 是否有任何方法可以將特定單元格向下移動並可以將行插入特定區域,如下所示:在我給出的示例中,我想在region1中添加一行(也保留所有舊行),它將變為:

region1:                region2:       
newval     newval       A         1  
John       2            B         2  
John       1            C         3  
Sue        1            D         4  
Sue        2            E         5  
Alice      5            F         6
Bob        1

如果上述問題仍然存在,我可以給你一個相同的方法。

public static void shiftCells(int startCellNo, int endCellNo, int shiftRowsBy, Sheet sheet){

    int lastRowNum = sheet.getLastRowNum();
    System.out.println(lastRowNum); //=7
    //      int rowNumAfterAdding = lastRowNum+shiftRowsBy;
    for(int rowNum=lastRowNum;rowNum>0;rowNum--){
        Row rowNew;
        if(sheet.getRow((int)rowNum+shiftRowsBy)==null){
            rowNew = sheet.createRow((int)rowNum+shiftRowsBy);
        }
        rowNew = sheet.getRow((int)rowNum+shiftRowsBy);
        Row rowOld = sheet.getRow(rowNum);
        System.out.println("RowNew is "+rowNum+" and Row Old is "+(int)(rowNum+shiftRowsBy));
        System.out.println("startCellNo = "+startCellNo+" endCellNo = "+endCellNo+" shiftRowBy = "+shiftRowsBy);
        for(int cellNo=startCellNo; cellNo<=endCellNo;cellNo++){
            rowNew.createCell(cellNo).setCellValue(rowOld.getCell(cellNo).getStringCellValue().toString());
            rowOld.getCell(cellNo).setCellValue("");
            System.out.println("working on " +cellNo);
        }
    }       
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM