1

i have written the following code with some help from google for exporting jtable to excel but i am not able to export it to excel and i am also getting null pointer .

cell.setCellValue(model.getValueAt(i, j).toString());

the whole code is

try {
        HSSFWorkbook fWorkbook = new HSSFWorkbook();
        HSSFSheet fSheet;
        fSheet = fWorkbook.createSheet("new Sheet");
        HSSFFont sheetTitleFont = fWorkbook.createFont();
        File file = new File("D:\\MOHIT\\bill report\\report.xls");         

        HSSFCellStyle cellStyle = fWorkbook.createCellStyle();
        sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //sheetTitleFont.setColor();
        TableModel model = report_table.getModel();

        TableColumnModel model1 = report_table.getTableHeader().getColumnModel();
        HSSFRow fRow1 = fSheet.createRow((short) 0);
        for (int i = 0; i < model1.getColumnCount(); i++){
            HSSFCell cell = fRow1.createCell((short) i);
            cell.setCellValue(model1.getColumn(i).getHeaderValue().toString());           

}
        for (int i = 1; i < model.getRowCount(); i++) {
            HSSFRow fRow = fSheet.createRow((short) i);
            for (int j = 1; j < model.getColumnCount(); j++) {
                HSSFCell cell = fRow.createCell((short) j);
                cell.setCellValue(model.getValueAt(i, j).toString());
                cell.setCellStyle(cellStyle);
            }
        }
        FileOutputStream fileOutputStream;
        fileOutputStream = new FileOutputStream(file);
        try (BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream)) {
            fWorkbook.write(bos);
        }
        fileOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

can somebody tell me why am i getting null pointer exception how to correct it.

Mohit Joshi
  • 53
  • 3
  • 9

1 Answers1

0

Try to replace

cell.setCellValue(model.getValueAt(i, j).toString());

by

cell.setCellValue(Objects.toString(model.getValueAt(i, j), ""));

And look the link which I've posted in my comment.

P.S. Class Objects is defined in the package java.util

Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48