以编程方式更新 Google 电子表格

发布于 2024-08-13 10:25:50 字数 508 浏览 3 评论 0 原文

我有一个预先存在的 Google 电子表格。我每个月都会更新此文档。我在电子表格中有一个模板工作集,我想克隆然后更新。

我更喜欢克隆工作表而不是从头开始创建它,因为它有一些非常复杂的公式。

我在这里使用 Google 电子表格的 Python api:

http:// /code.google.com/apis/spreadsheets/data/1.0/developers_guide_python.html

有人知道如何克隆和复制现有文档中的工作表吗?

编辑

我似乎让一位读者感到困惑。我没有 Excel 电子表格。我只有一个包含模板工作表的 Google 电子表格。

我想克隆此工作表,重命名它,然后以编程方式编辑它。

I've got a pre-existing Google spreadsheet. Each month I update this document. I've got a template workseet in the spreadseet that I'd like to clone and then update.

I'd prefer to clone the worksheet rather than create it from scratch as it has some pretty complex formulas.

I'm using the Python api for the Google spreadsheets here:

http://code.google.com/apis/spreadsheets/data/1.0/developers_guide_python.html

Does anyone know how to clone and copy a worksheet in a pre-existing document?

Edit

I seemed to have confused one reader. I don't have an excel spreadsheet. I only have a Google spreadsheet that has a template worksheet.

I'd like to clone this worksheet, rename it and then edit it programatically.

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

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

发布评论

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

评论(6

前事休说 2024-08-20 10:25:50
  1. 复制文档中的说明克隆模板工作表
  2. 按照 克隆文档中的工作表列表并迭代到所需的电子表格。
  3. 使用单元格 Feed 在您的电子表格,然后更新值。
  1. Clone your template worksheet using the instructions on Copying Documents
  2. Access the list of worksheets within the cloned document and iterate through to the required spreadsheet.
  3. Use the cell feed to get the appropriate cell in your spreadsheet, then update the values.
香橙ぽ 2024-08-20 10:25:50

哇!!!把卡车倒回来。有一种更简单的方法

在过去的几周里我一直在研究这个问题,因为我计划对我的月度报告做同样的事情。我还没有充实实际的代码,但我会在取得进展时添加它。

在 Google 文档中,有太多与使用文档相关的 API 和类似术语,以至于事情可能会变得有点混乱。如果您还不知道,请在您的脑海中记住这样一个事实:GAS(Google Apps 脚本)和 GAE(Google App Engine)是两个完全不同的东西。尽管它们听起来相同,但它们的含义就像 Java 与 JavaScript 一样相似。

GAS 是嵌入在 Google Docs 中的脚本(希望将来可以作为独立模块导入),用于驱动验证和动态文档等内容,但它们比大多数人怀疑的要强大得多(它们可以执行修改/更新等操作)外部文档和自动电子邮件回复)。请记住,这些需要轻量级,因为它们在谷歌的服务器上运行。如果你的脚本需要很长时间才能完成,它的执行将被提前中断(通过谷歌搜索以找到限制)。这意味着您应该仅使用普通 JS(没有像 jQuery 这样的框架)并尽可能进行性能调整。

另一方面,GAE 就像一个位于云中某处的 Web 服务器(具有可用的数据库层)。它作为一个方便的(并且已经部署的)中间件层存在,供企业/利益创建自定义应用程序来完成更多繁重的工作。不幸的是,外部电子表格的 API 太有限,无法单独完成我们正在做的工作,因此它不是一个选项。

使用 Google Apps 脚本和基于时间的触发器实现自动化

这种方法应该有效,但需要稍微有点黑客的方法。

打开包含报告表的工作簿。点击【工具】-> [脚本编辑器...]。一旦进入[触发器] - > [当前脚本的触发器...]。

如果您没有任何触发器,请添加一个。然后,在“事件”下拉菜单下选择“时间驱动”。

欢迎来到服务器端事件处理程序的世界。基于云的文档的一项巧妙功能是能够直接在文档中触发 cron 作业。无需外部中间件。

如果您现在还没有注意到,则不会触发“月计时器”。这就是它变得棘手的地方。为了解决缺少此功能的问题,需要我们每天触发触发器并使用一些 JavaScript 将当前日期与前一天的日期相匹配。

[代码将在此处]

首先,是附加到时间触发事件处理程序的函数。该代码块只是简单地解析日期,将其与前一个日期进行比较,并将该值存储在隐藏表(我们用作持久层)中以供第二天的比较。如果满足新月份条件,则运行下一个代码块。

[代码将位于此处]

您的显然与我的有点不同,但基本概念是:

  • 加载 SpreadSheet 对象(不要与 Sheet 对象混淆)
  • 找到模板 Sheet 对象
  • 克隆模板 Sheet 并为其指定适当的日期范围-based name

在我的项目中,我的下一步将是从月份中提取数据以生成堆积线图,以向上级报告当前状态。

注意:由于文档的多用户协作性质,事件必须在服务器端触发。这给我们带来了一个大问题。由于如果代码错误,事件代码会在其他地方运行,因此我们不会从浏览器获得任何反馈。唯一的解决方案是在触发器上设置通知,以便在脚本出现故障时立即向您发送电子邮件

更新:在研究这个问题时,我发现了另一个很酷的技术。如果我能设法让它正常工作而不出现任何错误,我可能会尝试使用 Google 日历上标记的日期来调用触发器。

Whoa!!! Back the truck up. There's a much simpler approach

I have been researching this a bit over the past few weeks because I'm planning to do the same thing for my monthly reports. I don't have the actual code fleshed out yet but I'll add it as I make progress.

In Google Docs there are so many API's and similar terms related to working with docs that things can get a little confusing. If you don't already know, establish in your head the fact that GAS (Google Apps Scripting) and GAE (Google App Engine) are two completely different things. Even though they sound the same thing they're about as similar as Java is to JavaScript.

GAS are the scrips embedded in Google Docs (which will hopefully be importable as stand alone modules in the future) that drive things like validation and dynamic documents but they're a lot more powerful than most suspect (they can do things like modify/update external documents and auto-email responses). Keep in mind that these need to be lightweight because they're run on google's servers. If your script takes to long to finish up it's execution will get cut off prematurely (google around to find the limits). That means you should use vanilla JS only (no frameworks like jQuery) and performance tweaks wherever possible.

GAE, on the other hand, is like a web server (with an available database layer) that lives somewhere in the cloud. It exists as a convenient (and already deployed) middleware layer for businesses/interests to create custom apps to do more heavy lifting. Unfortunately, the external Spreadsheet's API is too limited to accomplish what we're working on by itself so it's a non-option.

Automation using Google Apps Scripting and time-based triggers

This approach should work but requires a slightly hackish approach.

Open up the workbook containing your report sheets. Click on [Tools] -> [Script editor...]. Once there goto [Triggers] -> [Current script's triggers...].

If you don't have any triggers present, add one. Then, under the 'Events' dropdown menu select 'Time-driven'.

Welcome to the world of server-side event handlers. One of the neat features that you get with cloud-based documents is the ability to trigger cron jobs directly within your document. No external middleware necessary.

If you haven't noticed by now there's no trigger for 'Month timer'. This is where it gets hacky. To work around the lack of this feature it's going to require that we fire the trigger on a daily basis and use some JavaScript to match the current date with the previous day's date.

[code will go here]

First, comes the function that gets attached to the time trigger event handler. This block of code just simply parses the date, compares it to the previous date, and stores the value in a hidden sheet (that we use as out persistence layer) for the next day's comparison. If the new-month condition is met then the next block of code runs.

[code will go here]

Yours will obviously differ from mine a bit but the basic concept is:

  • Load the SpreadSheet object (not to be confused with a Sheet object)
  • Locate the template Sheet object
  • Clone the template Sheet giving it an appropriate date-range-based name

In mine, my next step will be to extract data from the month to generate a stacked line graph to report the current status to my higher-ups.

Note: Because of the multi-user collaboration nature of docs, events have to be fired server-side. This creates a big problem for us. Because the event code runs elsewhere if the code errors, we don't get any feedback from our browser. The only solution to this is to setup a notification on the trigger to immediately email you when the script faults.

Update: While researching this, I found another cool technique. If I can manage to get this working without any bugs I might try to invoke the trigger using a date marked on Google Calendar.

江挽川 2024-08-20 10:25:50

首先,我以前从未使用过 Python - 但我会告诉你我是如何在 C++ 中做到这一点的。

我使用 cURL 向 Google 文档 API。文件的二进制数据被返回,我将其写入文件。现在我有了 XLS 文件,然后我使用了可以读取 XLS 文件的 C/C++ 库来操作下载的文件。我使用的 API 支持多种选项;您可以做任何在 Excel 中可以做的事情。修改后我再次将其上传到Google Docs。

First of all, I've never worked with Python before - but I'll tell you how I did this in C++.

I've used cURL to make a GET request to the google documents API. The binary data of the file was returned and I wrote that to a file. Now I had the XLS file and then I used a C/C++ library that could read XLS files to manipulate the downloaded file. The API that I used supported a variety of options; you could do anything that you could do in Excel. After modification I uploaded it again to Google Docs.

太阳哥哥 2024-08-20 10:25:50

这真的很复杂。我知道你可以使用 Python 的 API 来编辑电子表格,Google 倾向于在他们的许多 Web 服务上提供这种功能,这一切都是通过以某种方式发送由 XML 组成的 HTTP post 请求来完成的,我希望你知道这一点,我不知道t。

根据,您至少可以添加工作表,从其他工作表读取行并将行写入工作表。如果必须的话,您可以一次复制一行,但是为每一行发送一个额外的 POST 请求似乎是一个可怕的主意。

编辑:

我对此了解得越来越多,但距离解决您最初的问题还有很长的路要走。此REST 原则概述概述了之间进行交互的基本风格网络上的程序。谷歌似乎正在虔诚地追随它。

这一切都发生在 HTTP 协议中,而今天之前我对此一无所知。在此HTTP 规范中阐明了基本游戏。它并不像看起来那么枯燥,也许我只是一个巨大的极客,但我发现它是一本鼓舞人心的读物。与美国宪法没有什么不同。

因此,由于您想要“克隆”文档,因此您将使用特定工作表的 GET 请求,然后将该工作表作为 POST 的有效负载发送回来。

越来越近了:)

This is really complicated. I understand that you can edit your spreadsheets with Python using their API, Google tends to offer that ability on many of their web services and it's all done by sending HTTP post requests made of XML somehow, I hope you know that part, I don't.

According to this you can at least add worksheets, read rows from other worksheets and write rows to worksheets. if you must, you could copy it one row at a time, however sending an additional POST request for each row seems like a horrible idea.

Edit:

I'm learning more and more about this, but still a long way off from solving your original problem. This overview of REST principles goes over the basic style of interaction that goes on between programs on the web. Google seems to be following it religiously.

It all takes place within the HTTP protocol, something I knew nothing about before today. In this HTTP specification the basic game is spelled out. Its not as dry as it looks, and maybe I'm just a huge geek, but I find it an inspiring read. Not unlike The Constitution of The United States.

So since you want to "clone" a document, your going to be using a GET request for a particular worksheet, and then sending that worksheet back as the payload of POST.

Getting closer :)

凯凯我们等你回来 2024-08-20 10:25:50

难道您不能将电子表格导出为 xls,然后将其作为具有(略有)不同名称的新文档上传,并在 XML 元数据中指定新名称吗?

下载和创建/上传文档部分位于 http://code.google.com/apis /documents/overview.html 应该是有益的。

我无法立即在 Python API 文档中看到任何导入/导出功能,但发送一些 http 请求也不错。

Couldn't you could export your spreadsheet as a xls and then upload it as a new doc with a (slightly) different name, specifying the new name in the XML metadata?

The Download and Create/upload Document sections at http://code.google.com/apis/documents/overview.html should be beneficial.

I can't immediately see any import/export functionality in the Python API docs, but sending a few http requests isn't so bad.

埋葬我深情 2024-08-20 10:25:50

(2017 年 2 月) 用当前术语重新表述问题:如何复制 Google 表格模板,然后以编程方式修改它(副本)? 简短回答:使用当前术语要容易得多Google API,特别是 Google Drive v3 APIGoogle Sheets v4 API,您可以使用 Google API 客户端库

最新的 Sheets API 提供了旧版本中不可用的功能,即让开发人员能够以编程方式访问工作表,就像使用用户界面 (UI) 一样,即创建冻结行、单元格格式、调整行/列大小、添加数据透视表、 。

您可以猜到,Sheets API 主要用于以编程方式访问电子表格操作和数据 功能如上所述,但要执行文件访问(例如复制模板工作表),请使用 Google Drive API

使用 Drive API 复制文件 (Sheet) 的伪代码 (Python)(假设我们首先使用模板名称搜索最近修改的文件,因此使用 orderBy 并选择第一个结果 [0] 如下):

TMPLFILE = 'my Sheets template'
tmpl = DRIVE.files().list(q="name='%s'" % TMPLFILE).execute().get('files')[0]
NEW_SHEET = {'name': 'Sheets data, Feb 2017'}
SHEET_ID = DRIVE.files().copy(body=NEW_SHEET, fileId=tmpl['id']).execute().get('id')

从 SQL 数据库 (SQLite) 读取值并将其写入上面创建的新工作表(从单元格“A1”作为“左上角”开始)的伪代码,就像用户输入来自 UI 的值(以便可以应用公式等):

cxn = sqlite3.connect('db.sqlite')
cur = cxn.cursor()
rows = cur.execute('SELECT * FROM data').fetchall()
cxn.close()
DATA = {'values': rows}
SHEETS.spreadsheets().values().update(spreadsheetId=SHEET_ID,
    range='A1', body=DATA, valueInputOption='USER_ENTERED').execute()

如果您对现代 Google API 相对较新,我有一个(有点过时但)用户友好的 介绍视频。之后还有 2 个视频可能也有用,其中一个演示了如何使用 Drive API。这些是此播放列表中的视频 2、3 和 4。视频 23 & 25 是另一对具有 Drive 和 Sheets API 的产品。

所有较新的视频都可以在此播放列表中找到,您可以在其中找到另一对包含Sheets API 加上上面“模板复制”代码的重复,但复制幻灯片模板,然后使用 Slides API 进行修改)而不是(视频 2)。

正如另一个答案中提到的,如果您愿意,还可以使用 Google Apps 脚本 执行类似的操作尽管 Apps 脚本当前使用较旧的 API,但该环境与使用 REST API 的比较。此外,还有一些突出的错误可能会使其更具挑战性(特别是 这个)。

(Feb 2017) Rephrasing question with current terminology: How do you copy a Google Sheet template, then modify it (the copy) programmatically? Short answer: it's much easier with current Google APIs, specifically the Google Drive v3 API and the Google Sheets v4 API, and you can do it with any language supported by the Google APIs Client Libraries.

The latest Sheets API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (UI), i.e., create frozen rows, cell formatting, resize rows/columns, add pivot tables, cell validation, create charts, etc.

As you can guess, the Sheets API is primarily for programmatically accessing spreadsheet operations & functionality as described above, but to perform file-level access such as copying a template Sheet, use the Google Drive API instead.

Pseudocode (Python) to copy a file (Sheet) using the Drive API (assuming we first search for the most recently modified file with the template name, hence the orderBy and selection of the first result [0] below):

TMPLFILE = 'my Sheets template'
tmpl = DRIVE.files().list(q="name='%s'" % TMPLFILE).execute().get('files')[0]
NEW_SHEET = {'name': 'Sheets data, Feb 2017'}
SHEET_ID = DRIVE.files().copy(body=NEW_SHEET, fileId=tmpl['id']).execute().get('id')

Pseudocode to read values from a SQL database (SQLite) and write them to the new Sheet created above (starting from cell 'A1' as "upper-left") as if a user entered the values from the UI (so formulae can be applied, etc.):

cxn = sqlite3.connect('db.sqlite')
cur = cxn.cursor()
rows = cur.execute('SELECT * FROM data').fetchall()
cxn.close()
DATA = {'values': rows}
SHEETS.spreadsheets().values().update(spreadsheetId=SHEET_ID,
    range='A1', body=DATA, valueInputOption='USER_ENTERED').execute()

If you're relatively new to modern Google APIs, I have a (somewhat dated but) user-friendly intro video for you. There are 2 videos after that maybe useful too, including one that demonstrates using the Drive API. Those are videos 2, 3, and 4 in this playlist. Videos 23 & 25 are another pair featuring the Drive and Sheets APIs.

All newer videos can be found in this playlist where you'll find another pair of videos featuring the Sheets API plus a reprise of the "template copying" code above but copying a Slides template which is then modified with the Slides API) instead (video 2).

As mentioned in another answer, you can also use Google Apps Script to do something similar if you prefer that environment vs. using REST APIs, although Apps Script currently uses older APIs. Also there are few outstanding bugs that may make it a bit more challenging (specifically this one and this one).

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