下载 Google 个 Sheets 文件并在 Node 上使用 SheetJS 读取数据

Download Google Sheets file and read data using SheetJS on Node

我在 Google 表格上有一个电子表格,其中包含一些数据。我已经公开发布了它,这样我就可以使用 URL 下载数据作为 .xlsx 文件。我想要做的是在节点中的以下内容:

以下是文件的 URL:Google Sheets link

通过 SheetJS 库,我知道我需要使用 XLSX.read(data, opts),但我似乎无法弄清楚如何使用它。到目前为止我有以下代码:

var https = require('https');
var fs = require('fs');
var XLSX = require("xlsx");

var fileURL = "https://docs.google.com/spreadsheets/d/e/2PACX-1vR9jv7gj6o0dtL0QoeHxW7Ux2fk0Br6slV3mg-uzZY6hc17Zw-_cXRz0-pilCeZx_lDzaRAo0tNfueT/pub?output=xlsx"

// Somehow use the url to read the file using XLSX.read(data, opts) and store it in a variable called workbook

var sheet1 = workbook.Sheets[workbook.SheetNames[0]]
var sheet2 = workbook.Sheets[workbook.SheetNames[1]]
        
console.log(XLSX.utils.sheet_to_json(sheet1));
console.log(XLSX.utils.sheet_to_json(sheet2));

我该怎么做?我可以在本地完美地处理文件,但是使用 URL 方法,我很迷茫。感谢您的帮助!

你的情况,下面的修改怎么样?

修改后的脚本:

const request = require("request");
const XLSX = require("xlsx");

const fileURL =
  "https://docs.google.com/spreadsheets/d/e/2PACX-1vR9jv7gj6o0dtL0QoeHxW7Ux2fk0Br6slV3mg-uzZY6hc17Zw-_cXRz0-pilCeZx_lDzaRAo0tNfueT/pub?output=xlsx";

request.get(fileURL, { encoding: null }, function (err, res, data) {
  if (err || res.statusCode != 200) {
    console.log(res.statusCode);
    return;
  }
  const buf = Buffer.from(data);
  const workbook = XLSX.read(buf);

  var sheet1 = workbook.Sheets[workbook.SheetNames[0]];
  var sheet2 = workbook.Sheets[workbook.SheetNames[1]];
  console.log(XLSX.utils.sheet_to_json(sheet1));
  console.log(XLSX.utils.sheet_to_json(sheet2));
});
  • 本次修改使用了request的模块

结果:

当此脚本为运行时,得到如下结果

[
  { Team: 'Manchester United' },
  { Team: 'PSG' },
  { Team: 'Barcelona' },
  { Team: 'Real Madrid' },
  { Team: 'Juventus' }
]
[
  { Name: 'Ronaldo', Age: 37 },
  { Name: 'Messi', Age: 34 },
  { Name: 'Neymar', Age: 30 }
]