EDITED将JTable写入Excel

Hel*_*ijs 12 java eclipse excel swing jtable

我正在尝试将我的JTable导出到Excel文件.列和行名称都很好,但我在JTable中添加的所有信息都没有写入.我尝试了System.out.println(),它除了列名和行名之外还打印了Null值.我试图从谷歌谷歌得到答案,但经过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();
  }
}
Run Code Online (Sandbox Code Playgroud)

这里是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();
            }
        });
Run Code Online (Sandbox Code Playgroud)

我正在使用'DefaultTableModel'

 DefaultTableModel tableModel = new DefaultTableModel(12,8); 
JTable rotaTable = new JTable(tableModel); 
Run Code Online (Sandbox Code Playgroud)

这是我第一次使用POI库.

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

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

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

小智 4

您必须从 0 开始行索引,因为表行从 0 开始,并从 1 创建 Excel 行,因为首先要写入列名称。我修改了您的第二个 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)+" ");
    }
}
Run Code Online (Sandbox Code Playgroud)