【问题标题】:How to automatically import data from uploaded CSV or XLS file into Google Sheets如何将上传的 CSV 或 XLS 文件中的数据自动导入 Google 表格
【发布时间】:2015-01-07 09:24:39
【问题描述】:

我的服务器上有一个旧数据库系统(无法通过网络访问),它会生成 CSV 或 XLS 报告到 Google Drive 文件夹。目前,我在 Drive Web 界面中手动打开这些文件并将它们转换为 Google 表格。

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

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

【问题讨论】:

  • google-spreadsheet-api 可以将数据导入现有的 google 电子表格。我怀疑 Drive API 可以作为新的电子表格文件导入,因为我想我在 SO 上看到了一些导入代码。
  • 很好奇您的旧系统如何将报告文件直接生成到 Google Drive。它是否使用 Drive API 或其他机制?如果是前者,那么您可以将代码更改为即时自动转换为表格,而不是对 CSV 文件进行后处理。

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


【解决方案1】:

如果有人会搜索 - 我创建了用于将 xlsx 文件自动导入谷歌电子表格的实用程序:xls2sheets。可以通过为./cmd/sheets-refresh 设置 cronjob 来自动完成,自述文件描述了这一切。希望对你有用。

【讨论】:

    【解决方案2】:

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

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

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

    下面是另一种用于短文件(“简单上传”)的 Python 解决方案,您不需要需要 apiclient.http.MediaFileUpload 类。此 sn-p 假定您的身份验证代码在您的服务端点为 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 添加到 METADATA。 (另请参阅this page 上的代码示例。)最后,没有原生 .gsheet“文件”——该文件只有一个指向在线工作表的链接,所以上面的内容就是您想要做的。

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

    【讨论】:

      【解决方案3】:

      您可以让 Google Drive 自动将 csv 文件转换为 Google 表格,方法是附加

      ?convert=true
      

      到您正在调用的 api url 的末尾。

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

      另外,在搜索上面的链接时,我发现这个问题已经在这里得到了回答:

      Upload CSV to Google Drive Spreadsheet using Drive v2 API

      【讨论】:

      • 报告程序不允许 HTTP 调用。它所能做的就是生成 CSV 或 XLS 并将其放在一个文件夹中(恰好是一个 google 驱动器文件夹)。
      • 我想知道...是否可以从 appscript 调用它,以便它只转换并将我放入某个文件夹的文件?
      • ?convert=true 参数仅适用于在同一个 http 请求中上传的文件。检查您使用的 Google Drive 应用程序的设置,看看是否有处理转换的设置。在幕后,该程序将使用 http 请求来同步您的文件。
      • 对于 API 的 v3 convert 不再有效。而是将上传的 MIME 类型指定为 text/csv,并将所需文件的 MIME 类型指定为 application/vnd.google-apps.spreadsheet
      • @Vadoff 谢谢,它有效。您应该将其作为单独的答案以供将来参考。
      【解决方案4】:

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

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

      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

      【讨论】:

      • 这是完美的,谢谢。由于某些报告包含逗号,遗憾的是,遗留程序无法使用另一个分隔符,有没有办法以这种方式导入 Excel 电子表格?
      • 其实,如果你不介意的话,我还有一个后续问题。出于小型企业报告的目的(数据不多),保存数据的最佳位置在哪里?在一组 Google 表格中,还是使用他们的 AppEngine 数据库有意义?
      • 如果您的遗留问题正确输出 csv,将任何带有逗号的值括在引号中,那么没关系,脚本将起作用。如果您必须使用 Excel 文件,那么the code here for converting Excel file to Google Spreadsheet 就可以了。在我的测试中,它适用于 xls 和 xlsx 文件。要使用该代码,您必须在项目的高级 Google 服务和开发者控制台中启用 Drive API。代码所需的开发者密钥是您可以在开发控制台中创建的服务器密钥。
      • 我已经修改了我在之前的评论中链接到的将 Excel 转换为表格的示例代码,以使其更简单(不使用 oAuth2,因为当您以所有者身份运行脚本时没有必要)。 You can find my updated convertExcel2Sheets function here。我也将它添加到我的答案中。
      • @clemlaflemme 是的,这可能很棘手 - 完全取决于使用哪种身份验证过程。现在它通常是基于会话 cookie 的,使用 URLFetchApp 重现是很痛苦的。如果您的数据服务没有适当的 API,它可能就像将用户名和密码值作为 POST 请求的正文一样简单,也可能像多个请求通过各种标头和 cookie 一样困难。抱歉,如果无法实际访问数据,我将无能为力。
      猜你喜欢
      • 2019-11-29
      • 2020-02-23
      • 2018-08-17
      • 1970-01-01
      • 2014-02-15
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多