Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Sun Aug 21, 2022 5:49 pm

HI dears ,
Thanks for your support to help me How to set Spicific position of table in word document java ?

Simply i need to put Table in spicfic position in Word Doc.

please check my files i put Wordfile & image to explian

shadywardy
 
Posts: 19
Joined: Thu Aug 18, 2022 2:25 pm

Mon Aug 22, 2022 9:11 am

Hello,

Thanks for your inquiry.

Here is the sample code and comments for your reference. Please give it a try.

Code: Select all
                Document doc = new Document();
        doc.loadFromFile("Scope.docx");
        /**
         * Inert a bookmark.
         *
         * If you can place this bookmark directly in the original document, you can skip this step.
         */
        //Find the keyword. it may like this "${table_holder}".
        //here I just use the whole paragraph for example.
        TextSelection selection= doc.findString("I Need to Put Table Here",false,true);
        //Get the TextRange of the key word
        TextRange range=selection.getAsOneRange();
        //Get the owner paragraph of the key word
        Paragraph owner=range.getOwnerParagraph();
        //Get the index of this range in the owner paragraph
        int index=owner.getChildObjects().indexOf(range);
        //Insert a temporary bookmark to include the key word
        BookmarkStart start=new BookmarkStart(doc,"table_bookmark");
        BookmarkEnd end=new BookmarkEnd(doc,"table_bookmark");
        owner.getChildObjects().insert(index,start);
        owner.getChildObjects().insert(index+2,end);

        //init a new table object
        Table table=new Table(doc,true);
        //reset rows and columns
        table.resetCells(2,2);
        //put some values in the table
        table.get(0,0).addParagraph().appendText("Row 1, Column 1");
        table.get(1,1).addParagraph().appendText("Row 2, Column 2");
        //init a TextBodyPart object
        TextBodyPart body=new TextBodyPart(doc);
        //add the table to the body
        body.getBodyItems().add(table);

        //Find the bookmark by name
        BookmarksNavigator navigator=new BookmarksNavigator(doc);
        navigator.moveToBookmark("table_bookmark");
        //Replace all content in the bookmark with the new body
        navigator.replaceBookmarkContent(body);

        //If you need, remove the bookmark after replacement
        //doc.getBookmarks().remove(navigator.getCurrentBookmark());

        //Save the file
        doc.saveToFile("output.docx", FileFormat.Docx);
Sincerely,
Andy
E-iceblue support team
User avatar

Andy.Zhou
 
Posts: 483
Joined: Mon Mar 29, 2021 3:03 am

Mon Aug 22, 2022 6:28 pm

Thanks for your support :)

shadywardy
 
Posts: 19
Joined: Thu Aug 18, 2022 2:25 pm

Return to Spire.Doc