2017-02-23 124 views
0

我有一个表(如下所示)写的内容谷歌文档:从谷歌表读取和使用应用程序脚本

enter image description here

我想阅读从我的谷歌表的数据,然后写它到一个谷歌文档,说的东西沿线

Hi James Madison, Welcome to Vienna! 
Hi James Monroe, Welcome to Toronto! 
Hi John Quincy Adams, Welcome to Paris! 
Hi Andrew Jackson, Welcome to New York! 
Hi Martin Van Buren, Welcome to London! 
Hi William Henry Harrison, Welcome to Tokyo! 
Hi John Tyler, Welcome to Berlin! 

为此,我知道我需要创建一个脚本,也是一个模板。

这些句子中的每一句都应该存在于它自己的新文档中,所以它们应该全部收集在同一个文件夹中。

最后,我想通过电子邮件发送所有文件。

我一直在寻找所有不同的例子,邮件合并等,但即使经过许多小时的搜索和摆弄,我仍然无法弄清楚如何制作这样的脚本。

也许有一些比我更有经验的人可能会告诉我如何去做,或者指给我一个能够以一种清晰易懂的方式解释它的资源。


这是我第一次尝试天真:

function extractDataFromSheet() { 

    // Opens spreadsheet by its ID 
    var spreadsheet = SpreadsheetApp.openById("1ow7iuLoqfCSqVhp3ra2uy-22LHUJfQA2UpZgOvIuQ5c"); 

    // Get the name of this SS 
    var name_of_sheet = spreadsheet.getName(); 

    var sheet = spreadsheet.getSheetByName('PussyCow'); // or whatever is the name of the sheet 
    var range = sheet.getRange(1,1); 
    var data = range.getValue(); 
    //Browser.msgBox(name_of_sheet +" "+data); 

    // Opens doc by its ID 
    var doc = DocumentApp.openById("1ZSqN-OOxvDV9YLpuDsXhqSWx4X3djUaVehuIlZbanxo"); 

    var name_of_doc = doc.getName(); 

    var doc_body = doc.getBody(); 

// Use editAsText to obtain a single text element containing 
// all the characters in the document. 
var text = doc_body.editAsText(); 

// Insert text at the beginning of the document. 
text.insertText(0, data); 

// Insert text at the end of the document. 
text.appendText(name_of_sheet); 

// Make the first half of the document blue. 
text.setForegroundColor(0, text.getText().length/2, '#00FFFF'); 


Browser.msgBox(name_of_doc); 
} 

回答

1

我不会写整个脚本你,但我会告诉你的,你可以在改写代码做一个例子(希望这是有道理的)。

所以,你想要做的第一件事就是收集所有的数据。要做到这一点的一个好方法是这样的:

var ss = SpreadsheetApp.getActive() 
var dataList = [] 
var iteration = ss.getLastRow() 
while (iteration > 0) { 
    dataList.push(ss.getRange('A' + iteration).getValue() + ',' + ss.getRange('B' + iteration).getValue()) 
    iteration-- 
} 

在这一点上,你把所有的数据的列表。接下来,我们需要将所有这些信息制作成单独的Google文档。

var documentList = [] 
for (i=0;i<dataList.length;i++) { 
    documentList.push(DocumentApp.create('documentName')) 
} 
//this is DEFINITELY not the fastest or most effecient way to do it, but whatever 
var body = undefined 
for (i=0;i<documentList.length;i++) { 
    body = 'Hi ' + dataList[i].split(',')[0] + ', Welcome to' + dataList[i].split(',')[1] + '!' 
    documentList[i].getBody.appendParagraph(body) 
} 

然后,我们要通过电子邮件发送人:这可以通过类似来完成。你的桌子不跟踪电子邮件,所以这是我可以做的最好的:

for (i=0;i<documentList.length;i++) { 
    MailApp.sendEmail('emailAdress','subject','whatever you want the body to be') 
} 
+0

你怎么看待我在我编辑过的代码中所做的事? –

+1

你工作中肯定有一些好东西。例如,你已经得到了范围,我完全忘记了它,并且确实更快,更容易。但是,我觉得你正在做一些工作,只是为了'我接下来要做什么'。'的目的。尽管你已经开始了,但这是第一种到达那里的方式。对于上帝的爱,请不要仅仅因为我说过这是做这件事的方式就做,因为你的方式可能更好。无论如何,我觉得下一步是添加电子邮件事件或使其循环范围内的每个条目。看起来不错! –

相关问题