Can I generate a file from Google Sheets script?
I'm using Google Sheets to prototyp开发者_如何转开发e a bunch of numerical data for something I'm doing.
Is there a way to export a subset to a text file?
Effectively, what I'm aiming to do is export a file I can include directly in the build for another project.
So is there a way to generate a text file for download?
If you have a Google Apps account, then you can use DocsList.createFile() to create the text file and save it in your documents list.
Section 3 of this tutorial shows how to save the selected range of a spreadsheet as a file in your documents list in CSV format. It could be modified pretty easily to save in a different format.
I have the texts of my project in some columns of a Google Spreadsheet. I took this script tutorial from Google and modified it to select only a specific range (in the example below it's D4:D).
It generates a CSV file in your Drive root folder. It still doesn't download the file - I'm working on that now.
Hope it helps!
/* The code below is a modification from this tutorial: https://developers.google.com/apps-script/articles/docslist_tutorial#section3 */
/* The code below is a modification from this tutorial: https://developers.google.com/apps-script/articles/docslist_tutorial#section3 */
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var csvMenuEntries = [{name: "Save as CSV file", functionName: "saveAsCSV"}];
ss.addMenu("CSV", csvMenuEntries);
}
function saveAsCSV() {
// Name the file
fileName = "quests.csv";
// Convert the range data to CSV format
var csvFile = convertRangeToCsvFile_(fileName);
// Create a file in the root of my Drive with the given name and the CSV data
DriveApp.createFile(fileName, csvFile);
}
function convertRangeToCsvFile_(csvFileName) {
// Get from the spreadsheet the range to be exported
var rangeToExport = SpreadsheetApp.getActiveSpreadsheet().getRange("D4:D");
try {
var dataToExport = rangeToExport.getValues();
var csvFile = undefined;
// Loop through the data in the range and build a string with the CSV data
if (dataToExport.length > 1) {
var csv = "";
for (var row = 0; row < dataToExport.length; row++) {
for (var col = 0; col < dataToExport[row].length; col++) {
if (dataToExport[row][col].toString().indexOf(",") != -1) {
//dataToExport[row][col] = "\"" + dataToExport[row][col] + "\"";
dataToExport[row][col] = dataToExport[row][col];
}
}
// Join each row's columns
// Add a carriage return to end of each row, except for the last one
if (row < dataToExport.length-1) {
csv += dataToExport[row].join(",") + "\r\n";
}
else {
csv += dataToExport[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
精彩评论