I am trying to export my JTable to Excel file. Column and Row names are fine, but all the information I am adding into JTable does not get written. I tried System.out.println() and it prints Null values everywhere apart from column and row names. I tried to get answers from mother google but after 2 hours of reading and trying, still no progress. What stays in my head is that there could be some mistake in code at Write to Excel part or everything that is added to JTable is just a picture on my monitor, not an actual data in it.? Correct me if I am wrong and any help is highly appreciated.
Here is Write to Excel Part. in first For loop I am getting headers and in second For loop, i should get everything that is inside my JTable but I'm not.
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();
}
}
And here is FocusListener code.
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();
}
});
I am using 'DefaultTableModel'
DefaultTableModel tableModel = new DefaultTableModel(12,8);
JTable rotaTable = new JTable(tableModel);
This is first time when I am working with POI library.
Picture of my JTable http://imgur.com/a/jnB8j
Picture of printed results in console http://imgur.com/a/jnB8j
Picture of Excel file created. http://imgur.com/a/jnB8j
for, why didn't you start by 0? - Kh.Tahericell.setCellValue((String) nrp.tableModel.getValueAt(i, j)+" ");.. into thiscell.setCellValue((String) tcm.getValueAt(i, j)+" ");- Kh.Taheri1so you're running the risk of aIndexOutOfBoundsException- MadProgrammer1because the header is starting at0, so they are trying to get the rows in the excel spread sheet to be offset ... some what dangerously... - MadProgrammer