2016-11-07 112 views
0

我已經寫了下面的代碼,從谷歌的一些幫助出口Jtable爲Excel,但我不能夠出口到Excel,我也得到空指針。導出Jtable在Excel中的優秀NetBeans

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

有人可以告訴我,爲什麼我會收到空​​指針異常如何糾正它。

回答

0

嘗試通過

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

更換

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

而且看我已經張貼在我的評論的鏈接。

P.S.類Objects被定義在包java.util

+0

非常感謝bro替換解決了我的問題 –