クイックスタート¶
This guide assumes you have xlwings already installed. If that's not the case, head over to インストール.
1. Jupyter NotebookからExcelをインタラクティブに操作¶
もし、pandas DataFrameをJupyter Notebookから入出力したいだけであれば、 view
および load
関数を使用してください。 Jupyter Notebooksとの連携 をご覧ください。
2. Scripting: PythonからExcelを自動化/インタラクティブに操作¶
Establish a connection with a workbook:
>>> 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インスタンスが同じファイルを開いている場合、どちらなのかをappインスタンスに指定する必要があります。appインスタンスのキー(PID)は xw.apps.keys()
で取得できます:
>>> xw.apps[10559].books['FileName.xlsx']
sheetオブジェクトをインスタンス化:
>>> sheet = wb.sheets['Sheet1']
rangeの値の読み込み/書き込みが簡単にできます:
>>> sheet['A1'].value = 'Foo 1'
>>> sheet['A1'].value
'Foo 1'
多くの 便利な機能 を使えます。例えば、Rangeを拡張できます:
>>> 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 arraysやPandas DataFramesを含む、大半の主要なデータ型を、ExcelからPythonとPythonからExcelの双方向に変換できます:
>>> 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. Macros: ExcelからPythonを呼び出す¶
アドインの Run
ボタン(v0.16の新機能)をクリックするか、VBA上で RunPython
関数を使えば、Python関数を呼び出せます:
Run
ボタンは、ワークブックと同じ名前のPythonモジュールにある main
関数を実行します。このアプローチの非常に優れた点は、ワークブックのマクロを有効にしなくても良いことで、 xlsx
形式でのワークブックの保存が可能となります。
モジュール内の任意の場所に配置した任意の名前のPython関数を呼び出すには、RunPython
を使用します:
Sub HelloWorld()
RunPython "import hello; hello.world()"
End Sub
注釈
デフォルトでは、 RunPython
は、Excelファイルを hello.py
と同じディレクトリーに同じ名前で保存する必要がありますが、 これらは変更することができます: Pythonファイルが別のフォルダーにある場合には、設定の PYTHONPATH
にそのフォルダーを追加してください。ファイル名が異なる場合には、 RunPython
コマンドを修正してください。
呼び出し元のExcelブックの参照には、 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!'
これを実行するには、xlwingsアドインをインストールするか、ワークブックをスタンドアローン モードでセットアップする必要があります。WindowsのコマンドプロンプトまたはMacのターミナルから、xlwingsのコマンドライン クライアントを使用すれば、最も簡単に全てをセットアップできます: xlwings quickstart myproject
。
アドインについての詳細は、 アドインおよび設定 をご覧ください。
4. UDFs: ユーザー定義関数 (Windowsのみ)¶
UDFをPythonで書いてみましょう。簡単にできます:
import xlwings as xw
@xw.func
def hello(name):
return f'Hello {name}'
Converters can be used with UDFs by using type hints. Again a Pandas DataFrame example:
import xlwings as xw
import pandas as pd
@xw.func
def correl2(df: pd.DataFrame):
# df arrives as DataFrame
return df.corr()
Type hints have been supported since v0.32.0. Previously, you would need to use a decorator (which continues to work):
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アドインにあるimportボタンをクリックすれば、この関数をExcelに取り込めます。 ユーザー定義関数 (UDFs) でステップ-バイ-ステップで説明しています。