如何自动将上传的CSV或XLS文件中的数据导入Google表格

时间:2014-11-10 22:55:03

标签: google-apps-script google-sheets google-drive-api google-spreadsheet-api

我在服务器上有遗留数据库系统(不可通过网络访问),可以生成CSV或XLS报告到Google云端硬盘文件夹。目前,我手动在云端硬盘网络界面中打开这些文件并将其转换为Google表格。

我希望这是自动的,以便我可以创建附加/转换和绘制其他工作表中数据的作业。

是否可以输出原生的.gsheet文件?或者,有无法通过Google Apps或基于Windows的脚本/实用程序将CSV或XLS保存到Google云端硬盘后以编程方式将其转换为.gsheet吗?

4 个答案:

答案 0 :(得分:33)

您可以使用Google Apps脚本以编程方式将数据从驱动器中的csv文件导入现有的Google表格,根据需要替换/附加数据。

下面是一些示例代码。它假设: a)您在云端硬盘中有一个指定的文件夹,其中保存/上传了CSV文件; b) CSV文件名为" report.csv"并以逗号分隔的数据;和 c)将CSV数据导入指定的电子表格。有关详细信息,请参阅代码中的注释。

function importData() {
  var fSource = DriveApp.getFolderById(reports_folder_id); // reports_folder_id = id of folder where csv reports are saved
  var fi = fSource.getFilesByName('report.csv'); // latest report file
  var ss = SpreadsheetApp.openById(data_sheet_id); // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data

  if ( fi.hasNext() ) { // proceed if "report.csv" file exists in the reports folder
    var file = fi.next();
    var csv = file.getBlob().getDataAsString();
    var csvData = CSVToArray(csv); // see below for CSVToArray function
    var newsheet = ss.insertSheet('NEWDATA'); // create a 'NEWDATA' sheet to store imported data
    // loop through csv data array and insert (append) as rows into 'NEWDATA' sheet
    for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
      newsheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    }
    /*
    ** report data is now in 'NEWDATA' sheet in the spreadsheet - process it as needed,
    ** then delete 'NEWDATA' sheet using ss.deleteSheet(newsheet)
    */
    // rename the report.csv file so it is not processed on next scheduled run
    file.setName("report-"+(new Date().toString())+".csv");
  }
};


// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.

function CSVToArray( strData, strDelimiter ) {
  // Check to see if the delimiter is defined. If not,
  // then default to COMMA.
  strDelimiter = (strDelimiter || ",");

  // Create a regular expression to parse the CSV values.
  var objPattern = new RegExp(
    (
      // Delimiters.
      "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

      // Quoted fields.
      "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

      // Standard fields.
      "([^\"\\" + strDelimiter + "\\r\\n]*))"
    ),
    "gi"
  );

  // Create an array to hold our data. Give the array
  // a default empty first row.
  var arrData = [[]];

  // Create an array to hold our individual pattern
  // matching groups.
  var arrMatches = null;

  // Keep looping over the regular expression matches
  // until we can no longer find a match.
  while (arrMatches = objPattern.exec( strData )){

    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[ 1 ];

    // Check to see if the given delimiter has a length
    // (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know
    // that this delimiter is a row delimiter.
    if (
      strMatchedDelimiter.length &&
      (strMatchedDelimiter != strDelimiter)
    ){

      // Since we have reached a new row of data,
      // add an empty row to our data array.
      arrData.push( [] );

    }

    // Now that we have our delimiter out of the way,
    // let's check to see which kind of value we
    // captured (quoted or unquoted).
    if (arrMatches[ 2 ]){

      // We found a quoted value. When we capture
      // this value, unescape any double quotes.
      var strMatchedValue = arrMatches[ 2 ].replace(
        new RegExp( "\"\"", "g" ),
        "\""
      );

    } else {

      // We found a non-quoted value.
      var strMatchedValue = arrMatches[ 3 ];

    }

    // Now that we have our value string, let's add
    // it to the data array.
    arrData[ arrData.length - 1 ].push( strMatchedValue );
  }

  // Return the parsed data.
  return( arrData );
};

然后,您可以在脚本项目中创建time-driven trigger以定期运行importData()函数(例如每天凌晨1点),所以您只需将新的report.csv文件放入指定的Drive文件夹,它将在下次计划的运行时自动处理。

如果绝对必须使用Excel文件而不是CSV,那么您可以使用下面的代码。要使其发挥作用,您必须在脚本和开发者控制台中的高级Google服务中启用Drive API(有关详细信息,请参阅How to Enable Advanced Services)。

/**
 * Convert Excel file to Sheets
 * @param {Blob} excelFile The Excel file blob data; Required
 * @param {String} filename File name on uploading drive; Required
 * @param {Array} arrParents Array of folder ids to put converted file in; Optional, will default to Drive root folder
 * @return {Spreadsheet} Converted Google Spreadsheet instance
 **/
function convertExcel2Sheets(excelFile, filename, arrParents) {

  var parents  = arrParents || []; // check if optional arrParents argument was provided, default to empty array if not
  if ( !parents.isArray ) parents = []; // make sure parents is an array, reset to empty array if not

  // Parameters for Drive API Simple Upload request (see https://developers.google.com/drive/web/manage-uploads#simple)
  var uploadParams = {
    method:'post',
    contentType: 'application/vnd.ms-excel', // works for both .xls and .xlsx files
    contentLength: excelFile.getBytes().length,
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    payload: excelFile.getBytes()
  };

  // Upload file to Drive root folder and convert to Sheets
  var uploadResponse = UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&convert=true', uploadParams);

  // Parse upload&convert response data (need this to be able to get id of converted sheet)
  var fileDataResponse = JSON.parse(uploadResponse.getContentText());

  // Create payload (body) data for updating converted file's name and parent folder(s)
  var payloadData = {
    title: filename, 
    parents: []
  };
  if ( parents.length ) { // Add provided parent folder(s) id(s) to payloadData, if any
    for ( var i=0; i<parents.length; i++ ) {
      try {
        var folder = DriveApp.getFolderById(parents[i]); // check that this folder id exists in drive and user can write to it
        payloadData.parents.push({id: parents[i]});
      }
      catch(e){} // fail silently if no such folder id exists in Drive
    }
  }
  // Parameters for Drive API File Update request (see https://developers.google.com/drive/v2/reference/files/update)
  var updateParams = {
    method:'put',
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    contentType: 'application/json',
    payload: JSON.stringify(payloadData)
  };

  // Update metadata (filename and parent folder(s)) of converted sheet
  UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/'+fileDataResponse.id, updateParams);

  return SpreadsheetApp.openById(fileDataResponse.id);
}

/**
 * Sample use of convertExcel2Sheets() for testing
 **/
 function testConvertExcel2Sheets() {
  var xlsId = "0B9**************OFE"; // ID of Excel file to convert
  var xlsFile = DriveApp.getFileById(xlsId); // File instance of Excel file
  var xlsBlob = xlsFile.getBlob(); // Blob source of Excel file for conversion
  var xlsFilename = xlsFile.getName(); // File name to give to converted file; defaults to same as source file
  var destFolders = []; // array of IDs of Drive folders to put converted file in; empty array = root folder
  var ss = convertExcel2Sheets(xlsBlob, xlsFilename, destFolders);
  Logger.log(ss.getId());
}

The above code is also available as a gist here

答案 1 :(得分:7)

您可以通过附加

让Google云端硬盘自动将csv文件转换为Google表格
?convert=true

到你打电话的api网址的末尾。

编辑: 以下是可用参数的文档: https://developers.google.com/drive/v2/reference/files/insert

此外,在搜索上述链接时,我发现此问题已在此处得到解答:

Upload CSV to Google Drive Spreadsheet using Drive v2 API

答案 2 :(得分:6)

(2017年3月)接受的答案不是最佳解决方案。它依赖于使用Apps脚本进行手动翻译,而且代码可能不具备弹性,需要维护。如果旧系统自动生成CSV文件,最好将其转到另一个文件夹进行临时处理(导入[上传到Google云端硬盘和转换]到Google表格文件)。

我的想法是让Drive API完成所有繁重工作。 2015年底的Google Drive API小组released v3,在该版本中,insert()将名称更改为create(),以便更好地反映文件操作。还没有更多转换标志 - 你只需指定MIME类型......想象一下!

文档也得到了改进:现在有一个special guide devoted to uploads(简单,多部分,可恢复),包含Java,Python,PHP,C#/ .NET,Ruby,JavaScript中的示例代码/Node.js和iOS / Obj-C可根据需要将CSV文件导入Google表格格式。

以下是短文件的另一种Python解决方案(&#34;简单上传&#34;),您需要apiclient.http.MediaFileUpload课程。此代码段假定您的身份验证代码适用于服务端点为DRIVE且最小身份验证范围为https://www.googleapis.com/auth/drive.file的位置。

# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'

# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
    print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))

更好的是,您不必上传到My Drive,而是上传到一个(或多个)特定文件夹,这意味着您要将父文件夹ID添加到{ {1}}。 (另请参阅this page上的代码示例。)最后,没有原生的.gsheet&#34;文件&#34; - 该文件只有一个指向在线工作表的链接,所以上面是你想要做的。

如果不使用Python,您可以使用上面的代码作为伪代码来移植到您的系统语言。无论如何,维护的代码要少得多,因为没有CSV解析。唯一剩下的就是吹掉遗留系统写入的CSV文件临时文件夹。

答案 3 :(得分:0)

万一有人在搜索-我创建了一个实用程序,用于将xlsx文件自动导入到Google电子表格中:xls2sheets。可以通过为./cmd/sheets-refresh设置cronjob来自动完成此操作,自述文件对此进行了描述。希望会有用。