如何使用DriveApp而不是DocsList将csv文件导入Google表格

时间:2015-04-22 02:48:30

标签: csv google-apps-script

我有一个类似于https://stackoverflow.com/a/26139420/4817369的问题,除了我使用FileID不实用。

我一直在使用这个Google脚本: https://developers.google.com/apps-script/articles/docslist_tutorial 将csv文件导入Google表格,以便我可以使用其他Google脚本修改csv文件。但是,DocsList功能昨天正式完成了设置,我似乎无法使我的代码与DriveApp一起使用。

function importFromCSV() {
  var fileName = Browser.inputBox("Enter the name of the file in your Docs    List to import (e.g. myFile.csv):");

var files = DocsList.getFiles();
var csvFile = "";

  for (var i = 0; i < files.length; i++) {
    if (files[i].getName() == fileName) {
      csvFile = files[i].getContentAsString();
      break;
     }
   }
  var csvData = CSVToArray(csvFile, ",");
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  for (var i = 0; i < csvData.length; i++) {
    sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new      Array(csvData[i]));
  }
}

一旦我搜索过,我无法弄清楚如何按名称实际检索特定文件 - 我尝试了各种不成功的版本,例如:

  var fileName = Browser.inputBox("Enter the name of the file in your Docs     List to import (e.g. myFile.csv):");
  var searchFiles = DriveApp.searchFiles(title = fileName);
  while (searchFiles.hasNext()) {
    var file = searchFiles.next();
    Logger.log(file.getName());
  }

  var csvFile = file.getBlob().getDataAsString();// get string content
  Logger.log(csvFile);// check in the logger
  var csvData = CSVToArray_(csvFile);// convert to 2D array
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  sheet.getRange(1,1, csvData.length,  csvData[0].length).setValues(csvData);// write to sheet in one single step
    }

我对编码的经验很少,所以任何建议都会受到赞赏!

1 个答案:

答案 0 :(得分:0)

您的搜索参数语法缺少引号。应该是这样的:

var searchFiles = DriveApp.searchFiles("title = '" + fileName + "'");