1
votes

I have tried to Upload .csv file via API using Google Apps (Script).

I give the below property in part of API URL.

"ZOHO_FILE":file.csv

Is there any way to create .csv file in Google Apps Script ?

If possible, pls let us know, how can create .csv file in Google Apps ?

Sorry for my english :-(

2
This does not appear to be google app engine question. - specialscope

2 Answers

3
votes

You can use this to convert a data range:

function convertRangeToCsvFile(dataRange) {

  try {
    var data = dataRange.getValues();

    var csvFile = undefined;

    // Loop through the data in the range and build a string with the CSV data
    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] + "\"";
          }
        }

        // Join each row's columns
        // Add a carriage return to end of each row, except for the last one
        if (row < data.length-1) {
          csv += data[row].join(",") + "\r\n";
        }
        else {
          csv += data[row];
        }
      }
      csvFile = csv;
    }
    return csvFile;
  }
  catch(err) {
    Logger.log(err);
    Browser.msgBox(err);
  }
}

or this to download a whole sheet

function downloadSpreadsheet(){
  //This function generates a pdf of your current spreadsheet and emails it to yourself as attachment
  //Make sure your spreadsheet is not too big. The pdf size tends to be 200kb/page and if too large
  //if the pdf is too large the urlFetch might timeout

  var AUTH_TOKEN = "xxxxxxxxxxxxxx"; //Enter your AUTH_TOKEN
  //You can receive it from https://appscripts.appspot.com/getAuthToken

  var ssID=SpreadsheetApp.getActiveSpreadsheet().getId()+"&gid="+SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
  var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
      + ssID + "&exportFormat=csv"; 
  //Add &gid=x at the end of above url if you only want a particular sheet
  //gid of a sheet can be obtained by the undocumented function getSheetId()
  //ex: SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
  //exportFormat=xls did not work when I tried. I dont know why

  var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";

  var res = UrlFetchApp.fetch(url, {headers: {Authorization: auth}});
  var content=res.getContentText();
  return content
}
0
votes

You asked for Apps Script, I hope;

Section 2 and 3 of the article below tells how to import and export CSV

https://developers.google.com/apps-script/articles/docslist_tutorial#section2