2017-01-02 21 views
0

我想寫我的測試結果/數據在運行時爲我寫了下面的代碼。編譯這段代碼時我沒有收到任何錯誤,但是結果沒有寫在這裏。有人能幫我解決這個問題嗎?無法使用POI在運行時寫入excel

public void WritetoExcel(String filepath, String OrderID) throws IOException 
    { 
     FileInputStream ExcelFile = new FileInputStream(filepath); 
     System.out.println(filepath); 
     ExcelWBook = new XSSFWorkbook(ExcelFile); 
     System.out.println("WorkBook Sucessfully"); 
     ExcelWSheet = ExcelWBook.getSheetAt(0); 
     System.out.println("Sheet Sucessfully"); 
     Iterator<Row> rowIterator= ExcelWSheet.iterator(); 
     int RowNum =0; 

     while (rowIterator.hasNext()) 
      { 
       Row row=rowIterator.next(); 
       RowNum++; 
      } 
     try 
     { 
      Row = ExcelWSheet.createRow(RowNum); 
      Iterator<Cell> cellIterator=Row.iterator(); 
      Cell = Row.getCell(0); 
      if (Cell==null) 
       { 
        Cell=Row.createCell(0); 
        Cell.setCellValue(OrderID);     
       } 
      else 
       { 
        Cell.setCellValue(OrderID); 
       } 
      FileOutputStream fileOut = new FileOutputStream(filepath); 
      ExcelWBook.write(fileOut); 
      fileOut.flush(); 
      fileOut.close(); 
     } 

     catch (Exception e) 
     { 
      throw (e); 
     } 

    } 
+1

'catch(Exception e){throw(e); } - - 認真?!? 'Row = ExcelWSheet.createRow(RowNum);'這怎麼編譯?!? –

+0

通過編譯我的意思是,它不顯示任何錯誤。我是Java新手,因此避免了任何語法錯誤。指導將不勝感激 –

+0

看看這個鏈接是否有幫助 - http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/ – Rao

回答

1

我打算讓這個評論,但它太長了。

我可以對你的代碼做一些評論。

首先,似乎您正在迭代並計算工作表中存在的行。然後你在該索引處創建一個新行。由於電子表格可能缺少行,因此這隻適用於特定類型的電子表格。也就是說,一個沒有缺失的行,你總是想在下一個空白處添加下一行。相反的:

Iterator<Row> rowIterator= ExcelWSheet.iterator(); 
int RowNum =0; 

while (rowIterator.hasNext()) 
    { 
     Row row=rowIterator.next(); 
     RowNum++; 
    } 
try 
{ 
    Row = ExcelWSheet.createRow(RowNum); 

你可以很容易地使用:

int rowNum = ExcelWSheet.getLastRowNum() + 1; 
Row row = ExcelWSheet.createRow(rowNum); 

然後你在該行的第一列寫orderId。相反的:

Iterator<Cell> cellIterator=Row.iterator(); 
Cell = Row.getCell(0); 
if (Cell==null) 
    { 
     Cell = Row.createCell(0); 
     Cell.setCellValue(OrderID);     
    } 
else 
    { 
     Cell.setCellValue(OrderID); 
    } 

你可以只使用:

Cell cell = row.createCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK); 
cell.setCellValue(OrderID); 

此外,對於這一點,你甚至不需要迭代器,但是當你真的需要通過的行和單元格進行迭代電子表格最好使用這樣的每個語法:

for (Row row : sheet) { 
    for (Cell cell : row) { 
     // do something with the cell 
    } 
}