2013-10-13 52 views
3

我想編寫一個Google Docs腳本來複制一個模板(它只包含一個容器綁定腳本)並附加用戶選擇的另一個文檔的內容。我怎麼做到這一點?我已經有一種方法來選擇文件(模板有一個靜態ID),但想出一種方法將文檔的所有內容(包括inlineImages和超鏈接)複製到我的新文檔中。如何複製模板並從其他文檔插入內容?

回答

5

我想唯一的辦法是一個接一個地複製元素......有一大堆文檔元素,但它不應該太難以相當詳盡。 以下是最常見的類型,您必須添加其他類型。

(從an answer by Henrique Abreu借原代碼)

function importInDoc() { 
    var docID = 'id of the template copy'; 
    var baseDoc = DocumentApp.openById(docID); 
    var body = baseDoc.getBody(); 

    var otherBody = DocumentApp.openById('id of source document').getBody(); 
    var totalElements = otherBody.getNumChildren(); 
    for(var j = 0; j < totalElements; ++j) { 
    var element = otherBody.getChild(j).copy(); 
    var type = element.getType(); 
    if(type == DocumentApp.ElementType.PARAGRAPH) 
     body.appendParagraph(element); 
    else if(type == DocumentApp.ElementType.TABLE) 
     body.appendTable(element); 
    else if(type == DocumentApp.ElementType.LIST_ITEM) 
     body.appendListItem(element); 
    else if(type == DocumentApp.ElementType.INLINE_IMAGE) 
     body.appendImage(element); 

    // add other element types as you want 

    else 
     throw new Error("According to the doc this type couldn't appear in the body: "+type); 
    } 
} 
+0

我注意到,元件也可以有一個TEXT類型。所以你還需要合併: else if(type == DocumentApp.ElementType.TEXT) body.setText(element); –

相關問題