使用poi库为java在excel表中写入值的问题

问题描述 投票:0回答:1

我从我的程序中获取值,我想将它们保存在Excel文件中,我使用poi库,我应该有9张纸,在每张单页中我必须获得一个矩阵(行*列)在我的情况下(无论如何)行数* 13列),,但我只获得1个由数组中的姓氏命名的表,并仅由列号13填充

这是方法

public static void writeExcelSheet(String categoryName) throws IOException {
    Workbook workbook=new HSSFWorkbook();
    Sheet sheet=workbook.createSheet(categoryName);
    int allength=arraylistCategory.size();

    for(int row=0;row<allength;row++){
        for(int column=0;column<13;column++){
             Cell cell=sheet.createRow(row).createCell(column);
             cell.setCellValue(arraylistCategory.get(row)[column]);
        }
    }

        FileOutputStream outputStream=new FileOutputStream("mel coef excel sheet.xls");
        workbook.write(outputStream);
        outputStream.close();



    arraylistCategory.clear();
}

你能告诉我什么是错的或错的,谢谢你提前

java excel apache-poi
1个回答
3
投票

我应该有9张

您的方法只在工作簿中创建一个工作表。假设您尝试调用此方法9次,则每次调用此方法时都会重新创建一个新的空白Workbook,每次都会覆盖该文件。这就解释了为什么你只获得数组中的姓氏。

相反,创建一次Workbook,然后将其传递给此方法,以便您可以在相同的Workbook上创建工作表。然后在最后一次调用此方法之后,将其写入FileOutputStream

并且仅由第13列填充

你这里有类似的问题。您正在为每列创建createRow(row)行。执行此操作时,您将使用新的空Row覆盖任何行,并删除除最后一个值之外的所有单元格值。在内部Row循环外部创建for,但在外部for循环内部,并在内部for循环内使用它。

for(int row = 0; row < allength; row++){
    Row currentRow = sheet.createRow(row);
    for(int column = 0; column < 13; column++){
         Cell cell = currentRow.createCell(column);
         cell.setCellValue(arraylistCategory.get(row)[column]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.