如何使用java在空单元格上写?

时间:2012-08-13 00:24:09

标签: java excel report apache-poi

我目前正在用Java编写一个程序,该程序将运行多个测试并在excel之后立即生成报告。我能够通过Excel读取和写入,结果列中显示通过失败的结果。我能够在excel中编写这些,但是通过在单元格上提供默认值(例如默认值),所以代码只会覆盖它。我想在Comment列上写一条评论,但我不知道怎么写 null 单元格。以下是我生成的报告的截图(可用图像的链接)以及excel中的读写代码。

FileInputStream fileInputStream = new FileInputStream("ReportExcel.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheetAt(0);   

fileInput csvInputFile = new fileInput();
String[] sReturnValue = csvInputFile.arrayReturnSingleValue("fileInput.csv");
if (prodnameresult.equals(prodname) ){
    Pass++;
    totalResult++;
    System.out.println ("Testcase1: Branding-Customised Product Name is PASSED");
    //Harold's Input    
        HSSFRow row = worksheet.getRow(1);
        HSSFCell cell = row.getCell((short) 4);
        cell.setCellValue("Passed");
    } 
else{
    Fail++;
    totalResult++;
    System.out.println("Testcase1: Branding-Customised Product Name is FAILED");
    //assertEquals(prodnameresult.equals(prodname), true);
    //Harold's Input
         HSSFRow row = worksheet.getRow(1);
         HSSFCell cell = row.getCell((short) 4);
         cell.setCellValue("Failed");
    }

//Harold's Input
    FileOutputStream os = new FileOutputStream("ReportExcel.xls");
    workbook.write(os);
    os.close();
}

报告:

http://i47.tinypic.com/2s1lsfc.png

1 个答案:

答案 0 :(得分:3)

我无法访问该报告,但为了回答您的问题,如果您的单元格 null ,则应创建它,而不是如下所示:

HSSFCell cell = row.getCell((short) 4);
if(cell == null)
   cell = row.createCell((short) 4);
cell.setCellValue("Passed");

如果样式与单元格不同,则应该将样式重新应用于单元格。