2017-01-02 41 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 
    } 
} 
相关问题