我試圖將我的JTable導出爲Excel文件。列和行名稱都很好,但我添加到JTable中的所有信息都沒有寫入。我試過System.out.println()和它打印空價值無處不在列和行名稱。我試圖從母親谷歌的答案,但經過2個小時的閱讀和嘗試,仍然沒有進展。 我的腦海中仍然存在的問題是,在寫入Excel部分代碼時可能會出現一些錯誤,或者添加到JTable的所有內容都只是顯示器上的圖片,而不是實際的數據。 糾正我,如果我錯了,並高度讚賞任何幫助。EDITED將JTable寫入Excel
這是寫入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
圖片的
Excel文件的圖片創建。 http://imgur.com/a/jnB8j
在第二個「for」中,爲什麼不從0開始? –
也許你必須將'cell.setCellValue((String)nrp.tableModel.getValueAt(i,j)+「」);'..改成這個'cell.setCellValue((String)tcm。getValueAt(i,j)+「」);' –
如果沒有更多的信息很難說,你可能會引用錯誤的模型 – MadProgrammer