我在使用Apache POI将一些数据写入Excel工作表时遇到问题。
我想多次调用一个函数,该函数会将数据写入我创建的Excel工作表中。

有什么方法可以在函数结尾每次将指针移到下一行???

我的代码在下面给出...

public static void excelLog(String filename , String message)
  {

    String dest="D:\\testexcel.xls";
    HSSFWorkbook myWorkBook = new HSSFWorkbook();
    HSSFSheet mySheet = myWorkBook.createSheet();
    HSSFRow myRow = null;
    HSSFCell myCell = null;
    String excelData [][] = new String [1][2];
    excelData[0][0]=filename;
    excelData[0][1]=message;

    myRow = mySheet.createRow(rowNum);

    for (int cellNum = 0; cellNum < 2 ; cellNum++){
    myCell = myRow.createCell((short) cellNum);
    myCell.setCellValue(excelData[rowNum][cellNum]);

    }
    rowNum++;

    try{
        FileOutputStream out = new FileOutputStream(dest);
        myWorkBook.write(out);
        out.close();
    }catch(Exception e){
        e.printStackTrace();
    }
 }


请帮助我。
谢谢 :)

最佳答案

这是修改后的代码,因此支持动态列大小。想法是创建一次行,如果该行已经存在,则重用它。

import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class PoiSample {

private static String dest = "D:\\testexcel.xls";
private static HSSFWorkbook myWorkBook = new HSSFWorkbook();
private static HSSFSheet mySheet = myWorkBook.createSheet();

private static void excelLog(int row, int col, String value) {
    HSSFRow myRow = mySheet.getRow(row);

    if (myRow == null)
        myRow = mySheet.createRow(row);

    HSSFCell myCell = myRow.createCell(col);
    myCell.setCellValue(value);
}

public static void main(String[] args) {
    int numCol = 10; // assume 10 cols

    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < numCol; j++) {
            excelLog(i, j, "Row : " + i + ", Cell : " + j);
        }
    }

    try {
        FileOutputStream out = new FileOutputStream(dest);
        myWorkBook.write(out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


}

10-05 23:13