gpt4 book ai didi

java - 使用 Java、Apache POI 写入单词表单元格?

转载 作者:太空宇宙 更新时间:2023-11-04 12:20:48 24 4
gpt4 key购买 nike

我有一个带有表格的Word文档。我想使用 Java 在这些单元格中插入文本,并且我已将 Apache POI 添加到我的项目中。

但是,我只成功读取了文档。我的应用程序获取表中的所有单元格。但我不知道如何在每个单元格中插入新文本?有什么想法吗?

  String SOURCE_FILE = "template.doc";

DocumentProcessor instance = new DocumentProcessor();
HWPFDocument doc = null;
try {
doc = instance.openDocument(SOURCE_FILE);

Range range = doc.getRange();
TableIterator itr = new TableIterator(range);
while(itr.hasNext()) {
Table table = itr.next();
for (int rowIndex = 0; rowIndex < table.numRows(); rowIndex++) {
TableRow row = table.getRow(rowIndex);
for (int colIndex = 0; colIndex < row.numCells(); colIndex++) {
TableCell cell = row.getCell(colIndex);
cell.getParagraph(0).text().replace("", "Hello");
System.out.println(cell.getParagraph(0).text());
}
}
}

} catch (Exception e) {
e.printStackTrace();
} finally {
saveDocument(doc, SOURCE_FILE);

}
}


private HWPFDocument openDocument(String file) throws Exception {
URL res = getClass().getClassLoader().getResource(file);
HWPFDocument document = null;
if (res != null) {
document = new HWPFDocument(new POIFSFileSystem(
new File(res.getPath())));
}
return document;
}

private static void saveDocument(HWPFDocument doc, String file) {
try (FileOutputStream out = new FileOutputStream(file)) {
doc.write(out);
doc.close();
System.out.println("File saved");
} catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

  public class TableCreate{

public static void main(String[] args)throws Exception {

//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();
//create first row
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("col one, row one");
tableRowOne.addNewTableCell().setText("col two, row one");
tableRowOne.addNewTableCell().setText("col three, row one");
//create second row
XWPFTableRow tableRowTwo = table.createRow();
tableRowTwo.getCell(0).setText("col one, row two");
tableRowTwo.getCell(1).setText("col two, row two");
tableRowTwo.getCell(2).setText("col three, row two");
//create third row
XWPFTableRow tableRowThree = table.createRow();
tableRowThree.getCell(0).setText("col one, row three");
tableRowThree.getCell(1).setText("col two, row three");
tableRowThree.getCell(2).setText("col three, row three");

document.write(out);
out.close();
System.out.println("create_table.docx written successully");
}
}

输出

enter image description here

关于java - 使用 Java、Apache POI 写入单词表单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38872022/

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