Home > OS >  Download text file from Google Sheet with App Script
Download text file from Google Sheet with App Script

Time:06-20

I wrote this code to set up a custom menu in a Google worksheet to download to local machine disk a TXT file with some data taken from some cell. At the very first stage I'm just trying to download "something" ("test 123" in the code below) but I get a red "try later" error from server.

Here I'm adding the menu in the worksheet

function onOpen() {
  SpreadsheetApp.getUi().createMenu('Export')
  .addItem('Download cycle for SD card', 'downloadAsFile')
  .addToUi();
}

and here there's the implementation of the function attached to the menu

function downloadAsFile(){

  var output = ContentService.createTextOutput()
                .setMimeType(ContentService.MimeType.TEXT)
                .setContent("test 123")
                .downloadAsFile("Cycle_JSON.txt");

  return output

}

If I use this second snippet inside function doGet() and I launch the script from a browser page it works fine, but that's not the way how it is intended to work.

I would prefer avoid to pass through Google Drive if not strictly necessary to keep things simple, but if there's no other chance it would be acceptable.

Any suggestion?

CodePudding user response:

Try this automatic tool

function downloadAsFile() {
  var content = 'test 123'
  var html = HtmlService.createHtmlOutput(`
<html><body onl oad="document.getElementById('dwn-btn').click()">
<textarea id="text-val" rows="10" style="display:none;">${content}</textarea>
<input type="button" id="dwn-btn" value="Download text file" style="display:none;"/>
<script>
window.close = function(){window.setTimeout(function(){google.script.host.close()},100)}
function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,'   encodeURIComponent(text));
    element.setAttribute('download', filename);
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function(){
    var text = document.getElementById("text-val").value;
    var filename = "Cycle_JSON.txt";
    download(filename, text);
  close();
}, false);
</script>
</body></html>  
  `)
    .setWidth(250).setHeight(100);
  SpreadsheetApp.getUi().showModalDialog(html, "Download file ...");
}
  • Related