无法使用for循环在Excel Sheet中写入数据(Apache_poi)

时间:2014-07-18 13:57:43

标签: java excel swing apache apache-poi

我正在尝试使用for循环将数据写入Excel工作表。但它只写在第一个单元格上,不再进行迭代。我尝试了很多,但无法解决这个问题。我的鳕鱼有什么问题。请帮忙。 这是我到目前为止所做的事情

 HSSFRow row1 = sheet.createRow((short) 1);
            String[] cellname = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I"};
            String[] fields = new String[]{"Student's Name", "Father's Name", "Mother's Name", "Address", "Phone No", "Date Of Birth", "Roll NO", "Class", "subjectMajor"};
            for (int i = 0; i <= 9; i++) {
                String Cellname = cellname[i] + 2;
                System.out.print(Cellname);
                HSSFCell CellName = row1.createCell((short) i);
                CellName.setCellValue(fields[i]);
                wb.write(output);
                output.close();
            }

1 个答案:

答案 0 :(得分:2)

  • 实际上,您甚至不需要将单元格坐标指定为&#34; A2&#34;,&#34; B2&#34;等等。您已经定义了哪个单元格在为createRow()createCell()方法提供参数时填充。例如:

    // creating an HSSFCell at "D9" and setting its value
    // "D" column has index 3; row number 9 has index 8 (starting index is 0)
    HSSFRow row = sheet.createRow( 8 );
    HSSFCell cell = row.createCell( 3 );
    cell.setCellValue( 1341.873 );
    
  • 另外,为避免ArrayIndexOutOfBoundsException,请在循环中使用<代替<=。否则,字段[9]将尝试访问第10个元素,而您的数组只有9个。不要忘记,数组也基于&#34; 0&#34; (第一个元素的索引为0,而不是1)。并且,您最好使用fields.length()而不是直接指定9。这样做,当您在fields[]数组中添加/删除某些列名称时,您不必更改循环限制。

  • 如评论中所述,wb.write(output)output.close()将在循环之后放置,通常在程序结束时。

所以这是执行任务的完整代码。希望它有所帮助!

String[] fields = new String[] { "Student's Name", "Father's Name", "Mother's Name", "Address", "Phone No", "Date Of Birth", "Roll NO", "Class", "subjectMajor" };

// Row with index 1 is the second row in Excel sheet
HSSFRow row1 = sheet1.createRow( 1 );

// Filling the row with the given data, one element per cell, 
// starting from the "A" column (cellIndex = 0).
for ( int cellIndex = 0; cellIndex < fields.length; cellIndex++ ) {
    HSSFCell cell = row1.createCell( cellIndex );
    cell.setCellValue( fields[cellIndex] );
}

// Writing a workbook to the disk
try {
    FileOutputStream fileOut = new FileOutputStream( "students.xls" );
    wb.write( fileOut );
    fileOut.close();
} catch ( IOException e ) {
    System.out.println( "IOException:" );
    System.out.println( e.getMessage() );
}