我有一個具有以下樣式的 Google 檔案:

實際的 TOC 是:

你可以看到它有幾種風格:
- 標題(14pt,藍色,下劃線)
- 字幕(12pt,黑色,下劃線)
- 標題 1 (11pt)
- 標題 2(10pt,粗體)
- 普通文本(10pt)
我想制作一個在活動檔案上運行的腳本并存盤每個標題的內容以進行以下更改:
- 頁眉 1(14pt,藍色,下劃線)
- 標題 2 (11pt)
- 普通文本(10pt,第一行包含“Topic no”粗體)
運行腳本后的最終結果應該是:

新的 TOC 應如下所示:

所以主要的變化是把 HEADER 2 的內容放到一個普通的文本行中,這樣它就從 TOC 中消失了。有沒有辦法撰寫一個腳本來解決這個問題?
uj5u.com熱心網友回復:
請參閱下面的腳本:
function findHeader() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
// Define the search parameters
var searchType = DocumentApp.ElementType.PARAGRAPH;
var searchHeadings = [DocumentApp.ParagraphHeading.HEADING2, DocumentApp.ParagraphHeading.HEADING1, DocumentApp.ParagraphHeading.TITLE];
var replacementHeadings = [DocumentApp.ParagraphHeading.NORMAL, DocumentApp.ParagraphHeading.HEADING2, DocumentApp.ParagraphHeading.HEADING1];
var searchResult = null;
// Style changes you want to apply
var H2_N = {};
H2_N[DocumentApp.Attribute.FONT_SIZE] = '11';
// Since HEADING 2 that are made to be Normal becomes first Normal heading and first Normal heading is to be bold,
// You can directly make it bold here to reduce redundancy
H2_N[DocumentApp.Attribute.BOLD] = true;
var H1_H2 = {};
H1_H2[DocumentApp.Attribute.FONT_SIZE] = '11';
var T_H1 = {};
T_H1[DocumentApp.Attribute.FONT_SIZE] = '14';
T_H1[DocumentApp.Attribute.FOREGROUND_COLOR] = '#0000FF';
T_H1[DocumentApp.Attribute.UNDERLINE] = true;
var styles = [H2_N, H1_H2, T_H1];
// Loop all searchHeadings
searchHeadings.forEach((searchHeading, index) => {
// Search until the wanted searchHeading is found
while (searchResult = body.findElement(searchType, searchResult)) {
var par = searchResult.getElement().asParagraph();
if (par.getHeading() == searchHeading) {
// Replace with its corresponding replacementHeadings and apply approriate styles
par.setHeading(replacementHeadings[index]);
par.setAttributes(styles[index]);
}
}
});
}
腳本行為總結:
- 降級以下標題 (
T -> H1,H1 -> H2,H2 -> N) - 每次降級應用不同的樣式:
T -> H1:14PT,藍色,下劃線H1 -> H2: 11點H2 -> N: 11PT, 粗體
H2 -> N直接變為粗體,因為您希望前 N 段為粗體。而當H2被降級時,它變成N,成為第一個N。所以我們可以在降級時直接將H2變成粗體。
輸出:

參考:
- 段落標題
- 屬性
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444745.html
上一篇:谷歌表格-腳本;getRangegetLastRow復制到
下一篇:C#訪問抽象類的屬性
