Frage

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.

War es hilfreich?

Lösung 2

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.

Andere Tipps

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.

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();
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top