繁体   English   中英

我可以使用要添加到脚本编辑器的预先编写的 Apps 脚本自动从 CSV 在 Google 表格中创建新电子表格的过程吗?

[英]Can I automate the process of creating a new spreadsheet in Google Sheets from a CSV with a pre-written Apps Script to be added to the Script Editor?

我正在编写一个 Python 程序,它接收一些每天下载的 CSV 文件,其想法是让每个电子表格自动生成,并使用从这些 CSV 文件创建的新电子表格单独上传到 Google 表格。 此外,我需要每个新创建的电子表格都上传一个 Apps 脚本。 到目前为止,我所看到的一切都是如何对现有电子表格执行操作,而不是如何从文件生成新电子表格。 而且我还没有看到 Google 是否允许以编程方式添加脚本而不是手动添加脚本(最后一个是几年前的)。

注意:合并每日 CSV 是不可能的,因为客户需要将每个电子表格发送给不同的收件人。

目标

  • 您每天下载一定数量的 CSV,并希望将它们转换为 Google 电子表格
  • 您想将 Apps 脚本文件附加到每个创建的电子表格

工作流程

实现此功能有多种可能性,为了在触发时自动执行该过程,您可以使用 Apps 脚本,如下所述:

下面是一个示例函数,它使用 Apps 脚本文件创建新的电子表格并自动将内容写入此文件:

function createSpreadsheetwithScript() {

  var ss=SpreadsheetApp.create('myCSV');
  var id=ss.getId();
  var token = ScriptApp.getOAuthToken();
  var url = "https://script.googleapis.com/v1/projects";
  var payload = {
    "title": "myAutoCreatedScript",
    "parentId": id
  }
  var options = {
    "method" : "POST",
    "muteHttpExceptions": true,
    "headers": {
       'Authorization': 'Bearer ' +  token
     },
    "contentType": "application/json",
    "payload": JSON.stringify(payload)
  }
  var response = UrlFetchApp.fetch(url,options);
  var scriptId=JSON.parse(response).scriptId;
  var url2="https://script.googleapis.com/v1/projects/"+scriptId+"/content";
 //test content 
  var source="function myFunction() {\n var x=1;\n}";
  var JSONsource="{\"timeZone\":\"America/New_York\",\"exceptionLogging\":\"STACKDRIVER\"}";  
   var payload2 = {
  "files": [
    {
      "name": "this is the gs. file",
      "type": "SERVER_JS",
      "source": source
    },
    {
      "name": "appsscript",
      "type": "JSON",
      "source": JSONsource,
   "updateTime":"2018-03-04T19:49:08.871Z",
    "functionSet":{
      "values":[{"name":"myFunction"}]}
    }
  ]
}

var options2 = {
  "headers": {
     'Authorization': 'Bearer ' + token,
   }, 
  "contentType": "application/vnd.google-apps.script+json",
  "method" : "PUT", 
  "payload": JSON.stringify(payload2)
  }
  var response2 = UrlFetchApp.fetch(url2,options2); 
}

确保使用必要的授权范围更新appsscript.json 文件的内容:

{
  "timeZone": "America/New_York",
  "dependencies": {
    "enabledAdvancedServices": [{
      "userSymbol": "Drive",
      "serviceId": "drive",
      "version": "v2"
    }]
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/script.projects", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/script.scriptapp"]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM