JExcel-在关闭WritableWorkbook之前修改多个单元格

时间:2018-07-25 22:12:43

标签: java excel for-loop jexcelapi

我试图在单元格(0,0)中放置标题,然后使用for()循环将文件路径添加到以下每一行中。但是,我只能添加一行代码。标题之后,Excel文档中的其他单元格均未修改。

在这里创建文件:

private void chooseSheetActionPerformed(java.awt.event.ActionEvent evt) {                                            
        sheetNum = chooseSheet.getSelectedIndex() - 1;
        try {
            WritableWorkbook workbook = Workbook.createWorkbook(newXls);
            workbook.createSheet("Sheet1", 0);
            workbook.write();
            workbook.close();

            writeXls();
        } catch (Exception ex) {
            Logger.getLogger(NewScore.class.getName()).log(Level.SEVERE, null, ex);
        }
    }  

这是我尝试写的地方:

public void writeXls() throws Exception {
    Workbook wb = Workbook.getWorkbook(newXls);
    WritableWorkbook copy = Workbook.createWorkbook(newXls, wb);
    WritableSheet ws = copy.getSheet(sheetNum);
    WritableCell cell;

    // Body Part - Title
    Label lab = new Label(0,0,partName);
    cell = (WritableCell) lab;
    ws.addCell(cell);
    copy.write();
    // Image Info
    int i = 1;
    for (File file : imageArray(dir)) {
        Label label = new Label (0,i,"test" + i);
        cell = label;
        ws.addCell(cell);
        copy.write();
        i++;
    }
    copy.close();
}

是否有一种方法可以使我的for()循环起作用,还是我需要以其他方式解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

好的。最初,无论您是尝试创建新工作簿还是编辑现有工作簿,我都很困惑。但是看来您这里需要一个新的。

在代码示例中似乎有两个问题。 第一个是您检索刚刚创建的excel文件并将其内容复制到自身中。

Workbook wb = Workbook.getWorkbook(newXls);
WritableWorkbook copy = Workbook.createWorkbook(newXls, wb);

我注意到的另一件事是,为了保存所有更改,最后只需要在WritableWorkbook实例上调用一次write。

我完成了这样的代码。

private static final String FILE_NAME = "D:/test_out.xls";
private static final String SHEET_NAME = "Test sheet name";
private static final int SHEET_INDEX = 0;
private static final String HEADER = "My header";

public static void main(String[] args) throws Exception {
    WritableWorkbook writableWorkbook = Workbook.createWorkbook(new File(FILE_NAME));
    WritableSheet writableSheet = writableWorkbook.createSheet(SHEET_NAME, SHEET_INDEX);

    int columnIndex = 0;
    int rowIndex = 0;

    writableSheet.addCell(new Label(columnIndex, rowIndex, HEADER));

    for (String value : Arrays.asList("First value", "Second value", "Another value")) {
        writableSheet.addCell(new Label (columnIndex, ++rowIndex, value));
    }

    writableWorkbook.write();
    writableWorkbook.close();
}

它为我创建了一张一张Excel文件。该工作表包含具有4个单元格的一列:我的标题,第一个值,第二个值,另一个值。当然,您可以随意放置所需的任何值:)