简体   繁体   English

使用Apache POI在Excel中开始新行的问题

[英]Problems with starting a new row in Excel with Apache POI

I'm using the apache poi package to create a spreadsheet of figures which represent features of a shape (area, perimeter, centroid). 我正在使用apache poi包来创建一个数字电子表格,这些数字电子表格表示形状的特征(区域,周长,质心)。 The problem is that i have a method: writeDatabase() which outputs the features of the shape as they are found, the output spreadsheet looks like this: http://s23.postimg.org/hqsfg76jv/Capture.png 问题是我有一个方法:writeDatabase()输出找到的形状特征,输出电子表格看起来像这样: http : //s23.postimg.org/hqsfg76jv/Capture.png

All of these figures need to be in the same line, and then a new line needs to be taken for the next record. 所有这些数字都必须在同一行中,然后需要为下一条记录使用新的一行。 the writeDatabase method is shown below writeDatabase方法如下所示

public static void writeDatabase(int value, int cellNum){

    try {
        Cell cell1=null;
        FileInputStream file = new FileInputStream(new File("features.xls"));
        Workbook workbook = new HSSFWorkbook(file);
        Sheet sheet = workbook.getSheetAt(0);

        int lastRow = sheet.getPhysicalNumberOfRows();

        cell1 = sheet.createRow(lastRow).createCell(cellNum);
        cell1.setCellValue(value);

        FileOutputStream outFile =new FileOutputStream(new File("features.xls"));
        workbook.write(outFile);
        outFile.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I think the problem is with this line being called each time, but i cant think of an alternative: int lastRow = sheet.getPhysicalNumberOfRows(); 我认为问题在于每次都调用此行,但我想不出另一种选择:int lastRow = sheet.getPhysicalNumberOfRows();

Any ideas? 有任何想法吗?

You need to provide some indication of whether a new line should be started or not (unless you can tell that a new line is starting simply because cellNum is 0?) 您需要提供一些关于是否应该开始新行的指示(除非您可以仅仅因为cellNum为0才能告诉新行正在开始?)

Then, you can either create a new row, or use the existing row: 然后,您可以创建一个新行,也可以使用现有行:

    int lastRow = sheet.getPhysicalNumberOfRows();

    Row row;
    if (startNewRow) {
        row = sheet.createRow(lastRow);
    } else {
        row = sheet.getRow(lastRow - 1);
    }

    cell1 = row.createCell(cellNum);
    cell1.setCellValue(value);

Where startNewRow might be set based on cellNum , or might be an additional parameter that is passed into writeDatabase , whichever is appropriate. 其中startNewRow可以基于cellNum设置,或者可以是传递到writeDatabase的附加参数,以适当的为准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM