如何使用 Apache POI 移动特定单元格? [英] How to shift specific cells using Apache POI?

查看:54
本文介绍了如何使用 Apache POI 移动特定单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Excel 工作表在同一张工作表上包含不同的区域,例如:

My excel sheet contains different regions on the same sheet like:

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 中再添加一行(也保留所有旧行),它将变为:

I want to add new items into one of these regions without affecting the other regions. I tried using rowShift() method but it is also deleting the complete rows. Is there any way that can shift the specific cells down and can insert rows into the specific regions like this: In my given example I want to add one more row in region1 (also retaining all old rows) and it will become:

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

推荐答案

如果上述问题仍然存在,我可以给你一个相同的方法.

If the above issue still persisting, I can give you a method for the same.

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);
        }
    }       
}

这篇关于如何使用 Apache POI 移动特定单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆