我正在尝试将我的测试结果/数据写入运行时的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);
}
}
答案 0 :(得分: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 each语法,如下所示:
for (Row row : sheet) {
for (Cell cell : row) {
// do something with the cell
}
}