Add table from .docx-document to another one

Hello. Is it possible to add table from .docx-document to another one?

For example I have a document (9.0 KB) and want to add (1) all of it content or (2) just the table to the another one (9.0 KB) with Web Document Builder from ONLYOFFICE Docs Community Edition (v 7.4) and .docbuilder-file with next content:

builder.OpenFile("link_to_doc_with_table");
var oDocument = Api.GetDocument();

// https://api.onlyoffice.com/docbuilder/howitworks/globalvariable
GlobalVariable["oSth"] = oDocument.GetElement(1);
builder.CloseFile();


builder.OpenFile("link_to_header");
var oDocument = Api.GetDocument();
oDocument.Push(GlobalVariable["oSth"]);
 
builder.SaveFile("docx", "tost.docx");
builder.CloseFile();

But generated document content (but not the size) is equal to original one.

hi @unam3 :handshake:
Yes, you can add a table. Take a look at this script.

builder.CreateFile("docx");
    var oDocument = Api.GetDocument();
    var oParagraph = oDocument.GetElement(0);
    var oFill = Api.CreateSolidFill(Api.CreateRGBColor(104, 155, 104));
    var oStroke = Api.CreateStroke(0, Api.CreateNoFill());
    var oDrawing = Api.CreateShape("rect", 3212465, 963295, oFill, oStroke);
        oParagraph.AddDrawing(oDrawing);
    var oDocContent = oDrawing.GetDocContent();
// Add Hyperlink
        oParagraph = oDocContent.GetElement(0);
        oParagraph.AddText('Hyperlink');
    var oRange = oParagraph.GetRange(0, 8);
        oRange.AddHyperlink('https://api.onlyoffice.com')
// Add BlockLvlSdt
    var oBlockLvlSdt = Api.CreateBlockLvlSdt();
        oBlockLvlSdt.AddText('oBlockLvlSdt');
        oDocContent.Push(oBlockLvlSdt);
// Add Table
    var oTableStyle = oDocument.CreateStyle("CustomTableStyle", "table");
        oTableStyle.SetBasedOn(oDocument.GetStyle("Bordered - Accent 5"));
    var oTable = Api.CreateTable(3, 3);
    var oCell = oTable.GetCell(0, 0);
        oCell.GetContent().GetElement(0).AddText("Cell #1");
        oTable.SetWidth("percent", 100);
        oTable.SetStyle(oTableStyle);
        oDocContent.Push(oTable);
    var json = oDocContent.ToJSON(true, true);
GlobalVariable["JSON"] = json;
builder.CloseFile();

////////////////////////

builder.CreateFile("docx");
    var json = GlobalVariable["JSON"]
    var oDocContentFromJSON = Api.FromJSON(json);
    var oDocument = Api.GetDocument();
    var arrElements = []
    for( var i = 0; i < oDocContentFromJSON.GetElementsCount(); i++) {
        arrElements.push(oDocContentFromJSON.GetElement(i));
    }
        oDocument.InsertContent(arrElements)
builder.SaveFile("docx", "DocContentToJSON.docx");
builder.CloseFile();

Additionally, the following method may be helpful for you:
https://api.onlyoffice.com/docbuilder/textdocumentapi/apidocument/getalltables

1 Like