gpt4 book ai didi

java - 使用 Java 创建 Word 文档

转载 作者:行者123 更新时间:2023-12-01 10:19:09 24 4
gpt4 key购买 nike

我有默认的表模型,它从数据库中获取数据,并且我想在 doc word 中将其打印为表格。如何实现这一目标。请参阅下面的代码:

    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();
}

}

最佳答案

在上面的评论中,我看到您已经在使用 Apache POI。如果我理解正确的话,你想将数据库中的数据输入到word文档的表格中。看看这个关于使用 Apache POI 在 word 中创建表格的教程: http://www.tutorialspoint.com/apache_poi_word/apache_poi_word_tables.htm

您可以使用从数据库检索的数据直接设置文本。如果您需要的话,我可以发布一个示例,但是本教程很好地展示了您需要做什么。

----更新----

抱歉,我花了一段时间,和妻子一起去吃午饭。试试这个:

// 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();

关于java - 使用 Java 创建 Word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35731857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com