2010-09-07 44 views
3

我的Excel表包含在同一張紙上喜歡不同的國家和地區:如何使用Apache POI移動特定的單元格?

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 
+0

你已經顯示的例子只是用* newval newval *替換單元格* John 2 *,它不會改變任何東西。那是你要的嗎? – JoseK 2010-09-07 11:34:16

+0

錯誤我無法寫滿整行。請閱讀該行(同時保留所有舊值)。我不需要替換,想要添加。 – chahal 2010-09-07 11:44:58

+0

是否有沒有人有任何想法:( – chahal 2010-09-08 06:29:53

回答

3

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

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); 
     } 
    }  
} 
相關問題