我正在尝试编写我的测试结果/数据,以便在运行时表现出色,我为此编写了以下代码。编译此代码时我没有收到任何错误,但是结果没有写入其中。有人可以帮我解决这个问题吗?
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);
}
}
最佳答案
我本来打算将此作为评论,但它太长了。
我可以对您的代码提出一些评论。
首先,您似乎正在迭代并计算工作表中存在的行。然后您将在该索引处创建一个新行。由于电子表格可能缺少行,因此这仅适用于非常特定类型的电子表格。也就是说,没有丢失行,并且您总是希望在下一个空白位置添加下一行。而不是:
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);
此外,为此您甚至不需要迭代器,但是当您确实需要迭代电子表格的行和单元格时,最好使用 foreach 语法,如下所示:
for (Row row : sheet) {
for (Cell cell : row) {
// do something with the cell
}
}
关于java - 无法使用 POI 在运行时写入 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41424408/