【发布时间】:2016-07-03 13:14:23
【问题描述】:
我想要一个 Google Apps 脚本,它可以使用以下触发器自动将我在 Google Drive 上的 Google 电子表格导出到 .xls 或 .xlsx
时间驱动(比如每 30 分钟)或事件驱动(对文件进行的每次编辑)。我是基于 Stack Overflow 上的一个老问题 here 但由于函数 oAuthConfig 是
停产了,我想我会基于OAuth1库打开一个新线程。
这是我遵循的所有步骤:
当文件打开时,我去了
Tools -> Script Editor...,然后我按照这些instructions安装了最新的OAuth1库(v.12和库 我使用的项目密钥是Mb2Vpd5nfD3Pz-_a-39Q4VfxhMjh3Sh48)。我也尝试过启用或禁用Development mode。我运行了除
googleOAuth_(...)之外的所有函数,并授予了他们要求的任何权限。最后,我从
Resources -> Current project's triggers创建了一个触发器,它在每次编辑电子表格时调用函数myOnEdit,如果失败,会通过电子邮件通知我。
这是脚本:
function myOnEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var r = s.getActiveCell();
if( r.getColumn() != 1 ) { //checks the column
var row = r.getRow();
var time = new Date();
time = Utilities.formatDate(time, ss.getSpreadsheetTimeZone(), "MM/dd/yy, hh:mm:ss");
var id = ss.getId();
s.getRange('A' + row.toString()).setValue(time);
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',
googleOAuth_('docs',url)).getBlob()
DriveApp.createFile(doc).setName('newfile.xls')
}
}
function authorise(){
// function to call to authorize googleOauth
var id=SpreadsheetApp.getActiveSpreadsheet().getId();
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',
googleOAuth_('docs',url)).getBlob()
}
function googleOAuth_(name,scope) {
var service = OAuth1.createService(name);
service.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
service.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
service.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
service.setConsumerKey('anonymous');
service.setConsumerSecret('anonymous');
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
所以,代码似乎没有产生任何错误,但有两个问题:
即使创建了文件
newfile.xls,也不是我想要的。基本上,当我在 Excel 上打开它时,我收到消息““newfile.xls”的文件格式和扩展名不匹配。该文件可能已损坏或不安全。除非您信任它的来源,否则不要打开它。做还是要打开它?”,然后它会等待一段时间,当文件打开时,它看起来像是 Excel 格式的 Google 登录页面。每次我对一行进行编辑时,对应于该行第一列的单元格都会更改为当前时间戳,例如“07/03/16, 03:58:30” 原始电子表格。
【问题讨论】:
-
如果您手动将文件导出到XLSX,您可以打开它吗?您是否考虑过使用内容服务而不是 UrlFetch?
-
@Ruben 是的,我可以。通过您提出的方式或
File菜单。
标签: google-apps-script google-sheets export-to-excel