2014-02-21 79 views
3

我試圖刪除第三行如何使用apache poi刪除一行

這是我根據rgettman,Leo,zibi的評論所做的編輯。謝謝。

public class MainTest { 

    public static void main(String[] args) throws IOException { 

     FileInputStream file = new FileInputStream(new File("test.xlsx")); 
     XSSFWorkbook wb = new XSSFWorkbook(file); 
     XSSFSheet sheet = wb.getSheetAt(0); 
     sheet.removeRow(sheet.getRow(3)); 
//  sheet.shiftRows(3, 3, -1); 

     File outWB = new File("testResult.xlsx"); 
     OutputStream out = new FileOutputStream(outWB); 
     wb.write(out); 
     out.flush(); 
     out.close(); 


     System.exit(0); 
    } 

} 

但這刪除值在一排,但如果您正在使用XLS文件(而不是XLSX),那麼你應該使用HSSFWorkbook工作不會刪除該行

+0

我希望excel不期待xlsx文件 – Leo

+1

您正在將行3向下移動1.使用負數向上移位。 – rgettman

回答

8

。我只是測試下面的解決方案,一切工作正常:

File file = new File(....); 
    FileInputStream fis = new FileInputStream(file); 
    HSSFWorkbook wb = new HSSFWorkbook(fis); 
    HSSFSheet sheet = wb.getSheetAt(0); 

    sheet.shiftRows(3, 3, -1); 

    File outWB = new File(.....); 
    OutputStream out = new FileOutputStream(outWB); 
    wb.write(out); 
    out.flush(); 
    out.close(); 

甚至尤爲明顯使用Workbook類的工廠,它不鍵入認識到你:

Workbook wb = WorkbookFactory.create(file); 
    Sheet sheet = wb.getSheetAt(0); 
    sheet.shiftRows(3, 3, -1); 

belowe你可以找到一個函數,它不排它可以在xls和xlsx(測試;)中使用)。

Workbook wb = WorkbookFactory.create(file); 
Sheet sheet = wb.getSheetAt(0); 
removeRow(sheet, 2); 
File outWB = new File(...); 
OutputStream out = new FileOutputStream(outWB); 
wb.write(out); 
out.flush(); 
out.close(); 


public static void removeRow(Sheet sheet, int rowIndex) { 
    int lastRowNum = sheet.getLastRowNum(); 
    if (rowIndex >= 0 && rowIndex < lastRowNum) { 
     sheet.shiftRows(rowIndex + 1, lastRowNum, -1); 
    } 
    if (rowIndex == lastRowNum) { 
     Row removingRow = sheet.getRow(rowIndex); 
     if (removingRow != null) { 
      sheet.removeRow(removingRow); 
     } 
    } 
} 
+0

你可以考慮接受我的答案,如果它可以幫助你:) – zibi

+1

+1謝謝。這工作真棒。不過,我正在使用'xlsx'。你能否修改你的答案到'xlsx'謝謝。 – CHEBURASHKA

+0

您是否嘗試過工作簿工廠? – zibi

0

嘗試更好的特殊功能removeRow

此外,XSSFWorkbook用的.xlsx推廣工作。

1

見移行的defnition:

Shifts rows between startRow and endRow n number of rows. If you use a negative number, it will shift rows up. Code ensures that rows don't wrap around. Calls shiftRows(startRow, endRow, n, false, false); Additionally shifts merged regions that are completely defined in these rows (ie. merged 2 cells on a row to be shifted).

Specified by: shiftRows(...) in Sheet 
Parameters: 
    startRow the row to start shifting 
    endRow the row to end shifting 
    n the number of rows to shift 

所以爲了刪除您需要使用startRow = 3(從零開始的索引所以基本上第3行是第四行),endRow = sheet.getLastRowNum()n = -1以將選定的行,即從第4行向最後一行向上移動1行。