我已成功使用此代碼將一個檔案的全部內容復制到另一個檔案中:
const newestFile = DocumentApp.openById("ID").getBody();
const archive = DocumentApp.openById("ID").getBody();
let index = 12;
let el, type;
for (let i = 0; i < newestFile.getNumChildren(); i ){
el = newestFile.getChild(i);
type = el.getType();
switch (type){
case DocumentApp.ElementType.PARAGRAPH:
archive.insertParagraph(index,el.copy());
index ;
break;
case DocumentApp.ElementType.LIST_ITEM:
archive.insertListItem(index,el.copy());
index ;
break;
case DocumentApp.ElementType.TABLE:
archive.insertTable(index,el.copy());
index ;
break;
}
}
但是,我現在需要將檔案的一部分復制到另一個檔案中,但我無法弄清楚。如果我知道如何獲取任何元素的主體索引,我可以用同樣的方式來做,但我不知道這是否可能。我需要復制的文本總是以特定文本(“當前周”)開頭,并在特定文本(“ARCHIVE”)之前立即結束。
uj5u.com熱心網友回復:
描述
這是一個如何在某些文本之間復制的簡單示例。我只介紹了段落和表格,但可以處理任何其他型別的元素。
測驗檔案

腳本
function myFunction() {
try {
let doc = DocumentApp.getActiveDocument();
let body = doc.getBody();
let count = body.getNumChildren();
doc = DocumentApp.create("dummy");
let copy = doc.getBody();
let start = false;
for( let i=0; i<count; i ) {
let child = body.getChild(i);
if( child.getType() == DocumentApp.ElementType.PARAGRAPH ) {
if( child.asParagraph().findText("Current Week") ) start = true;
if( start ) copy.appendParagraph(child.asParagraph().copy());
if( child.asParagraph().findText("ARCHIVE") ) break;
}
else if( child.getType() == DocumentApp.ElementType.TABLE ) {
if( start ) copy.appendTable(child.asTable().copy());
}
}
}
catch(err) {
console.log("Error in myFunction - " err)
}
}
參考
- https://developers.google.com/apps-script/reference/document/body#getChild(整數)
- https://developers.google.com/apps-script/reference/document/element-type
- https://developers.google.com/apps-script/reference/document/body
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450839.html
