第 8 章. Excel 自动化
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
本章拉开了第四部分的序幕,该部分主要介绍 xlwings。虽然“Python in Excel”将 Excel 变成了一个 Jupyter 笔记本,但 xlwings 的目标是用 Python 取代 VBA。 因此,xlwings 允许您自动化 Excel 应用程序、运行宏并创建自定义函数。为此,xlwings 依赖于我们在第 2 章中安装的 Python 环境。因此,您可以离线工作,并使用任何您想要的第三方包。
本章将从读取和写入单元格值等基础内容开始。在了解 xlwings 如何与 pandas DataFrame、图表和图片配合使用后,我们将通过一个报表案例研究来实践这些技能。最后一节将教你如何提高脚本的性能,以及如何解决功能缺失的问题。本章要求你在 Windows 或 macOS 上运行代码示例,因为它们依赖于本地安装的 Microsoft Excel。
xlwings入门
xlwings的主要目标是作为VBA的直接替代方案,让你能够通过Python与Excel进行交互。由于Excel的网格布局非常适合展示列表、NumPy数组和pandas DataFrame等数据结构,因此xlwings的核心功能之一就是尽可能简化从Excel读取和向Excel写入数据的过程。 本节首先将介绍如何将 Excel 用作数据查看器——这在您于 Jupyter 笔记本中操作 DataFrame 时非常有用。接下来,我将带您了解 Excel 对象模型,最后您将学习如何从 Python 调用 VBA 代码。
将 Excel 用作数据查看器
如果DataFrame 包含超过十行数据,Jupyter Notebook 只会显示前五行和后五行。更好地理解数据的一种方法是绘制图表——这有助于发现异常值或其他不规则现象。不过,有时在 Excel 中滚动浏览完整数据集会更有帮助。这就是view函数的作用:
In[1]:# First, let's import the packages that we'll use in this chapterimportdatetimeasdtimportnumpyasnpimportpandasaspdimportxlwingsasxw
In[2]:# Let's create a DataFrame based on pseudorandom numbers.# We'll make it large enough that only the head and tail are displayed.rng=np.random.default_rng(seed=1234)df=pd.DataFrame(data=rng.standard_normal((100,5)),columns=[f"Sample{i}"foriinrange(1,6)],)df
Out[2]: Sample 1 Sample 2 Sample 3 Sample 4 Sample 5 0 -1.603837 0.064100 0.740891 0.152619 0.863744 1 2.913099 -1.478823 0.945473 -1.666135 0.343745 2 -0.512444 1.323759 -0.860280 0.519493 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access