java - 如何使用 Apache POI 移动特定单元格?

标签 java 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);
        }
    }       
}

关于java - 如何使用 Apache POI 移动特定单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3656176/

相关文章:

java - 在 Apache POI 中创建 CellStyle 库

java - 从带有分隔符的文件中读取

java - 通过数据报包发送数组的最佳方式是什么?

java - ReloadableResourceBundleMessageSource 与 ResourceBundleMessageSource - 缓存概念和其他差异

java - POI条形图生成一系列有问题

java - 使用 POI Java 提取 Word 文档表格单元格中的内容

java - 无法使用复制构造函数正确实例化新对象克隆

java - 未处理的警报异常 : Modal Dialog Present (Selenium)

java - 使用apache poi 3.9迭代写入xlsx文档时出现异常

java - 从模板创建新文档