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