将数据从 Google Drive 中的 CSV 文件导入到 Google Sheet

Kha*_*idN 5 csv import google-sheets

我正在使用 SAS 每 24 小时生成两个 CSV 文件。我使用 bat 脚本将生成的 CSV 文件保存在 Google Drive 的文件夹中。CSV 文件已被替换,因此文件夹中将始终只有这两个文件。

CSV 文件以“,”分隔,仅包含三列或四列。

我想在 Google 表格和 CSV 文件之间创建直接链接,以便 Google 表格自动更新为最新数字。

我尝试过使用“ImportData”功能但没有成功

=IMPORTDATA("https://drive.google.com/file/d/123231jshu231731/edit?usp=sharing")
Run Code Online (Sandbox Code Playgroud)

其中 123231jshu231731 是 file_id。

但我得到的错误是

Result was not automatically expanded, please insert more columns (896).
Run Code Online (Sandbox Code Playgroud)

这没有意义,因为文件只有 3 列

希望有人能更好地解决我的自动化问题

谢谢

Jos*_*son 4

将 csv 文件发布到网络

显然IMPORTDATA仅适用于发布到网络上的文档。让它为你工作的两种方法是:

  1. 将您的 csv 文件存储在公共 Google 云端硬盘文件夹中
  2. 以其他方式在网络上托管您的 csv 文件 - 我想您需要在您的计算机上使用 csv 文件运行服务器。

但是,这涉及将您的 csv 数据公开给连接到互联网的任何人(可能是您不想要的)


保持 csv 文件的私密性

如果您希望数据保持私密性,您可以编写一个脚本来定期将 csv 数据加载到电子表格中。

Google 提供了一项名为Google Apps Script (GAS)的服务,该服务允许您使用 JavaScript 编写脚本以在 Google Drive 中执行更复杂的任务。

在 GAS 中,您可以创建称为可安装触发器的东西,您可以将其设置为按设定的时间间隔定期运行。

以下是我如何编写上传 csv 数据的脚本的基本布局:

function timedTrigger() {
  // list the csv file ids
  var baseballScoresFileId = "123231jshu231731";
  var donutPricesFileId = "984732ageyn555646";

  // get the spreadsheet by it's id
  var ss = SpreadsheetApp.openById("the spreadsheet id");

  // get the sheets you want to print the data to
  var baseballSheet = ss.getSheetByName("Baseball Scores");
  var donutsSheet = ss.getSheetByName("Donuts Scores");

  // print the data to the first row first columnscript
  printCsvData(baseballScoresFileId, baseballSheet, 1, 1);

  printCsvData(donutPricesFileId, donutsSheet, 5, 2); // prints to B5
}

// This function loads the data from a csv fileId
//   and prints it to the sheet starting at the cell
//   located at (row, col)
// It works just like IMPORTDATA except you specify the row and col in the 
function printCsvData(fileId, sheet, row, col) {
  // get data from file
  var data = DriveApp.getFileById(fileId).getBlob().getDataAsString();

  // parse the csv string into two dimensional array
  var values = parseCsvData(data);

  // print the values into the range starting at row, col
  sheet.getRange(row, col, values.length, values[0].length).setValues(values);
}

// This function converts a string of comma
//   separated values and converts them into
//   a two dimensional array
function parseCsv(string) {
  var values = [];
  // ...
  return values;
}
Run Code Online (Sandbox Code Playgroud)

我不太确定您的 CSV 文件格式如何;我最好的猜测是:

function parseCSV(string) {
  return string.split("\n").map(function (row) {
    return row.split(",");
  });
}
Run Code Online (Sandbox Code Playgroud)

您可能需要担心额外的空格。


如果您不熟悉 JavaScript 或编程,这将是一个很好的学习机会。但是,如果加载 csv 文件不是迫切需要,请注意,您可能需要 5-20 小时来学习如何设置脚本。不管怎样,祝你好运!