How to fill some rows of Excel in a JTable on Java?

前端 未结 1 435
旧巷少年郎
旧巷少年郎 2021-01-28 07:02

I\'m working on importing data from an Excel file into a Java JTable. I can import all the sheet, but I want to import only some rows. This is the code I\

1条回答
  •  一整个雨季
    2021-01-28 07:06

    Starting from this complete example, the following code creates a table having the indicated number of COLUMNS from MIN_ROW to MAX_ROW, inclusive.

    view formula

    private static final int COLUMNS = 4;
    private static final int MIN_ROW = 3;
    private static final int MAX_ROW = 5;
    …
    DataFormatter format = new DataFormatter();
    DefaultTableModel model = new DefaultTableModel(0, COLUMNS);
    for (Row row : sheet) {
        if (row.getRowNum() >= MIN_ROW && row.getRowNum() <= MAX_ROW) {
            Vector rowData = new Vector();
            for (Cell cell : row) {
                rowData.add(format.formatCellValue(cell));
            }
            model.addRow(rowData);
        }
    }
    …
    JFrame f = new JFrame("TableTest");
    f.add(new JTable(model));
    

    Addendum: Looking closer at your current approach, you may want to accommodate non-contiguous rows. It may help to replace your array with a List. You can then use contains() in place of the predicate above:

    if (a.contains(row.getRowNum()) {…}
    

    Addendum: To evaluate formulae, you can pass a FormulaEvaluator to formatCellValue().

    view evaluated

    FormulaEvaluator eval = book.getCreationHelper().createFormulaEvaluator();
    …
    rowData.add(format.formatCellValue(cell, eval));
    

    0 讨论(0)
提交回复
热议问题