如何在特定书签中使用docx4j在word doc中创建表而不覆盖word doc

时间:2013-08-15 13:57:30

标签: java docx4j

我需要在特定书签的位置创建一个表。即我需要找到书签并插入表格。我怎么能用docx4j做到这一点 在此先感谢


对不起杰森,我是Stackoverflow的新手,所以我不能清楚地写出我的问题,这是我的情况和问题。

我根据您的建议和我的需求对代码进行了更改,代码就在这里

//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这个词,它说“未知错误”。我测试写一些字符串“value”,它在该书签中完美写入,文档正在打开,但不是在表格的情况下。请帮我 提前致谢

2 个答案:

答案 0 :(得分:2)

您可以调整示例代码BookmarksReplaceWithText.java

在你的情况下:

  • 第89行:父母将不是p,它将是身体或tc。你可以删除测试。
  • 第128行:您想要插入表
  • ,而不是添加运行

您可以使用TblFactory创建表格,或使用示例docx中的docx4j webapp to generate code

答案 1 :(得分:0)

出于某种原因,用表格替换书签对我没有帮助,所以我依靠用表格替换文本。我使用 XHTML 导入器为我的用例从 HTML 创建了我的表格

MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

    String xhtml= <your table HTML>;

    XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
    int ct = 0;
    List<Integer> tableIndexes = new ArrayList<>();
    List<Object> documentContents = documentPart.getContent();
    for (Object o: documentContents) {

        if (o.toString().contains("PlaceholderForTable1")) {
            tableIndexes.add(ct);
        }
        ct++;
    }

    for (Integer i: tableIndexes) {
        documentPart.getContent().remove(i.intValue());
        documentPart.getContent().addAll(i.intValue(), XHTMLImporter.convert( xhtml, null));
    }

在我的输入词文档中,我定义了文本“PlaceholderForTable1”,我想在其中插入我的表格。

相关问题