0
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进入了评论区。非常感谢任何建议或意见。

4

3 回答 3

2

顺便说一句,您在文件路径中使用了多余的斜杠

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

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

于 2013-12-18T10:13:32.030 回答
1

在您的代码中,此行HSSFRow row = sheet.createRow((short) 0);仅在 position 处创建一个新行0。除此之外的任何东西都仍然存在null,因此当您尝试对其调用任何方法时都会抛出 NPE。

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

HSSFRow row = sheet.createRow(2); // create a row at rownum 2
// use the created row and add/edit cells in it.
于 2013-12-18T10:04:34.317 回答
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();
    }
}
于 2013-12-18T10:12:43.283 回答