how to Create table in word doc using docx4j in specific bookmark without overwritting the word doc

半城伤御伤魂 提交于 2019-12-11 04:17:59

问题


I need to create a table at the location of particular bookmark. ie i need to find the bookmark and insert the table . how can i do this using docx4j Thanks in Advance


Sorry Jason, I am new to Stackoverflow so i couldnt write my problem clearly, here is my situation and problem.

I made changes in that code as you suggested and to my needs, and the code is here

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

I dont need to delete text in bookmark so i removed it. I dont know whats the problem, program is compiling but I cannot open the word doc , it says "unknown error". I test to write some string "value" it writes perfectly in that bookmark and document is opening but not in the case of table. Please help me Thanks in advance


回答1:


You can adapt the sample code BookmarksReplaceWithText.java

In your case:

  • line 89: the parent won't be p, it'll be body or tc. You could remove the test.
  • line 128: instead of adding a run, you want to insert a table

You can use TblFactory to create your table, or the docx4j webapp to generate code from a sample docx.



来源:https://stackoverflow.com/questions/18254279/how-to-create-table-in-word-doc-using-docx4j-in-specific-bookmark-without-overwr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!