将jtable导出为java netbeans中的excel

时间:2016-11-07 09:25:02

标签: java excel swing netbeans jtable

我在谷歌的帮助下编写了以下代码,用于将jtable导出到excel但是我无法将其导出到excel,我也得到了空指针。

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

整个代码是

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();
    }

有人可以告诉我为什么我得到空指针异常如何纠正它。

1 个答案:

答案 0 :(得分:0)

尝试替换

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

通过

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

查看我在评论中发布的链接。

P.S。课程Objects

中定义了课程java.util