当前位置: 首页 > 知识库问答 >
问题:

如何在word文档中使用docx4j在特定书签下创建表而不重写word文档

松嘉运
2023-03-14

我根据你的建议和我的需要对代码进行了修改,代码就在这里

//loop through the bookmarks
for (CTBookmark bm : rt.getStarts()) {

// do we have data for this one?
String bmname =bm.getName(); 
// find the right bookmark (in this case i have only one bookmark so check if it is    not null)
if (bmname!=null) {
String value = "some text for testing run";
//if (value==null) continue;

List<Object> theList = null;
//create bm list 
theList = ((ContentAccessor)(bm.getParent())).getContent();

// I set the range as 1 (I assume this start range is to say where the start the table creating)
int rangeStart = 1;



WordprocessingMLPackage wordPackage =   WordprocessingMLPackage.createPackage();

// create the table

Tbl table = factory.createTbl();

//add boards to the table 
addBorders(table);

for(int rows = 0; rows<1;rows++)
{// create a row
Tr row = factory.createTr();
for(int  colm = 0; colm<1;colm++)
{

// create a cell

Tc cell = factory.createTc();

// add the content to cell

cell.getContent().add(wordPackage.getMainDocumentPart()
.createParagraphOfText("cell"+colm));

// add the cell to row
row.getContent().add(cell);
} 

// add the row to table

table.getContent().add(row);

// now add a run (to test whether run is working or not)
org.docx4j.wml.R run = factory.createR();
org.docx4j.wml.Text t = factory.createText();
run.getContent().add(t);    
t.setValue(value);
//add table to list
theList.add(rangeStart, table);
//add run to list
//theList.add(rangeStart, run);
}

我不需要删除书签中的文本,所以我删除了它。我不知道出了什么问题,程序正在编译,但我打不开doc这个词,上面写着“未知错误”。我测试写一些字符串“值”,它在书签和文档打开时写得很完美,但在表的情况下不是这样。请帮我提前谢谢

共有1个答案

师承弼
2023-03-14

您可以修改示例代码BookmarksReplaceWithText.java

在您的情况下:

  • 第89行:父级不是p,而是body或tc。您可以删除该测试。
  • 第128行:不添加运行,而是插入表
 类似资料:
  • 问题内容: 我想使用Python创建Word文档,但是,我想尽可能多地重用现有的文档创建代码。我目前正在使用XSLT生成HTML文件,并以编程方式将其转换为PDF文件。但是,我的客户现在要求以Word(.doc)格式提供同一文档。 到目前为止,我没有太多运气找到该问题的解决方案。有谁知道可以帮助解决此问题的开源库(或 gulp 专有解决方案)? 注意:所有可能的解决方案必须在Linux上运行。我相

  • 我使用数据库中的数据获取默认表模型,我想以doc word打印为表。如何实现。请参阅下面的代码:

  • 如何使用Apache POI创建Word文档?

  • 目前,我从文档中获得的所有文本如下所示:

  • 有没有办法将文件附加到MS Word文档中?我的意思与您将MS Excel文件拖放到MS Word中的方式相同。它显示MS Excel图标和文件名,双击打开附件。 我的情况来自以前的html文件,我导入使用XHTMLImporter.convert.现在超文本标记语言引用附件下载几个地方,并希望将这些文件附加到适当的MS Word文档。