如何仅使用 Javascript 访问 Google Sheets 电子表格?

发布于 2024-10-01 12:34:43 字数 139 浏览 11 评论 0原文

我想仅使用 JavaScript(无 .NET、C#、Java 等)访问 Google 电子表格

我来了

请告诉我如何使用 JavaScript 或其任何框架(如 jQuery)访问(创建/编辑/删除)Google Sheets。

I want to access Google Spreadsheets using JavaScript only (no .NET, C#, Java, etc.)

I came here and was shocked to know that there is NO API for JavaScript to access Google Sheets.

Please tell me how to access (CREATE/EDIT/DELETE) Google Sheets using JavaScript or any of its frameworks like jQuery.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

心头的小情儿 2024-10-08 12:34:44

要点如下。

您可以使用 Google Sheets API。目前无法使用 API 删除电子表格(请阅读文档)。将 Google Docs API 视为创建和查找文档的途径。

您可以使用基于工作表的 Feed 在电子表格中添加/删除工作表

可以通过基于列表的 Feed 更新电子表格或基于单元格的 Feed

可以通过上述 Google Spreadsheets API 读取电子表格,或者仅针对已发布的工作表,使用 Google Visualization API 查询语言来查询数据(它可以返回 CSV、JSON 或 HTML 表格格式的结果)。


忘记 jQuery。只有当您遍历 DOM 时,jQuery 才真正有价值。由于 GAS(Google Apps 脚本)不使用 DOM,jQuery 不会为您的代码添加任何价值。坚持香草。

我真的很惊讶没有人在答案中提供这些信息。不仅可以做到这一点,而且使用普通 JS 相对容易做到。唯一的例外是 Google Visualization API,它相对较新(截至 2011 年)。可视化 API 还专门通过 HTTP 查询字符串 URI 工作。

Here's the Gist.

You can create a spreadsheet using the Google Sheets API. There is currently no way to delete a spreadsheet using the API (read the documentation). Think of Google Docs API as the route to create and look-up documents.

You can add/remove worksheets within the spreadsheet using the worksheet based feeds.

Updating a spreadsheet is done through either list based feeds or cell based feeds.

Reading the spreadsheet can be done through either the Google Spreadsheets APIs mentioned above or, for published sheets only, by using the Google Visualization API Query Language to query the data (which can return results in CSV, JSON, or HTML table format).


Forget jQuery. jQuery is only really valuable if you're traversing the DOM. Since GAS (Google Apps Scripting) doesn't use the DOM jQuery will add no value to your code. Stick to vanilla.

I'm really surprised that nobody has provided this information in an answer yet. Not only can it be done, but it's relatively easy to do using vanilla JS. The only exception being the Google Visualization API which is relatively new (as of 2011). The Visualization API also works exclusively through a HTTP query string URI.

缪败 2024-10-08 12:34:44

有一种解决方案不需要发布电子表格。但是,该工作表确实需要“共享”。更具体地说,需要以一种任何知道链接的人都可以访问电子表格的方式共享工作表。完成此操作后,即可使用 Google Sheets HTTP API。

首先,您需要一个 Google API 密钥。前往这里:
https://developers.google.com/places/web-service/get -api-key
注意。请注意向公众提供 API 密钥的安全后果:https://support .google.com/googleapi/answer/6310037

获取电子表格的所有数据 - 警告,这可能会包含大量数据。

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true

获取工作表元数据

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}

获取一系列单元格

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{sheetName}!{cellRange}?key={yourAPIKey}

现在有了这些信息,就可以使用 AJAX 检索数据,然后在 JavaScript 中对其进行操作。我建议使用 axios

var url = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true";                                                             
axios.get(url)
  .then(function (response) {
    console.log(response);                                                                                                                                                    
  })
  .catch(function (error) {
    console.log(error);                                                                                                                                                       
  });                

There's a solution that does not require one to publish the spreadsheet. However, the sheet does need to be 'Shared'. More specifically, one needs to share the sheet in a manner where anyone with the link can access the spreadsheet. Once this is done, one can use the Google Sheets HTTP API.

First up, you need an Google API key. Head here:
https://developers.google.com/places/web-service/get-api-key
NB. Please be aware of the security ramifications of having an API key made available to the public: https://support.google.com/googleapi/answer/6310037

Get all data for a spreadsheet - warning, this can be a lot of data.

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true

Get sheet metadata

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}

Get a range of cells

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{sheetName}!{cellRange}?key={yourAPIKey}

Now armed with this information, one can use AJAX to retrieve data and then manipulate it in JavaScript. I would recommend using axios.

var url = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true";                                                             
axios.get(url)
  .then(function (response) {
    console.log(response);                                                                                                                                                    
  })
  .catch(function (error) {
    console.log(error);                                                                                                                                                       
  });                
故事与诗 2024-10-08 12:34:44

2016 更新:最简单的方法是使用 Google Apps Script API,特别是 电子表格服务。这适用于私人工作表,与需要发布电子表格的其他答案不同。

这将允许您将 JavaScript 代码绑定到 Google 表格,并在打开表格或选择菜单项(您可以定义)时执行它。

这是快速入门/演示。代码如下所示:

// Let's say you have a sheet of First, Last, email and you want to return the email of the
// row the user has placed the cursor on.
function getActiveEmail() {
  var activeSheet = SpreadsheetApp.getActiveSheet();
  var activeRow = activeSheet.getActiveCell().getRow();
  var email = activeSheet.getRange(activeRow, 3).getValue();

  return email;
}

您还可以将此类脚本发布为网络应用

2016 update: The easiest way is to use the Google Apps Script API, in particular the SpreadSheet Service. This works for private sheets, unlike the other answers that require the spreadsheet to be published.

This will let you bind JavaScript code to a Google Sheet, and execute it when the sheet is opened, or when a menu item (that you can define) is selected.

Here's a Quickstart/Demo. The code looks like this:

// Let's say you have a sheet of First, Last, email and you want to return the email of the
// row the user has placed the cursor on.
function getActiveEmail() {
  var activeSheet = SpreadsheetApp.getActiveSheet();
  var activeRow = activeSheet.getActiveCell().getRow();
  var email = activeSheet.getRange(activeRow, 3).getValue();

  return email;
}

You can also publish such scripts as web apps.

病毒体 2024-10-08 12:34:44

编辑:这个问题在 Google 文档的 API 发布之前就已得到解答。请参阅 Evan Plaice 的回答Dan Dascalescu 的回答了解更多最新信息
信息。

看起来好像可以,但使用起来很痛苦。它涉及使用 Google 数据 API。

http://gdatatips.blogspot.com/ 2008/12/using-javascript-client-library-w-non.html

“JavaScript 客户端库具有用于日历、通讯录、Blogger 和 Google Finance 的辅助方法。但是,您可以将它与几乎任何Google Data API 用于访问经过身份验证的/私人提要。此示例使用 DocList API。”

以及编写与电子表格交互的小工具的示例:http://code.google.com /apis/电子表格/小工具/

edit: This was answered before the google doc's api was released. See Evan Plaice's answer and Dan Dascalescu's answer for more up-to-date
information.

It looks lke you can, but it's a pain to use. It involves using the Google data API.

http://gdatatips.blogspot.com/2008/12/using-javascript-client-library-w-non.html

"The JavaScript client library has helper methods for Calendar, Contacts, Blogger, and Google Finance. However, you can use it with just about any Google Data API to access authenticated/private feeds. This example uses the DocList API."

and an example of writing a gadget that interfaces with spreadsheets: http://code.google.com/apis/spreadsheets/gadgets/

瞄了个咪的 2024-10-08 12:34:44

“JavaScript 访问 Google 文档”实施起来会很乏味,而且 Google 文档也不是那么容易获取的。我有一些很好的链接可以分享,通过它们你可以实现 js 对 gdoc 的访问:

http://code.google.com/apis/文件/docs/3.0/developers_guide_protocol.html#UploadingDocs

http://code.google.com/apis/spreadsheets/gadgets/

http://code.google.com/apis/gdata/docs/ js.html

http://www.mail-archive。 com/[电子邮件受保护]/msg01924.html

也许这些会有所帮助你出去..

'JavaScript accessing Google Docs' would be tedious to implement and moreover Google documentation is also not that simple to get it. I have some good links to share by which you can achieve js access to gdoc:

http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs

http://code.google.com/apis/spreadsheets/gadgets/

http://code.google.com/apis/gdata/docs/js.html

http://www.mail-archive.com/[email protected]/msg01924.html

May be these would help you out..

丢了幸福的猪 2024-10-08 12:34:44

抱歉,这是一个糟糕的答案。显然,这个问题已经存在近两年了,所以问题不要屏住呼吸。

以下是官方请求,您可以" star"

也许您能想到的最接近的方法就是使用 Google App Engine 推出您自己的服务/Python 并使用您自己的 JS 库公开您需要的任何子集。尽管我很想自己有更好的解决方案。

Sorry, this is a lousy answer. Apparently this has been an issue for almost two years so don't hold your breath.

Here is the official request that you can "star"

Probably the closest you can come is rolling your own service with Google App Engine/Python and exposing whatever subset you need with your own JS library. Though I'd love to have a better solution myself.

护你周全 2024-10-08 12:34:44

在这个快速变化的世界中,大多数链接都已经过时了。

现在您可以使用 Google 云端硬盘 Web API

In this fast changing world most of these link are obsolet.

Now you can use Google Drive Web APIs:

ヅ她的身影、若隐若现 2024-10-08 12:34:44

您可以使用 RGraph 工作表连接器以 JavaScript 读取 Google Sheets 电子表格数据:

https://www.rgraph.net/canvas/docs/import-data-from-google-sheets.html

最初(几年前)这依赖于一些 RGraph 函数来发挥其魔力- 但现在它可以独立工作(即不需要RGraph公共库)。

一些示例代码(此示例制作一个 RGraph 图表):

<!-- Include the sheets library -->
<script src="RGraph.common.sheets.js"></script>

<!-- Include these two RGraph libraries to make the chart -->
<script src="RGraph.common.key.js"></script>
<script src="RGraph.bar.js"></script>

<script>
    // Create a new RGraph Sheets object using the spreadsheet's key and
    // the callback function that creates the chart. The RGraph.Sheets object is
    // passed to the callback function as an argument so it doesn't need to be
    // assigned to a variable when it's created
    new RGraph.Sheets('1ncvARBgXaDjzuca9i7Jyep6JTv9kms-bbIzyAxbaT0E', function (sheet)
    {
        // Get the labels from the spreadsheet by retrieving part of the first row
        var labels = sheet.get('A2:A7');

        // Use the column headers (ie the names) as the key
        var key = sheet.get('B1:E1');

        // Get the data from the sheet as the data for the chart
        var data   = [
            sheet.get('B2:E2'), // January
            sheet.get('B3:E3'), // February
            sheet.get('B4:E4'), // March
            sheet.get('B5:E5'), // April
            sheet.get('B6:E6'), // May
            sheet.get('B7:E7')  // June
        ];

        // Create and configure the chart; using the information retrieved above
        // from the spreadsheet
        var bar = new RGraph.Bar({
            id: 'cvs',
            data: data,
            options: {
                backgroundGridVlines: false,
                backgroundGridBorder: false,
                xaxisLabels: labels,
                xaxisLabelsOffsety: 5,
                colors: ['#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5'],
                shadow: false,
                colorsStroke: 'rgba(0,0,0,0)',
                yaxis: false,
                marginLeft: 40,
                marginBottom: 35,
                marginRight: 40,
                key: key,
                keyBoxed: false,
                keyPosition: 'margin',
                keyTextSize: 12,
                textSize: 12,
                textAccessible: false,
                axesColor: '#aaa'
            }
        }).wave();
    });
</script>

You can read Google Sheets spreadsheets data in JavaScript by using the RGraph sheets connector:

https://www.rgraph.net/canvas/docs/import-data-from-google-sheets.html

Initially (a few years ago) this relied on some RGraph functions to work its magic - but now it can work standalone (ie not requiring the RGraph common library).

Some example code (this example makes an RGraph chart):

<!-- Include the sheets library -->
<script src="RGraph.common.sheets.js"></script>

<!-- Include these two RGraph libraries to make the chart -->
<script src="RGraph.common.key.js"></script>
<script src="RGraph.bar.js"></script>

<script>
    // Create a new RGraph Sheets object using the spreadsheet's key and
    // the callback function that creates the chart. The RGraph.Sheets object is
    // passed to the callback function as an argument so it doesn't need to be
    // assigned to a variable when it's created
    new RGraph.Sheets('1ncvARBgXaDjzuca9i7Jyep6JTv9kms-bbIzyAxbaT0E', function (sheet)
    {
        // Get the labels from the spreadsheet by retrieving part of the first row
        var labels = sheet.get('A2:A7');

        // Use the column headers (ie the names) as the key
        var key = sheet.get('B1:E1');

        // Get the data from the sheet as the data for the chart
        var data   = [
            sheet.get('B2:E2'), // January
            sheet.get('B3:E3'), // February
            sheet.get('B4:E4'), // March
            sheet.get('B5:E5'), // April
            sheet.get('B6:E6'), // May
            sheet.get('B7:E7')  // June
        ];

        // Create and configure the chart; using the information retrieved above
        // from the spreadsheet
        var bar = new RGraph.Bar({
            id: 'cvs',
            data: data,
            options: {
                backgroundGridVlines: false,
                backgroundGridBorder: false,
                xaxisLabels: labels,
                xaxisLabelsOffsety: 5,
                colors: ['#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5'],
                shadow: false,
                colorsStroke: 'rgba(0,0,0,0)',
                yaxis: false,
                marginLeft: 40,
                marginBottom: 35,
                marginRight: 40,
                key: key,
                keyBoxed: false,
                keyPosition: 'margin',
                keyTextSize: 12,
                textSize: 12,
                textAccessible: false,
                axesColor: '#aaa'
            }
        }).wave();
    });
</script>
中二柚 2024-10-08 12:34:44

对于此类事情,您应该使用 Google Fusion TablesAPI 就是为此目的而设计的。

For this type of thing you should use Google Fusion Tables. The API is designed for that purpose.

送舟行 2024-10-08 12:34:43

我创建了一个简单的 javascript 库,它通过 JSON api 检索 google 电子表格数据(如果已发布):

https://github.com/mikeymckay/google-spreadsheet-javascript

您可以在此处查看其实际效果:

http://mikeymckay.github.com/google-spreadsheet-javascript/sample.html

I have created a simple javascript library that retrieves google spreadsheet data (if they are published) via the JSON api:

https://github.com/mikeymckay/google-spreadsheet-javascript

You can see it in action here:

http://mikeymckay.github.com/google-spreadsheet-javascript/sample.html

破晓 2024-10-08 12:34:43

2018 年 1 月更新:当我去年回答这个问题时,我忽略了使用 JavaScript 访问 Google API 的第三种方式,那就是使用 Node.js 应用它的客户端库,所以我在下面添加了它。

现在是 2017 年 3 月,这里的大多数答案都已过时 - 接受的答案现在指的是使用较旧 API 版本的库。最新答案:您只需使用 JavaScript 即可访问大多数 Google API 。 Google 今天提供了 2 种(更正,3 种)方法来执行此操作:

  1. 正如 Dan Dascalescu 的回答中提到的,您可以使用Google Apps 脚本,Google 云中的 JavaScript 解决方案。也就是说,在 Google 服务器上运行的浏览器之外的非 Node 服务器端 JS 应用程序。
  1. 您也可以使用适用于 JavaScript 的 Google API 客户端库,用于访问最新的 Google 表格客户端的 REST API
  1. 使用 JavaScript 访问 Google API 的第三种方法是从服务器上的 Node.js 客户端库 -边。它的工作原理与使用上面描述的 JavaScript(客户端)客户端库类似,只是您将从服务器端访问相同的 API。以下是表格的Node.js 快速入门示例。您可能会发现上面基于 Python 的视频更加有用,因为它们也从服务器端访问 API。

使用REST API时,您需要管理&存储您的源代码并通过滚动您自己的授权代码来执行授权(请参阅上面的示例)。 Apps 脚本代表您处理此问题,管理数据(减少 Ape-in​​ago 在他们的答案中提到的“痛苦” ),并且您的代码存储在 Google 的服务器上。但是您的功能仅限于 App Script 提供的服务,而 REST API 为开发人员提供了更广泛的 API 访问权限。但是嘿,有选择是件好事,对吧?总之,为了回答OP原来的问题,开发人员有三种方式使用JavaScript访问Google表格,而不是零。

Jan 2018 UPDATE: When I answered this question last year, I neglected to mention a third way to access Google APIs with JavaScript, and that would be from Node.js apps using its client library, so I added it below.

It's Mar 2017, and most of the answers here are outdated -- the accepted answer now refers to a library that uses an older API version. A more current answer: you can access most Google APIs with JavaScript only. Google provides 2 (correction, 3) ways to do this today:

  1. As mentioned in the answer by Dan Dascalescu, you can use Google Apps Script, the JavaScript-in-Google's-cloud solution. That is, non-Node server-side JS apps outside the browser that run on Google servers.
  1. You can also use the Google APIs Client Library for JavaScript to access the latest Google Sheets REST API on the client side.
  1. The 3rd way to access Google APIs with JavaScript is from the Node.js client library on the server-side. It works similarly to using the JavaScript (client) client library described just above, only you'll be accessing the same API from the server-side. Here's the Node.js Quickstart example for Sheets. You may find the Python-based videos above to be even more useful as they too access the API from the server-side.

When using the REST API, you need to manage & store your source code as well as perform authorization by rolling your own auth code (see samples above). Apps Script handles this on your behalf, managing the data (reducing the "pain" as mentioned by Ape-inago in their answer), and your code is stored on Google's servers. But your functionality is restricted to what services App Script provides whereas the REST API gives developers much broader access to the API. But hey, it's good to have choices, right? In summary, to answer the OP original question, instead of zero, developers have three ways of accessing Google Sheets using JavaScript.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文