使用 pyExcelerator/xlrd 进行数据透视
如何使用 pyExcelerator / xlrd 等 python 库创建带有数据透视表的工作表(在 Excel 工作簿中)?我需要生成一份每日报告,其中有一个数据透视表来汇总其他工作表上的数据。一种选择是使用一个空白模板,我可以复制该模板并用数据填充该模板。在这种情况下,有没有办法从代码中刷新数据透视表?还有其他建议吗?
How can I go about creating a worksheet (within an excel workbook) with a pivot table using python libs like pyExcelerator / xlrd? I need to generate a daily report that has a pivot table to summarize data on other sheets. One option would be to have a blank template that I copy and populate with the data. In this case, is there a way to refresh the pivot from code? Any other suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请澄清(通过编辑您的问题)“sheet”是否是“spreadsheet”的缩写并表示整个 XLS 文件,或者它是否是“worksheet”的缩写(“工作簿”的一个组件)。
如果“数据透视表”指的是 Excel 机制,那么您就不走运了,因为它只能由 Excel 创建。但是,如果您指的是使用 Python 和适当的库自行创建的“交叉表”,则可以使用 xlrd、xlwt 和 xlutils 来完成此操作。
xlrd 你似乎知道。
xlwt 是 pyExcelerator 的一个分支,修复了错误并进行了多项增强。 pyExcelerator 似乎没有得到维护。
xlutils 是一个实用程序模块包。 xlutils.copy 可用于从 xlrd Book 对象创建 xlwt Workbook 对象,以便您可以对 xlwt Workbook 进行更改并将其保存到文件中。
这是有关这三个包的更多信息的一站式商店,以及教程和链接到 google-group/mailing-list,您可以使用它来获取帮助。
Please clarify (by editing your question) whether "sheet" is an abbreviation of "spreadsheet" and means a whole XLS file, or whether it's an abbreviation of "worksheet", a component of a "workbook".
If by "pivot table" you mean the Excel mechanism, you are out of luck, because that can be created only by Excel. However if you mean a "cross-tab" that you create your self using Python and an appropriate library, you can do this using the trio of xlrd, xlwt and xlutils.
xlrd you appear to know about.
xlwt is a fork of pyExcelerator with bugs fixed and several enhancements. pyExcelerator appears not to be maintained.
xlutils is a package of utility modules. xlutils.copy can be used to make an xlwt Workbook object from an xlrd Book object, so that you can make changes to the xlwt Workbook and save it to a file.
Here is your one-stop-shop for more info on the three packages, together with a tutorial, and links to a google-group/mailing-list which you can use to get help.
尝试看看这个:Python:刷新工作表中的数据透视表
如果你弄清楚如何创建数据透视表,然后您可以使用我的代码来刷新它们
Try to have a look at this: Python: Refresh PivotTables in worksheet
If you figure out howto create the pivot tables then you can use my code to refresh them
我不相信您可以使用 xlwt 以编程方式添加数据透视表。
但是您的第二种方法(填充预先配置的工作簿)似乎是合理的。
您可以使用模板工作簿中的 VBA 宏刷新数据透视表。要自动执行此操作,请创建一个
WorkBook_Open
事件处理程序。刷新数据透视表的 VBA 代码是:
I do not believe you can programatically add a pivot table using
xlwt
.But your second approach (populating a pre-configured workbook) seems reasonable.
You can refresh the pivot table using a VBA macro in the template workbook. To do this automatically, create a
WorkBook_Open
event handler.The VBA code to refresh a pivot table is: