【发布时间】:2020-04-17 13:03:49
【问题描述】:
我曾尝试使用谷歌应用脚本删除谷歌文档的标题和正文部分中的某些段落...但是,如果该段落是一个部分中的最后一个段落,则会出现异常:不能删除文档部分的最后一段。
而这正是我要删除的段落。
我已尝试将该段落与前一段合并,但它不起作用 - 该段落仍然存在。
实现这一目标的唯一有效方法是手动删除段落,方法是将光标放在上一行的末尾并按“前进”删除。这会毫无例外地删除下一行等...但是我需要使用应用程序脚本自动执行此操作 - 所以我问有没有办法在脚本中搜索一个元素,然后从该点模拟按下删除?这更像是一种 hack,但看不到另一种方法?
一个例子可能是:
var foundElement = body.findText("Dialogue");
while (foundElement != null) {
// Get the text object from the element
var foundText = foundElement.getElement().asText();
// Where in the element is the found text?
var start = foundElement.getStartOffset();
var end = foundElement.getEndOffsetInclusive();
//PSUEDO CODE PRESS FORWARD DELETE TWICE FROM the **end** of the search phrase...
end.pressdelete(twice)
}
更新:
我可以通过遍历文档中的所有标题来删除标题段落 - 显然,可以有多个...
对话后我仍然无法删除表格中的空段落(屏幕截图 2)...
var p = d.getBody().getParent();
var headers = [];
var footers = [];
// let's loop through all the child elements in the document including headers and footers etc...
for ( var i = 0; i < p.getNumChildren(); i += 1 ) {
var t = p.getChild(i).getType();
if ( t === DocumentApp.ElementType.BODY_SECTION ) continue; // not interested in the body
if ( t === DocumentApp.ElementType.HEADER_SECTION ) {
//OLD CODE FOR FIRST HEADER
if (headers.length > -1) {
headers.push(p.getChild(i).asHeaderSection())
}
var h = p.getChild(i).asHeaderSection().getText();
} else if ( t === DocumentApp.ElementType.FOOTER_SECTION ) {
var f = p.getChild(i).asFooterSection().getText();
}
}
function cleanHeaders(p) {
p.forEach(function(h, j, ar) {
var para = h.getParagraphs();
para.forEach(function(e, i, arr) {
var children = e.getNumChildren()
//Logger.log("::Children:: " + children);
if (children < 1) {
var t = e.getText();
var type = e.getType();
var parent = e.getParent();
var pChildren = parent.getNumChildren();
var childIndex = parent.getChildIndex(e);
//Logger.log("::Element::" + e + " ::Number:: " + i + " ::Type:: " + type + " ::Text:: " + t + " ::Children:: " + children + " ::Parent:: " + parent + " ::ParentChildren:: " + pChildren + " ::childIndex:: " + childIndex);
for ( var i = 0; i < parent.getNumChildren(); i += 1 ) {
Logger.log(parent.getChild(i));
if (i != 0) {
parent.getChild(i).asParagraph().merge();
}
}
if (parent != 'DocumentBodySection' && parent != 'HeaderSection') {
//e.getPreviousSibling().merge();
}
}
});
});
}
Logger.log("HEADERS: " + headers.length);
cleanHeaders(headers);
【问题讨论】:
标签: google-apps-script google-docs