Java - Unable write in excel cell

608 views Asked by At
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();

I'm trying to write existing excel file but it throws me java.lang.NullPointerException in commented area. Any advice or comments is highly appreciated.

3

There are 3 answers

0
Rahul On BEST ANSWER

In your code, this line HSSFRow row = sheet.createRow((short) 0); just creates a new row at position 0. Anything beyond that is still null and thus will throw a NPE when you try to call any method on it.

To be able to write to a cell in a row, you need to first create a row at the particular position.

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

If the cells do not already exist on the worksheet you need to create them:

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();
    }
}
0
Honza Zidek On

By the way, you use redundant slashes in your file paths

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

One slash is sufficient. Slash (/) does NOT have to be escaped in Strings like backslash.