我的目標
假設我正在編輯 Google Doc #1。
現在假設我決定:“嘿,我想在與 Google Doc #1 相同的檔案夾中創建一個名為‘我喜歡奶酪披薩’的新 Google 檔案。”
此外,假設我希望名為“我喜歡奶酪披薩”的 Google 檔案包含第一段,其中包含文本“我喜歡奶酪披薩”。
我將如何實作我的目標?
我想象當我在編輯 Google Doc #1 時,我會輸入“我喜歡奶酪披薩”,然后運行一個 Apps 腳本。
可能有用的例子
例如,我在Extending Google Docs中找到的以下腳本插入了一個段落,其中包含與檔案名稱相同的文本...
function createDoc() {
var doc = DocumentApp.create('Sample Document');
var body = doc.getBody();
var rowsData = [['Plants', 'Animals'], ['Ficus', 'Goat'], ['Basil', 'Cat'], ['Moss', 'Frog']];
body.insertParagraph(0, doc.getName())
.setHeading(DocumentApp.ParagraphHeading.HEADING1);
table = body.appendTable(rowsData);
table.getRow(0).editAsText().setBold(true);
}
如何檢索游標當前位于 Google Doc 中的句子?顯然完成了它所說的。
var cursor = DocumentApp.getActiveDocument().getCursor();
var surroundings = cursor.getSurroundingText();
var marker = '\u200B'; // A zero-wdith space character - i.e. a hidden marker.
cursor.insertText(marker);
var surroundingTextStr = surroundings.getText(); // Copy to string
surroundings.replaceText(marker, ''); // Remove the marker from the document.
// Build sentence pattern, allowing for marker.
var pattern = /([A-Z\u200B][^\.!?]*[\.!?])/ig;
var match;
while ((match = pattern.exec(surroundingTextStr)[0]) != null){
Logger.log(match);
if (/\u200B/.test(match)){
match = match.replace(marker, '');
Logger.log("We found the sentence containing the cursor!");
Logger.log(match);
}
}
當然,下面會創建一個名為“'New Text File”的文本檔案,其文本為“Hello, world!”。那不是我想要的。但我想它仍然可能會有所幫助。在當前檔案夾中創建一個具有給定名稱和內容的文本檔案...
// Create a text file with the content "Hello, world!"
DriveApp.getRootFolder().createFile('New Text File', 'Hello, world!');
uj5u.com熱心網友回復:
這應該做。它創建一個選單,您可以從中呼叫腳本。我不知道用例,但也許用作業表管理新檔案更簡單?
function onOpen(e) {
DocumentApp.getUi().createMenu('NewDoc')
.addItem('Create', 'newDocWithSentense')
.addToUi();
}
function newDocWithSentense() {
const doc = DocumentApp.getActiveDocument();
const cursor = doc.getCursor();
const surroundings = cursor.getSurroundingText().getText();
const currentFileFolder = DriveApp.getFileById(doc.getId()).getParents().next()
const newDoc = DocumentApp.create(surroundings).getId()
DriveApp.getFileById(newDoc).moveTo(currentFileFolder)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488097.html
