2013-09-27 59 views
0

你好,任何人都可以足夠的善良,並告訴我爲什麼正是我得到這個代碼行上的空指針異常:cell = sheet.getRow(init_cell).getCell(0); init_cell = 7;但是當我用7替換上述行中的變量時,空指針消失。Apache POI:爲什麼我得到空指針異常?

查詢的結果集有多行。

public static void main(String[] args) throws Exception 
{ 
    int init_cell=7; 
    try { 
     Connection con = null; 
     Statement st = null; 
     ResultSet rs = null; 
     con = DriverManager.getConnection(
       "jdbc:postgresql://127.0.0.1:5432/DB", "xxxx", 
       "xxxx"); 

     st = con.createStatement(); 
     rs = st.executeQuery("select * from vs;"); 
     FileInputStream input_template = new FileInputStream(new File("C:\\Users\\xxxx\\Desktop\\ExcelWriteTest\\template-audit.xls")); 
     HSSFWorkbook template = new HSSFWorkbook(input_template); 
     HSSFSheet sheet = template.getSheet("Synthesis"); 

     while(rs.next()) 
     { 
      Cell cell = null; 
      cell = sheet.getRow(init_cell).getCell(0); 
     cell.setCellValue(rs.getString("serial_number")); 
     ++init_cell; 

     } 

     input_template.close(); 
     FileOutputStream out_template =new FileOutputStream(new File("C:\\Users\\xxxx\\Desktop\\ExcelWriteTest\\newaudit.xls")); 
     template.write(out_template); 
     out_template.close(); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 


} 

回答

1

的的getRow()函數將一個整數參數,這意味着「以該特定行說對於例如這裏的第七行中第一小區 [即getCell(0)]」它將插入值。