Java - 无法在excel单元格中写入

时间:2013-12-18 10:00:04

标签: java excel nullpointerexception hssf

FileInputStream file = new FileInputStream(new File("//Users//"+ usr +"//Desktop//TNA//output//output.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheet("Sheet1");
Cell name_c = null;
Cell department_c = null;
Cell prev_depart_c = null;
HSSFRow row = sheet.createRow((short) 0);
HSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
department_c = sheet.getRow(2).getCell(1); // throws exception here
department_c.setCellValue(department);
prev_depart_c = sheet.getRow(3).getCell(1);
prev_depart_c.setCellValue(prev_depart);
emp_no_c = sheet.getRow(4).getCell(1);
emp_no_c.setCellValue(emp_no);
file.close();
FileOutputStream outFile =new FileOutputStream(new File("//Users//"+ usr +"//Desktop//TNA//output//output10.xls"));
workbook.write(outFile);
outFile.close();

我正在尝试编写现有的excel文件,但它会在注释区域中抛出java.lang.NullPointerException。任何建议或意见都非常感谢。

3 个答案:

答案 0 :(得分:2)

顺便说一下,你在文件路径中使用了冗余斜杠

File("//Users//"+ usr +"//Desktop//TNA//output//output.xls"));

一个斜线就足够了。斜杠(/)不必像反斜杠一样在字符串中进行转义。

答案 1 :(得分:1)

在您的代码中,此行HSSFRow row = sheet.createRow((short) 0);只会在位置0处创建一个新行。超出此范围的任何内容仍为null,因此当您尝试调用其上的任何方法时将抛出NPE。

为了能够写入一行中的单元格,您需要先在特定位置创建一行。

HSSFRow row = sheet.createRow(2); // create a row at rownum 2
// use the created row and add/edit cells in it.

答案 2 :(得分:1)

如果工作表上尚不存在单元格,则需要创建它们:

public class ExcelExample {

    public static void main(String[] args) throws IOException {
        FileInputStream file = new FileInputStream(new File("/output.xls"));
        HSSFWorkbook workbook = new HSSFWorkbook(file);
        HSSFSheet sheet = workbook.getSheet("Sheet1");

        Cell name_c = null;
        Cell department_c = null;
        Cell prev_depart_c = null;


        HSSFRow row = sheet.createRow((short) 0);
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        HSSFRow row2 = sheet.createRow(2);
        HSSFCell cell = row2.createCell(1);
        cell.setCellValue("5");

        HSSFRow row3 = sheet.createRow(3);
        HSSFCell cell2 = row2.createCell(1);
        cell2.setCellValue("5");

        file.close();
        FileOutputStream outFile =new FileOutputStream(new File("/output10.xls"));
        workbook.write(outFile);
        outFile.close();
    }
}