01=PY セルで xl() を使い、表を DataFrame で受け取る確認済

=PY セルに xl("表名[#All]", headers=True) と書くと、表全体が見出し付きの pandas DataFrame として渡る。2 次元の範囲は既定で DataFrame になるので、そのまま groupby で集計できる。

考え方と手順
  1. 台帳を Excel の表にして、表名を付ける(例: RequestLedger)
  2. セルに =PY と入力して PY を選び、Python のエディターに切り替える
  3. xl("RequestLedger[#All]", headers=True) で表全体を読む。[#All] は表全体、headers=True は先頭行を見出しとして扱う指定である
  4. 読んだ DataFrame を groupby で集計し、最後の式の値をセルに返す
  5. セル範囲だけを読むときは xl("B1:C4") のように番地で書く
PythonMicrosoft のクラウドで動く
# Python in Excel cell (=PY). Table name: RequestLedger
df = xl("RequestLedger[#All]", headers=True)

# Count requests and total findings by document type
summary = (
    df.groupby("種別")
      .agg(件数=("依頼ID", "count"), 指摘件数計=("指摘件数", "sum"))
      .sort_values("件数", ascending=False)
)
summary
実行結果(2026-09-12)
         件数  指摘件数計
種別                
社内通知     11     42
プレスリリース  10     34
Web 記事    7     42
契約書       6     27
提案書       6     26
rows: 40 total: 40
Copilot に書かせる指示の例

Python in Excel のセル用に、表 RequestLedger を xl() で見出し付きで読み、種別ごとの件数と指摘件数の合計を件数の多い順に並べるコードを書いて。ファイルの読み込みやネットワークは使わないこと。

注意

xl() が読むのはセルの値で、ブックの数式・グラフ・ピボットテーブルは読めない。表全体を読むには [#All] を付ける。計算は Microsoft のクラウドで行うので、インターネット接続が要る。集計の合計が元の表の行数と合うかを人が確かめる。

利用条件
Python in Excel は Excel for Microsoft 365 の Windows・Mac・Web で使える(iPad・iPhone・Android は不可)。対象のサブスクリプションでは standard compute と自動計算。premium compute と手動・部分計算は Python in Excel アドオンライセンスが要る。
必要なもの
pandas 3.0.5
試験
xl() を見本データで代用して手元で実行(2026-09-12、Python 3.12.10 (venv) / Windows 11、pandas 3.0.5)
出典
Microsoft Support「Get started with Python in Excel」
Microsoft Support「Python in Excel DataFrames」
確認日
2026-09-13(第 1 版)
出典の該当箇所
For a table with headers named MyTable, use xl("MyTable[#All]", headers=True). The [#All] specifier ensures that the entire table is analyzed in the Python formula, and headers=True ensures that the table headers are processed correctly.
Python in Excel uses a DataFrame as the default object for two-dimensional ranges.
The Python code doesn't have access to other properties in the workbook, such as formulas, charts, PivotTables, macros, or VBA code.

02集計を Excel の値で返すときは、グループの列を索引から列に戻す確認済

=PY の結果は Python オブジェクトか Excel の値で返せる。DataFrame を Excel の値で返すと、索引の列は条件を満たすときだけ出る。groupby に as_index=False を付けると、グループの名前が普通の列として並ぶ。

考え方と手順
  1. 後の Python セルで使い回す中間の結果は、Python オブジェクトで返す(セルにカードのアイコンが出る)
  2. グラフや条件付き書式に使う最終の結果は、数式バーの Python 出力メニューで Excel の値に切り替える
  3. groupby(..., as_index=False) で、グループの名前を索引ではなく列に置く
  4. 出力先の範囲に値があると #SPILL! になるので、結果が広がる右と下のセルを空けておく
PythonMicrosoft のクラウドで動く
# Python in Excel cell (=PY), output type: Excel value
df = xl("RequestLedger[#All]", headers=True)

by_dept = (
    df.groupby("依頼部署", as_index=False)   # department stays a column
      .agg(件数=("依頼ID", "count"), 平均指摘=("指摘件数", "mean"))
      .round({"平均指摘": 1})
)
by_dept
実行結果(2026-09-12)
依頼部署  件数  平均指摘
 人事部  11   4.1
 営業部  10   4.6
 広報部  19   4.2
index is numeric: True
Copilot に書かせる指示の例

Python in Excel のセルで、表 RequestLedger を依頼部署ごとに集計し、件数と指摘件数の平均(小数第 1 位まで)を返すコードを書いて。Excel の値で出力するので、部署名は索引ではなく列に置くこと。

注意

Excel の値に直した結果は、最も近い Excel の型に置き換わる。後の Python の計算で使うなら Python オブジェクトのままにする。describe() の結果のように索引が数値でない DataFrame は、索引の列も出力されるので、列の並びを確かめる。

利用条件
Python in Excel は Excel for Microsoft 365 の Windows・Mac・Web で使える。出力の種類の切り替えは右クリックのメニューからもできる。
必要なもの
pandas 3.0.5
試験
xl() を見本データで代用して手元で実行(2026-09-12、Python 3.12.10 (venv) / Windows 11、pandas 3.0.5)
出典
Microsoft Support「Python in Excel DataFrames」
pandas「pandas.DataFrame.groupby」
確認日
2026-09-13(第 1 版)
出典の該当箇所
When the output type of a DataFrame is set to Excel values, the DataFrame only outputs the index column if one of the following conditions is met. If values of the index column are not numeric (like the result of describe() or group_by()). If the index column name has been set.
Return object with group labels as the index.
If you plan to reuse the result in a future Python calculation, it's recommended to return the result as a Python object.

03Python セルの計算順(行優先)に合わせて変数を置く確認済

ワークシートの Python セルは、行ごとに A 列から右へ、次に下の行へと計算される。シートの並び順にも従う。変数を作るセルは、それを使うセルより上か、同じ行の左に置く。

考え方と手順
  1. 表を読み込んで型を整えるセル(df を作る)をシートの左上に置き、Python オブジェクトで返す
  2. df を使う集計のセルは、その下の行か右に置く
  3. 複数のシートで分析するときは、データと変数を持つセルを前のシートに置く
  4. import 文や設定は最初のシートにまとめる
  5. 計算を止めて作業したいときは部分計算か手動計算にし、F9 で再計算する
PythonMicrosoft のクラウドで動く
# --- Cell A1 (=PY, Python object): load and clean once ---
df = xl("RequestLedger[#All]", headers=True)
df["依頼日"] = pd.to_datetime(df["依頼日"])
df["完了日"] = pd.to_datetime(df["完了日"])
df

# --- Cell A2 (=PY, Excel value): calculated after A1 (row-major order) ---
done = df[df["状態"] == "完了"].copy()
done["日数"] = (done["完了日"] - done["依頼日"]).dt.days
done.groupby("種別")["日数"].median()
実行結果(2026-09-12)
           日数
種別           
Web 記事    6.0
プレスリリース   3.0
契約書       7.5
提案書       5.0
社内通知     12.0
completed rows: 14
Copilot に書かせる指示の例

Python in Excel で 2 つのセルに分けたコードを書いて。1 つ目のセルで表 RequestLedger を読み、依頼日と完了日を日付型にする。2 つ目のセルで状態が完了の行について、種別ごとの日数の中央値を出す。どちらのセルを上に置くかも書くこと。

注意

下の行や前のシートにある変数を参照すると、定義より先に計算されるため失敗する。依存する値が変わると、Python の数式はすべて順に再計算される。手動・部分計算にしたときは、再計算するまで古い値が残るので、報告の前に再計算する。

利用条件
自動計算は対象の Microsoft 365 サブスクリプションで使える。手動・部分計算モードは Python in Excel アドオンライセンスが要る。
必要なもの
pandas 3.0.5
試験
xl() を見本データで代用して手元で実行(2026-09-12、Python 3.12.10 (venv) / Windows 11、pandas 3.0.5)
出典
Microsoft Support「Get started with Python in Excel」
Microsoft Support「Python in Excel availability」
確認日
2026-09-13(第 1 版)
出典の該当箇所
But in a Python in Excel worksheet, Python cells calculate in row-major order. The cell calculations run across a row (from column A to column XFD), and then across each following row down the worksheet.
The row-major calculation order also applies across worksheets within a workbook and is based on the order of the worksheets within the workbook.
To ensure that your libraries are imported before your Python formulas run, enter your import statements and any settings on the first worksheet in your workbook.

04使えるライブラリをセルで確かめ、import を最初にまとめる確認済

Python in Excel で使えるのは、Anaconda が提供する厳選されたライブラリである。手元の Python に入れたパッケージは反映されない。追加のライブラリはセルで import して使い、あるかどうかは importlib で確かめられる。

考え方と手順
  1. 既定で読み込まれるのは Matplotlib・NumPy・pandas・seaborn・statsmodels で、np や pd の別名ですぐ使える
  2. 使いたいライブラリの import 名を、Python セルで importlib.util.find_spec に渡して確かめる
  3. import の書き方はライブラリごとに違う(例: beautifulsoup4 は from bs4 import BeautifulSoup)
  4. 使う import 文は[Formulas]→[Initialization]の作業ウィンドウか、最初のシートにまとめる
PythonMicrosoft のクラウドで動く
# Python in Excel cell (=PY): which optional libraries does this runtime provide?
import importlib.util

wanted = ["bs4", "sklearn", "scipy", "networkx"]
found = {name: importlib.util.find_spec(name) is not None for name in wanted}
pd.Series(found, name="available")
実行結果(2026-09-12)
bs4         False
sklearn      True
scipy        True
networkx     True
Name: available
Copilot に書かせる指示の例

Python in Excel のセルで、bs4・sklearn・scipy・networkx が使えるかを importlib で調べ、名前と True/False を並べた Series を返すコードを書いて。インストールは試みないこと。

注意

ライブラリはネットワークにも手元のファイルにも触れない。初期化の作業ウィンドウは、ライブラリのページでは読み取り専用、初期化設定のページでは import を追加・編集できると書かれており、記述が食い違う。自分の画面で確かめる。初期化の変更は Copilot in Excel with Python の動きにも影響する。

利用条件
Python in Excel は Excel for Microsoft 365 の Windows・Mac・Web で使える。ライブラリと Python の版は Microsoft が定期的に更新し、既存のブックは作成時の環境で計算される(新しい環境があると更新を促される)。
必要なもの
pandas 3.0.5
試験
xl() を見本データで代用して手元で実行(2026-09-12、Python 3.12.10 (venv) / Windows 11、pandas 3.0.5)
出典
Microsoft Support「Open-source libraries and Python in Excel」
Microsoft Support「Introduction to Python in Excel」
Microsoft Support「Python in Excel initialization settings」
確認日
2026-09-13(第 1 版)
出典の該当箇所
In addition to the core libraries, you can import additional libraries available through Anaconda.
If you have a local version of Python installed on your computer, any customizations you've made to that Python installation won't be reflected in Python in Excel calculations.
This task pane is currently read-only and shows the initialization settings for your Python in Excel runtime.
Changing initialization settings affects how Python behaves in your workbook. Any changes can impact both Python in Excel and Copilot in Excel with Python.

05外部データは Power Query で取り込み、xl() でクエリ名を読む確認済

Python in Excel のコードは、ネットワークにも手元のファイルにも触れない。pandas.read_csv や read_excel で外のファイルを読むコードは動かない。Power Query でクエリを作り、xl("クエリ名") で DataFrame として受け取る。

考え方と手順
  1. [Data]→[Get Data]で CSV などの取り込み元を選ぶ
  2. [Load To...]で[Only Create Connection]を選ぶと、シートに展開せずにクエリだけができる
  3. =PY セルで xl("クエリ名") と書き、DataFrame として受け取る
  4. Excel on the web では Power Query でこの取り込みができないので、デスクトップの Excel でクエリを作る
PythonMicrosoft のクラウドで動く
# Python in Excel cell (=PY)
# "RequestsQuery" is a Power Query connection (Load To... > Only Create Connection).
# pd.read_csv("C:/...") would not work here: the code has no file or network access.
df = xl("RequestsQuery")

open_items = df[df["状態"] != "完了"]
open_items.groupby("担当者")["依頼ID"].count().rename("未完了件数")
実行結果(2026-09-12)
担当者
担当A    10
担当B     7
担当C     3
担当D     6
Name: 未完了件数
Copilot に書かせる指示の例

Python in Excel のセル用に、Power Query の接続 RequestsQuery を xl() で読み、状態が完了でない依頼を担当者ごとに数えるコードを書いて。pandas.read_csv などでファイルを直接読むコードは使わないこと。

注意

Power Query が Python in Excel に外部データを渡す唯一の方法である。ネット上や信頼できない場所から開いたブックは、保護ビューで Python の数式が実行されない。クエリの取り込み元が更新されたかは、Python の結果ではなくクエリの側で確かめる。

利用条件
Power Query で取り込んだデータを Python in Excel で使うのは、デスクトップの Excel(Windows・Mac)。Excel on the web では使えない。
必要なもの
pandas 3.0.5
試験
xl() を見本データで代用して手元で実行(2026-09-12、Python 3.12.10 (venv) / Windows 11、pandas 3.0.5)
出典
Microsoft Support「Use Power Query to import data for Python in Excel」
Microsoft Support「Data security and Python in Excel」
Microsoft Support「Get started with Python in Excel」
確認日
2026-09-13(第 1 版)
出典の該当箇所
Power Query is the only way to import external data for use with Python in Excel.
The Python code doesn't have access to your computer, devices, or account. The Python code doesn't have network access.
To protect your security, common external data functions in Python, such as pandas.read_csv and pandas.read_excel, aren't compatible with Python in Excel.
Importing external data with Power Query to use with Python in Excel is not available for Excel on the web.

06FORMULATEXT で Python セルのコードを一覧にして点検する確認済

Python セルの中身は =PY(python_code, return_type) という関数で、FORMULATEXT で文字列として取り出せる。点検用のシートにコードを並べると、レビューや引き継ぎのときに読み比べやすい。

考え方と手順
  1. 点検用のシートを作り、A 列に Python セルの場所を書く
  2. B 列に =FORMULATEXT(参照) を入れ、=PY(...) の文字列を取り出す
  3. 最後の引数が 1 なら Python オブジェクト、0 なら Excel の値で返すセルである
  4. PY 関数は数式バーに直接入力できず、他の関数と組み合わせられないので、点検のシートは読むだけに使う
Excel
Review sheet (row 2; fill down for more cells)
A2: Sheet1!C1
B2: =FORMULATEXT(Sheet1!C1)
C2: =IF(RIGHT(B2,3)=",1)","Python object",IF(RIGHT(B2,3)=",0)","Excel value","check"))

Example of the text returned in B2 (syntax from the PY function reference):
=PY("xl(""Table1[#All]"", headers=True)",1)
Copilot に書かせる指示の例

Sheet1 の C1 から C5 にある Python セルのコードを、点検用のシートに FORMULATEXT で並べ、各セルの戻り値が Python オブジェクトか Excel の値かを表示する数式を書いて。

注意

C 列の判定は、FORMULATEXT の結果が公式の構文例と同じく ,1) か ,0) で終わる前提である。自分のブックで取り出した文字列を見て確かめる。コードの意味は人が読んで判断する。FORMULATEXT は Python の結果の正しさを示さない。

利用条件
Python in Excel は Excel for Microsoft 365 の Windows・Mac・Web で使える。PY 関数はアドインから書き込み・読み取りもできる。
試験
実行の対象外(設定・HTTP・数式)(2026-09-12)
出典
Microsoft Support「PY function」
確認日
2026-09-13(第 1 版)
出典の該当箇所
The PY function syntax is primarily used by add-ins to directly insert or read Python formulas. It can also be seen when using the FORMULATEXT function on a cell containing a Python formula.
The PY function cannot be used with any other Excel functions. If used with other functions, a formula cannot be entered.
0 indicates Excel value. 1 indicates Python object.

07openpyxl の read_only と data_only で台帳を読む確認済

手元の Python で xlsx を読むとき、load_workbook に read_only=True を付けると、大きなファイルを少ないメモリで読める。data_only=True は数式ではなく、Excel が最後に保存した値を返す。openpyxl は数式を計算しないので、Excel で保存していない数式の値は None になる。

考え方と手順
  1. 大きな台帳は load_workbook(..., read_only=True) で開き、iter_rows(values_only=True) で行を順に読む
  2. read_only で開いたブックは、読み終えたら close() で閉じる
  3. 数式の文字列が欲しいときは既定のまま、Excel が保存した値が欲しいときは data_only=True で開く
  4. data_only で None が返るセルは、Excel で開いて保存し直すまで値が無い
Python手元で動く
from openpyxl import load_workbook

SRC = "samples/request_ledger.xlsx"        # input, not modified
AFTER = "samples/excel_ledger_after.xlsx"  # has a formula sheet saved by openpyxl

# 1) read_only: stream rows with low memory, then close explicitly
wb = load_workbook(SRC, read_only=True)
ws = wb.worksheets[0]
header = next(ws.iter_rows(max_row=1, values_only=True))
status_col = header.index("状態")
open_count = sum(1 for r in ws.iter_rows(min_row=2, values_only=True) if r[status_col] != "完了")
wb.close()
print("open requests:", open_count)

# 2) formula text vs stored value
formula = load_workbook(AFTER)["集計"]["B2"].value
stored = load_workbook(AFTER, data_only=True)["集計"]["B2"].value
print("formula:", formula)
print("stored value:", stored)  # None: openpyxl wrote the formula but never calculated it
実行結果(2026-09-12)
open requests: 26
formula: =COUNTIF(依頼台帳!G:G,A2)
stored value: None
Copilot に書かせる指示の例

openpyxl で request_ledger.xlsx を read_only で開き、状態が完了でない行を数えて close() するコードと、別のブックの数式セルを data_only あり・なしで読み比べるコードを書いて。ファイルは書き換えないこと。

注意

openpyxl は Excel の図形などをすべては読まないので、同じ名前で保存し直すと図形が失われる。元のファイルは上書きしない。read_only のブックではセルの型が通常と異なり、書き込みはできない。値の確認は Excel で再計算した後のファイルで行う。

利用条件
openpyxl(試験した版は code.tested に記録)。Python in Excel ではなく手元の Python で動かす。
必要なもの
openpyxl 3.1.5
試験
手元で実行して確認(2026-09-12、Python 3.12.10 (venv) / Windows 11、openpyxl 3.1.5)
出典
openpyxl「Tutorial」
openpyxl「Optimised Modes」
確認日
2026-09-13(第 1 版)
出典の該当箇所
data_only controls whether cells with formulae have either the formula (default) or the value stored the last time Excel read the sheet.
The workbook must be explicitly closed with the close() method.
shapes will be lost from existing files if they are opened and saved with the same name.

08pandas で台帳を集計し、新しいブックに複数シートで書き出す確認済

手元の Python では、pandas の read_excel で台帳を読み、groupby で集計し、ExcelWriter で新しいブックに複数のシートとして書き出せる。同じ名前のファイルがあると上書きされるので、出力先は新しい名前にする。

考え方と手順
  1. read_excel(sheet_name=0) で最初のシートを DataFrame として読む
  2. 依頼日から月の列を作り、groupby で種別×状態と月別の件数を出す
  3. with pd.ExcelWriter(出力先) の中で、to_excel をシートの名前を変えて呼ぶ
  4. 書き出した後に read_excel(sheet_name=None) で読み直し、シート名と合計の件数を確かめる
Python手元で動く
import pandas as pd

SRC = "samples/request_ledger.xlsx"
OUT = "out_ledger_summary.xlsx"   # new file; the source is never overwritten

df = pd.read_excel(SRC, sheet_name=0)
df["依頼月"] = pd.to_datetime(df["依頼日"]).dt.strftime("%Y-%m")

by_type = df.groupby(["種別", "状態"])["依頼ID"].count().unstack(fill_value=0)
by_month = (df.groupby("依頼月", as_index=False)
              .agg(件数=("依頼ID", "count"), 指摘件数計=("指摘件数", "sum")))

with pd.ExcelWriter(OUT, engine="openpyxl") as writer:
    by_type.to_excel(writer, sheet_name="種別x状態")
    by_month.to_excel(writer, sheet_name="月別", index=False)

# Read back and reconcile with the source
check = pd.read_excel(OUT, sheet_name=None)
print("sheets:", list(check))
print(by_month.to_string(index=False))
print("rows in source:", len(df), "| total in 月別:", int(check["月別"]["件数"].sum()))
実行結果(2026-09-12)
sheets: ['種別x状態', '月別']
    依頼月  件数  指摘件数計
2026-07  21     95
2026-08  19     76
rows in source: 40 | total in 月別: 40
Copilot に書かせる指示の例

pandas で request_ledger.xlsx を読み、種別×状態の件数表と、月別の件数・指摘件数の合計を、新しいブック out_ledger_summary.xlsx の別々のシートに書き出すコードを書いて。元のファイルは上書きせず、最後に読み直して合計の件数を表示すること。

注意

ExcelWriter は既定で書き込みモードなので、既にあるファイル名を渡すと上書きする。元の台帳と同じ名前にしない。書き出した表は値だけで、Excel の数式やピボットテーブルにはならない。合計の件数が元の行数と合うかを確かめる。

利用条件
pandas と openpyxl(試験した版は code.tested に記録)。手元の Python で動かす。Python in Excel では pandas.read_excel で外のファイルを読めない。
必要なもの
pandas 3.0.5, openpyxl 3.1.5
試験
手元で実行して確認(2026-09-12、Python 3.12.10 (venv) / Windows 11、pandas 3.0.5、openpyxl 3.1.5)
出典
pandas「pandas.DataFrame.to_excel」
pandas「pandas.read_excel」
確認日
2026-09-13(第 1 版)
出典の該当箇所
To write to multiple sheets it is necessary to create an ExcelWriter object with a target file name, and specify a sheet in the file to write to.
Note that creating an ExcelWriter object with a file name that already exists will overwrite the existing file because the default mode is write.
Read an Excel file into a DataFrame.