我的 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/