[英]Create Word Document with Java
I have default table model fetch with data from database and i want to print in doc word as a table. 我具有从数据库中获取数据的默认表模型,我想以doc字作为表进行打印。 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();
}
}
In the above comments, I see that you are already using Apache POI. 在以上注释中,我看到您已经在使用Apache POI。 If I understand correctly, you want to input data from a database into a table on a word document. 如果我理解正确,则希望将数据库中的数据输入到Word文档的表格中。 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 看一下有关使用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.