[英]Copying a section from Google Docs to another Doc using Apps Script
I've successfully used this code to copy the entirety of one doc into another doc:我已经成功地使用此代码将一个文档的全部内容复制到另一个文档中:
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;
}
}
However, I now need to copy a portion of a doc into another doc, and I can't figure it out.但是,我现在需要将一个文档的一部分复制到另一个文档中,但我无法弄清楚。 If I knew how to get the body index of any element I could do it the same way, but I don't know if that's even possible.
如果我知道如何获取任何元素的 body 索引,我可以用同样的方法来做,但我不知道这是否可行。 The text I need to copy out will always be preceded by a specific text ("Current Week") and end immediatly before a specific text ("ARCHIVE").
我需要复制的文本将始终以特定文本(“当前周”)开头,并在特定文本(“ARCHIVE”)之前立即结束。
Description描述
Here is a simple example of how to copy between certain text.这是一个如何在特定文本之间复制的简单示例。 I've only covered paragraphs and tables but any other type of Element can be handled.
我只介绍了段落和表格,但可以处理任何其他类型的元素。
Test Document测试文件
Script脚本
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)
}
}
Reference参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.