Reputation: 382
I have default table model fetch with data from database and i want to print in doc word as a table. How to achieve that. See the code below:
try {
try {
con = connCC.getDBconnection();
} catch (ClassNotFoundException ex) {
Logger.getLogger(CustomerSR.class.getName()).log(Level.SEVERE, null, ex);
}
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select * From Appointment");
while (rs.next()) {
for (int col = 0; col < 1; col++) {
rowData.add(rs.getString(1));
rowData.add(rs.getString(2));
rowData.add(rs.getString(3));
rowData.add(rs.getString(4));
rowData.add(rs.getString(5));
}
model.addRow(rowData);
}
window.display(model);
//window.display(names, phones, addresses);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
Upvotes: 1
Views: 15801
Reputation: 103
In the above comments, I see that you are already using Apache POI. If I understand correctly, you want to input data from a database into a table on a word document. Take a look at this tutorial on creating tables in word with Apache POI: http://www.tutorialspoint.com/apache_poi_word/apache_poi_word_tables.htm
You can set the text directly with the data that you retrieve from the database. I can post an example if you need it, but the tutorial does a pretty good job of showing what you need to do.
----UPDATE----
Sorry that it took me a while, went to lunch with the wife. Try this:
// Blank Document
XWPFDocument document = new XWPFDocument();
// Write the Document in file system
FileOutputStream out = new FileOutputStream(new File("create_table.docx"));
// Create table
XWPFTable table = document.createTable();
// Table row
XWPFTableRow tableRow;
int rowCount = model.getRowCount() - 1;
int colCount = model.getColumnCount() - 1;
// Iterate through rows
for (int row = 0; row <= rowCount; row++) {
tableRow = table.getRow(row);
// Iterate through columns
for (int col = 0; col <= colCount; col++) {
tableRow.getCell(col).setText((String) model.getValueAt(row, col));
// If more columns, add cell
if (row == 0 && col < colCount) {
tableRow.addNewTableCell();
}
}
// If more rows, add row
if (row < rowCount) {
table.createRow();
}
}
// Write to word document and close file.
document.write(out);
out.close();
Upvotes: 2