CSV文件在Google Apps中创建

时间:2012-05-17 09:13:33

标签: google-apps google-apps-script

我尝试使用Google Apps(脚本)通过API上传.csv文件。

我在API网址的一部分中提供了以下属性。

“ZOHO_FILE”:FILE.CSV

有没有办法在Google Apps脚本中创建.csv文件?

如果可能,请告诉我们,如何在Google Apps中创建.csv文件?

对不起我的英文: - (

2 个答案:

答案 0 :(得分:3)

您可以使用它来转换数据范围:

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);
  }
}

或者下载整张表

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
}

答案 1 :(得分:1)

我希望你要求提供Apps脚本;

以下文章的第2节和第3节介绍了如何导入和导出CSV

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