【发布时间】:2017-09-19 21:02:25
【问题描述】:
我正在尝试将我的 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();
}
}
这里是 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
【问题讨论】:
-
第二个
for,你为什么不从0开始? -
也许你必须把
cell.setCellValue((String) nrp.tableModel.getValueAt(i, j)+" ");.. 改成这个cell.setCellValue((String) tcm.getValueAt(i, j)+" "); -
没有更多信息很难判断,您可能引用了错误的模型
-
另外,你的第二个循环,你没有补偿行索引从
1开始的事实,所以你冒着IndexOutOfBoundsException的风险 -
@Kh.Taheri 他们从
1开始,因为标题从0开始,所以他们试图让excel 电子表格中的行被偏移...一些多么危险……
标签: java excel eclipse swing jtable