快速入门¶
本指南假设你已经安装了 xlwings。如果没有,请前往安装.
1. 在 Jupyter 笔记本中与 Excel 交互¶
如果你只是想在 Jupyter 笔记本中导入和导出 pandas DataFrame,可以使用view
和load
函数,详见Jupyter 笔记本:与 Excel 交互.
2. 脚本:通过 Python 自动化/与 Excel 交互¶
建立与工作簿的连接:
>>> import xlwings as xw
>>> wb = xw.Book() # this will open a new workbook
>>> wb = xw.Book('FileName.xlsx') # connect to a file that is open or in the current working directory
>>> wb = xw.Book(r'C:\path\to\file.xlsx') # on Windows: use raw strings to escape backslashes
如果你在两个 Excel 实例中打开了同一个文件,则需要完全限定它并包含应用程序实例。你可以通过xw.apps.keys()
:
>>> xw.apps[10559].books['FileName.xlsx']
实例化一个工作表对象:
>>> sheet = wb.sheets['Sheet1']
读取/写入范围中的值非常简单:
>>> sheet['A1'].value = 'Foo 1'
>>> sheet['A1'].value
'Foo 1'
有许多方便的功能可用,例如范围扩展:
>>> sheet['A1'].value = [['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
>>> sheet['A1'].expand().value
[['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
强大的转换器处理大多数感兴趣的数据类型,包括双向的 Numpy 数组和 Pandas DataFrame:
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
>>> sheet['A1'].value = df
>>> sheet['A1'].options(pd.DataFrame, expand='table').value
a b
0.0 1.0 2.0
1.0 3.0 4.0
Matplotlib图形可以在 Excel 中作为图片显示:
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> plt.plot([1, 2, 3, 4, 5])
[<matplotlib.lines.Line2D at 0x1071706a0>]
>>> sheet.pictures.add(fig, name='MyPlot', update=True)
<Picture 'MyPlot' in <Sheet [Workbook4]Sheet1>>
3. 宏:从 Excel 调用 Python¶
你可以通过点击Run
按钮(自 v0.16 起新增)或在 VBA 中使用RunPython
函数来调用 Python 函数:
The Run
按钮期望名为main
的函数位于与你的工作簿同名的 Python 模块中。这种方法的优点是你不需要将工作簿启用宏,你可以将其保存为xlsx
.
如果你想调用任何 Python 函数,无论它位于哪个模块或具有什么名称,请使用RunPython
:
Sub HelloWorld()
RunPython "import hello; hello.world()"
End Sub
注意
默认情况下,RunPython
期望hello.py
位于与 Excel 文件相同的目录下且名称相同,但你可以更改这两者:如果你的 Python 文件位于不同的文件夹中,请将该文件夹添加到PYTHONPATH
配置中的。如果文件有不同的名称,请相应地更改RunPython
命令。
使用xw.Book.caller()
:
# hello.py
import numpy as np
import xlwings as xw
def world():
wb = xw.Book.caller()
wb.sheets[0]['A1'].value = 'Hello World!'
引用调用的 Excel 工作簿。要使此功能运行,你需要安装 xlwings 插件或将工作簿设置为独立模式。最简单的设置方法是使用 Windows 上的命令提示符或 Mac 上的终端中的 xlwings 命令行客户端:xlwings quickstart myproject
.
关于插件的详细信息,请参阅插件与设置.
4. UDFs:用户定义函数(仅限 Windows)¶
编写 Python 中的 UDF 非常简单:
import xlwings as xw
@xw.func
def hello(name):
return f'Hello {name}'
通过使用类型提示,转换器可以与 UDF 一起使用。再次以 Pandas DataFrame 为例:
import xlwings as xw
import pandas as pd
@xw.func
def correl2(df: pd.DataFrame):
# df arrives as DataFrame
return df.corr()
类型提示自 v0.32.0 起已受支持。在此之前,你需要使用装饰器(它继续有效):
import xlwings as xw
import pandas as pd
@xw.func
@xw.arg("df", pd.DataFrame)
def correl2(df):
# df arrives as DataFrame
return df.corr()
通过点击 xlwings 插件的导入按钮将此函数导入 Excel:逐步教程,请参见用户定义函数(UDFs).