dev*_*evo 6 javascript google-apps google-sheets google-apps-script
我有一个使用Google App Script HtmlService和html表单开发的Web应用程序,使用在Google驱动器中填充excel表SpreadsheetApp.而另一部分则呼吁ContentService将数据下载为excel文件.
function doGet(e) {
// Read excel sheet
//getAppFile();
// Render the application from HTML template
return HtmlService.createTemplateFromFile('index').evaluate()
.setTitle('Go Smart')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function downloadDoubleQuateCsvFile() {
var sheetId = PropertiesService.getScriptProperties().getProperty('sheetId');
var ss = SpreadsheetApp.openById(sheetId).getActiveSheet();
//var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var maxColumn = ss.getLastColumn();
var maxRow = ss.getLastRow();
var data = ss.getRange(1, 1, maxRow, maxColumn).getValues();
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != - 1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
if (row < data.length - 1) {
csv += data[row].join(",") + "\r\n";
} else {
csv += data[row];
}
}
csvFile = csv;
}
return makeCSV(csvFile);
}
function makeCSV(csvString) {
var csvFileName = 'test.csv';
var output = ContentService.createTextOutput();
output.setMimeType(ContentService.MimeType.CSV);
output.setContent(csvString);
output.downloadAsFile(csvFileName);
return output;
}
Run Code Online (Sandbox Code Playgroud)
此脚本只是在控制台中提供工作表标题详细信息对象,而不是下载任何文件.
<button class="btn btn-success btn-sm" onclick="google.script.run.downloadDoubleQuateCsvFile()">Export</button>
Run Code Online (Sandbox Code Playgroud)
在第二个函数中添加return后,我收到这样的错误.
Error: The script completed but the returned value is not a supported return type.
Run Code Online (Sandbox Code Playgroud)
注意:我在驱动器中有excel文件和数据
Spe*_*ton 12
要使downloadAsFile()方法起作用,必须从发布的URL调用的doGet()或doPost()返回contentservice对象.
例:
function doGet(){
var output = ContentService.createTextOutput();
output.setMimeType(ContentService.MimeType.CSV);
output.setContent(csvString);
output.downloadAsFile(csvFileName);
return output;
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中,您将通过google.script.run将ContentService对象返回到网页.它不会要求从浏览器下载.事实上,返回contentservice对象将导致错误,因为它不是返回google.script.run调用的有效对象.仅允许本机javascript对象.
如果您希望它能够工作,您需要向用户显示一个指向单击的链接,该链接将指向另一个选项卡中的脚本.或者,您可以在指向脚本的锚标记上使用"download"属性.
例如,这假设您保留returnDoubleQuateCsvFile()的返回修复:
function doGet(e){
var serveCSV = e.parameter.servecsv;
if(serveCSV){return downloadDoubleQuateCsvFile()}
return HtmlService.createTemplateFromFile('index').evaluate()
.setTitle('Go Smart')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Run Code Online (Sandbox Code Playgroud)
在您的网页中:
<a href="//script.google.com/WebAppURL/exec?servecsv=true" target="_blank">Click here to download</a>
Run Code Online (Sandbox Code Playgroud)
请记住,并非所有浏览器都支持此功能.(只考虑chrome,opera,firefox支持自动下载).