【发布时间】:2014-02-24 20:08:46
【问题描述】:
我正在尝试制作一个 google 脚本,用于将新版本的 google 电子表格(或工作表)导出(或打印)为 pdf,并带有页面参数(纵向/横向,...)
我对此进行了研究并找到了可能的解决方案here。 有几个类似的解决方案,但只适用于旧版本的谷歌电子表格。
请考虑以下代码:
function exportAsPDF() {
//This code runs from a NEW version of spreadsheet
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous"); oauthConfig.setConsumerSecret("anonymous");
var requestData = { "method": "GET", "oAuthServiceName": "google","oAuthUseToken": "always" };
var ssID1="0AhKhywpH-YlQdDhXZFNCRFROZ3NqWkhBWHhYTVhtQnc"; //ID of an Old version of spreadsheet
var ssID2="10xZX9Yz95AUAPu92BkBTtO0fhVk9dz5LxUmJQsJ7yPM"; //ID of a NEW version of spreadsheet
var ss1 = SpreadsheetApp.openById(ssID1); //Old version ss object
var ss2 = SpreadsheetApp.openById(ssID2); //New version ss object
var sID1=ss1.getActiveSheet().getSheetId().toString(); // old version sheet id
var sID2=ss2.getActiveSheet().getSheetId().toString(); // new version sheet id
//For Old version, this runs ok.
var url1 = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="+ssID1+"&gid="+sID1+"&portrait=true"+"&exportFormat=pdf";
var result1 = UrlFetchApp.fetch(url1 , requestData);
var contents1=result1.getBlob();
var pdfFile1=DriveApp.createFile(contents1).setName("FILE1.pdf");
//////////////////////////////////////////////
var url2 = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="+ssID2+"&gid="+sID2+"&portrait=true"+"&exportFormat=pdf";
var result2 = UrlFetchApp.fetch(url2 , requestData);
var contents2=result2.getBlob();
var pdfFile2=DriveApp.createFile(contents2).setName("FILE2.pdf");
}
它工作正常并生成文件“FILE1.pdf”,可以正确打开。但是对于新版本的电子表格,它会在“var result2 = UrlFetchApp.fetch(url2, requestData);”处导致错误 302(截断服务器响应)。好吧,没关系,因为新版本的 url 格式不包含“key”参数。新版本的正确 url 必须像 "https://docs.google.com/spreadsheets/d/"+ssID2+"/export?gid="+sID2+"&portrait=true&format=pdf"
将其用于 url2 (var url2 = "https://docs.google.com/spreadsheets/d/"+ssID2+"/export?gid="+sID2+"&portrait=true&format=pdf") 再次失败,并出现错误“无法为服务执行授权:google”。
嗯,这个错误可能是由于 RequestTokenUrl 的范围不正确。我找到了替代范围 https://docs.google.com/feeds 并将其设置为:oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://docs.google.com/feed/");
代码再次运行后,在UrlFetchApp.fetch(url2 , requestData); 行出现了一个新错误:“Error OAuth”……我不知道如何继续……我已经测试了数百种变体,但没有得到很好的结果。
有什么想法吗? docs.google.com/feeds 新版本电子表格的范围是否正确? oauthConfig 是否正确?
提前致谢。
【问题讨论】:
标签: google-apps-script google-sheets