2013-09-27 69 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)]”它将插入值。