我正在尝试将JTable导出到Excel文件。列名和行名都可以,但是我添加到JTable中的所有信息都不会被写入。我尝试了 System.out.println(),它在除列名和行名之外的所有地方打印 Null 值。我试图从Google妈妈那里获得答案,但是经过2个小时的阅读和尝试,仍然没有任何进展。
我想到的是,“写入Excel”部分的代码可能有错误,或者添加到JTable的所有内容只是监视器上的图片,而不是其中的实际数据。
如果我做错了,请纠正我,我们将不胜感激。

这是写入Excel部件。
在第一个For循环中,我获取标题,在第二个For循环中,我应该获取JTable内部的所有内容,但我没有。

TableColumnModel tcm = nrp.rotaTable.getColumnModel();

    String nameOfFile = JOptionPane.showInputDialog("Name of the file");

    Workbook wb = new HSSFWorkbook();
    CreationHelper createhelper = wb.getCreationHelper();

    Sheet sheet = wb.createSheet("new sheet");
    Row row = null;
    Cell cell = null;

    for (int i = 0; i < nrp.tableModel.getRowCount(); i++) {
        row = sheet.createRow(i);
        for (int j = 0; j < tcm.getColumnCount(); j++) {

            cell = row.createCell(j);
            cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());

        }
    }
    for (int i = 1; i < nrp.tableModel.getRowCount(); i++) {
        row = sheet.createRow(i);
        System.out.println("");
        for (int j = 0; j < nrp.tableModel.getColumnCount(); j++) {

            cell = row.createCell(j);
            cell.setCellValue((String) nrp.tableModel.getValueAt(i, j)+" ");
            System.out.print((String) nrp.tableModel.getValueAt(i, j)+" ");
        }
    }


    File file = new File("Some name.xls");
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
    wb.close();
  }
}

这是FocusListener代码。
rotaTable.addFocusListener(new FocusListener() {
            public void focusGained(FocusEvent e) {
            }
            public void focusLost(FocusEvent e) {
                CellEditor cellEditor = rotaTable.getCellEditor();
                if (cellEditor != null)
                    if (cellEditor.getCellEditorValue() != null)
                        cellEditor.stopCellEditing();
                    else
                        cellEditor.cancelCellEditing();
            }
        });

我正在使用'DefaultTableModel'
 DefaultTableModel tableModel = new DefaultTableModel(12,8);
JTable rotaTable = new JTable(tableModel);

这是我第一次使用POI库。

我的JTable http://imgur.com/a/jnB8j的图片

控制台http://imgur.com/a/jnB8j中打印结果的图片

创建的Excel文件的图片。 http://imgur.com/a/jnB8j

最佳答案

您必须以0开始的行索引,因为表行是从0开始的,并且要创建Excel行是从1开始的,因为第一个为您编写列名。我修改了第二个for循环,如下所示:

for (int i= 0; i < nrp.tableModel.getRowCount(); i++) {
    row = sheet.createRow(i+1);
    System.out.println("");
    for (int j = 0; j < nrp.tableModel.getColumnCount(); j++) {
        cell = row.createCell(j);
        if(nrp.tableModel.getValueAt(i, j)!=null){
        cell.setCellValue((String) nrp.tableModel.getValueAt(i, j));
        }
        System.out.print((String) nrp.tableModel.getValueAt(i, j)+" ");
    }
}

09-11 18:43
查看更多