How to Use Python in Excel (=PY Function Guide)

Here’s how to use Python in Excel: select a cell, go to Formulas > Insert Python (or type =PY(), write your Python code, and press Ctrl+Enter. Use xl() to pull worksheet data into your code:

df = xl("Sales[#All]", headers=True)
df.groupby("Region")["Revenue"].sum()

I don’t have Excel’s cloud Python in my test setup, so the Excel steps follow Microsoft’s support docs as of October 2026. The Command Prompt screenshots run the same pandas code locally with Python 3.12.5, pandas 3.0.6 and openpyxl 3.1.5.

I’ll cover who has the feature, turning it on, referencing cells with xl(), output types, charts, its limits, and how to work with Excel files from regular Python instead.

What is Python in Excel?

It’s a Microsoft 365 feature that lets you type Python into a cell. The code runs in Microsoft’s cloud, not on your PC, with a curated set of Anaconda libraries such as pandas, Matplotlib and seaborn. You don’t need Python installed locally.

Microsoft Support introduction page for Python in Excel explaining that Python runs in the Microsoft cloud with Anaconda libraries
Microsoft’s own introduction page. You need an internet connection, since the code runs in the cloud.

Who can use Python in Excel?

Subscription / platformStatus (per Microsoft, Oct 2026)
Business and Enterprise, Excel for WindowsAvailable on the Current Channel (Version 2408 or later)
Business and Enterprise, Excel on the webAvailable
Business and Enterprise, Excel for MacAvailable on the Current Channel (16.96 or later)
Family and PersonalPreview on Windows (Current Channel) and the web
EducationPreview through the Microsoft 365 Insider Program
Excel for iPad, iPhone, AndroidNot available; Python cells show an error when recalculated

Standard compute is included with qualifying plans. Faster premium compute and manual calculation modes need Microsoft’s paid Python in Excel add-on license.

How to turn on Python in Excel

  1. Open a workbook in Excel for Microsoft 365.
  2. Select a cell, then choose Formulas > Insert Python. You can also type =PY and pick PY from the AutoComplete list.
  3. The cell shows a PY icon. Type your Python code; Enter adds a new line.
  4. Press Ctrl+Enter to run the code and return the result to the cell.

Press Ctrl+Shift+U to expand the formula bar for multi-line code. Microsoft also has a larger code editor with IntelliSense if you’re writing more than a few lines.

How do you reference Excel cells in Python?

The xl() function connects your code to the grid. While editing a Python cell, you can click a range to insert it, or type it yourself:

xl("A1")                              # one cell
xl("B1:C4")                           # a range
xl("Sales[#All]", headers=True)       # a whole Excel table as a DataFrame

df = xl("Sales[#All]", headers=True)
df.groupby("Region")["Revenue"].agg(["sum", "mean"])

Ranges with headers come back as pandas DataFrames, so everything you know about pandas applies. Here’s that same summary run locally on the sample data:

import pandas as pd

# the same data you'd have in an Excel table called Sales
df = pd.DataFrame({
    "Region": ["West", "West", "East", "East", "South", "South"],
    "Month": ["Jan", "Feb", "Jan", "Feb", "Jan", "Feb"],
    "Revenue": [5400.00, 6075.00, 4410.00, 4950.00, 6435.00, 6795.00],
})

summary = df.groupby("Region")["Revenue"].agg(["sum", "mean"]).round(2)
print(summary)
print(f"\nGrowth Jan -> Feb: {df[df.Month == 'Feb'].Revenue.sum() / df[df.Month == 'Jan'].Revenue.sum() - 1:.1%}")

Output:

            sum    mean
Region                 
East     9360.0  4680.0
South   13230.0  6615.0
West    11475.0  5737.5

Growth Jan -> Feb: 9.7%
Command Prompt output of a pandas groupby revenue summary by US region, the same code you would run in a Python in Excel cell
Developing in a local editor first is a handy way to test longer Python in Excel formulas.

Python object vs Excel value output

Each Python cell returns either a Python object (a card icon you can expand) or an Excel value spilled into the grid. Switch with the Python output menu in the formula bar or the right-click menu.

Keep DataFrames as Python objects when another Python cell will reuse them. Convert to Excel values when you want normal Excel charts, formulas or conditional formatting on the result.

Python in Excel charts, calculation order and limits

Matplotlib and seaborn plots appear as images in the cell. You can open the card to see them larger or place them over the grid.

Python cells calculate in row-major order, across row 1 from column A, then row 2, and so on. Define a variable in an earlier cell than the one that uses it.

  • No local files or web requests: pandas.read_csv and read_excel don’t work. Bring data in through the worksheet or Power Query.
  • Only the libraries Microsoft provides through Anaconda are available; you can’t pip install your own.
  • An internet connection is required, and some features need the paid add-on for faster compute.

Using Python with Excel files without Microsoft 365

If you don’t have Python in Excel, regular Python can still read, write and format .xlsx files. pandas handles the data, and openpyxl handles formatting and formulas. Install both with python -m pip install pandas openpyxl.

import pandas as pd

df = pd.DataFrame({
    "Store": ["Austin", "Denver", "Boston", "Tampa"],
    "Q3 Sales": [12500.50, 9800.25, 14300.00, 7600.00],
    "Q4 Sales": [13900.00, 10250.75, 15120.40, 8015.10],
})
df["Growth"] = (df["Q4 Sales"] / df["Q3 Sales"] - 1).round(4)

with pd.ExcelWriter("store_report.xlsx", engine="openpyxl") as writer:
    df.to_excel(writer, sheet_name="Sales", index=False)
    df.describe().round(2).to_excel(writer, sheet_name="Stats")

print("sheets:", pd.ExcelFile("store_report.xlsx").sheet_names)
print(pd.read_excel("store_report.xlsx", sheet_name="Sales"))

Output:

sheets: ['Sales', 'Stats']
    Store  Q3 Sales  Q4 Sales  Growth
0  Austin  12500.50  13900.00  0.1120
1  Denver   9800.25  10250.75  0.0460
2  Boston  14300.00  15120.40  0.0574
3   Tampa   7600.00   8015.10  0.0546
Command Prompt output of pandas writing a two-sheet Excel workbook of US store sales with openpyxl and reading it back
Two sheets written with ExcelWriter, then read back to confirm the data.

openpyxl can then add formulas and number formats that show up when you open the file in Excel:

from openpyxl import load_workbook
from openpyxl.styles import Font

wb = load_workbook("store_report.xlsx")
ws = wb["Sales"]

ws["F1"] = "Q4 Total"
ws["F1"].font = Font(bold=True)
ws["F2"] = "=SUM(C2:C5)"                     # a real Excel formula, calculated when Excel opens it
for row in range(2, 6):
    ws[f"B{row}"].number_format = '"$"#,##0.00'
    ws[f"C{row}"].number_format = '"$"#,##0.00'
    ws[f"D{row}"].number_format = "0.0%"
wb.save("store_report.xlsx")

ws = load_workbook("store_report.xlsx")["Sales"]
print(ws["F2"].value, "|", ws["B2"].number_format, "|", ws.max_row, "rows")

Output:

=SUM(C2:C5) | "$"#,##0.00 | 5 rows
Command Prompt output of openpyxl adding a SUM formula and dollar and percent number formats to an Excel sheet
openpyxl stores the formula text; Excel calculates =SUM(C2:C5) when it opens the workbook.

For more, see writing a pandas DataFrame to Excel and reading an Excel file in Python.

Data guides that pair well with Python in Excel:

Frequently asked questions

How do I use Python in Excel?

Select a cell, choose Formulas > Insert Python or type =PY(, write your code, and press Ctrl+Enter. Use xl() to reference cells and tables.

Do I need to install Python to use Python in Excel?

No. The code runs in Microsoft’s cloud with Anaconda’s libraries, so a local Python install isn’t used.

Is Python in Excel free?

It’s included with qualifying Microsoft 365 Business and Enterprise plans at standard compute speed. Premium compute needs a paid add-on, and Family and Personal access is in preview.

Why can’t I see Insert Python in Excel?

Your plan, update channel or platform may not support it yet. iPad, iPhone and Android versions of Excel don’t have it.

Can Python in Excel read CSV files or websites?

No. For security, it can’t read local files or the internet. Load data with Power Query or paste it into the sheet first.

Where can I check the latest availability?

Microsoft keeps it current on the Python in Excel availability page.