Comparison
Getting Started With Python Excel AutomationDeep dive

Python in Excel vs openpyxl and xlwings

Python in Excel runs code inside a cell; openpyxl and pandas write files from a script; xlwings drives the Excel application. Compare where each runs, what it can reach and which jobs it suits.

"Python and Excel" now means three quite different things. Python in Excel puts Python inside a workbook: a =PY formula runs in a Microsoft cloud container and returns its result to a cell. openpyxl, xlsxwriter and pandas run Python outside Excel: a script reads and writes .xlsx files without Excel installed at all. xlwings (and pywin32 underneath it on Windows) runs Python alongside Excel: a script drives the running application as if a person were clicking. They overlap less than the shared name suggests, and choosing the wrong one produces a solution that fights its tool at every step. This guide from Using Python in Excel compares them on the questions that decide real projects.

Where the code runs in each approach Python in Excel runs in a Microsoft cloud container triggered by a cell. openpyxl and pandas run in a script on any machine and work on files without Excel. xlwings runs in a script on a machine with Excel installed and controls the application. Python in Excel inside a =PY cell Microsoft cloud container data only via xl() recalculates like a formula openpyxl / pandas a script, any machine no Excel needed reads and writes files runs on a schedule xlwings a script beside Excel Windows or macOS + Excel drives the live app recalc, macros, refresh inside, outside, alongside — the rest of the differences follow

The same job, three ways

A concrete task makes the differences tangible: summarise a sales table by region and put the result in a workbook.

Python in Excel — a formula in the workbook itself, set to return Excel values:

Python
sales = xl("Sales[#All]", headers=True)
sales.groupby("Region", as_index=False)["Amount"].sum().sort_values("Amount", ascending=False)

pandas with openpyxl — a script that reads one file and writes another, on any machine:

Python
import pandas as pd

pd.DataFrame({
    "Region": ["North", "South", "North", "West"],
    "Amount": [1200.0, 950.0, 800.0, 400.0],
}).to_excel("sales.xlsx", sheet_name="Sales", index=False)

sales = pd.read_excel("sales.xlsx", sheet_name="Sales")
summary = sales.groupby("Region", as_index=False)["Amount"].sum().sort_values("Amount", ascending=False)
with pd.ExcelWriter("summary.xlsx", engine="openpyxl") as writer:
    summary.to_excel(writer, sheet_name="By region", index=False)
print(summary)

xlwings — a script that opens the workbook in Excel, writes into it and lets Excel recalculate:

Python
import pandas as pd
import xlwings as xw

with xw.App(visible=False) as app:
    book = app.books.open("sales.xlsx")
    sales = book.sheets["Sales"].range("A1").expand().options(pd.DataFrame, index=False).value
    summary = sales.groupby("Region", as_index=False)["Amount"].sum()
    sheet = book.sheets.add("By region")
    sheet.range("A1").options(index=False).value = summary
    book.save("summary_live.xlsx")

The pandas logic is identical in all three. What differs is everything around it: who runs the code, when, on what machine, and what happens to the result afterwards.

Question 1 — Who triggers the work, and when?

Python in Excel runs when the workbook calculates: when someone opens it, edits an input, refreshes a query or presses F9. That is ideal for analysis a person is actively doing, and useless for a report that must exist at 06:00 before anyone is awake. Nobody is there to open the workbook.

A pandas or openpyxl script runs whenever something starts it — cron, Windows Task Scheduler, a CI job, a web request — which is exactly what scheduled reporting needs; see Scheduling Python Excel Scripts with Cron. xlwings can be scheduled too, but it needs an interactive desktop with Excel installed, which makes unattended runs fragile.

Suitability for unattended scheduled runs File-level scripts with pandas and openpyxl are well suited to unattended scheduled runs. xlwings is possible but fragile because it needs a desktop session with Excel. Python in Excel only runs when a person opens or recalculates the workbook. fit for a report that must exist before anyone logs in pandas / openpyxl built for it xlwings needs a desktop Python in Excel needs a person scheduling is the clearest dividing line

Question 2 — What data can the code reach?

This is the second hard boundary. Python in Excel sees only what xl() can reference: cells, tables, names and Power Query results in the same workbook. It cannot open files, call APIs or query databases directly, and each calculation's data is capped at 100 MB. That sandbox is deliberate — it is why an organisation can allow it at all — and it means external data must come in through Power Query first.

Scripts reach anything the machine can: databases through SQLAlchemy, REST APIs through requests, cloud storage, other workbooks by the hundred. If the job starts with "pull yesterday's orders from the warehouse", a script is the natural fit, as in Moving Data Between Excel and Databases.

Question 3 — Which packages can you use?

Python in Excel ships a curated Anaconda-based set with pandas, NumPy, matplotlib, seaborn and statsmodels imported by default and more available to import, but nothing can be installed. Your own internal library, a niche statistics package or a newer release of something already present is not available. Scripts can use any package the environment can install, pinned to exact versions in a requirements file, which is also what makes their output reproducible six months later.

Question 4 — What does the output look like, and who can open it?

Python in Excel produces results in a live workbook: values that update when inputs change, and images of charts. Anyone who opens the file in a client without Python in Excel support sees error values instead of results, so a workbook that leaves your team usually needs its results converted to static values first.

openpyxl and xlsxwriter produce ordinary files that open anywhere — Excel on any platform, LibreOffice, Google Sheets — with native charts, conditional formats and tables that need nothing special to display. xlwings produces the same ordinary files, but because Excel itself saved them, formulas are recalculated and connections refreshed, which file-level libraries cannot do.

Capabilities of the three approaches A matrix comparing Python in Excel, openpyxl with pandas, and xlwings on scheduling, external data, installing packages, needing Excel installed, recalculating formulas and live interactive analysis. A B C D 1 capability Python in Excel openpyxl/pandas xlwings 2 unattended schedule no yes fragile 3 files, APIs, databases via Power Query yes yes 4 install any package no yes yes 5 needs Excel installed Excel 365 no yes 6 recalculate formulas yes no yes 7 live analysis in grid yes no partly no column wins every row; the job decides

Question 5 — Who maintains it?

A Python in Excel workbook keeps its code next to its data, which is a genuine advantage for an analyst who owns both: there is no separate repository, environment or deployment. It is also a maintenance risk at scale. Code spread across cells is hard to review, has no version history beyond the file itself, and cannot be unit-tested in place.

A script lives in version control, runs in CI, and can be tested with ordinary tools — the practices in Testing and Packaging Excel Automation Scripts. The cost is that someone has to own an environment. A reasonable rule: if more than one person edits the logic, or if the output feeds a decision someone will be held to, it belongs in a script.

Combining them

The approaches compose well when each does what it is good at. A scheduled pandas script can build a clean, formatted workbook every morning from the database, and analysts can then add Python in Excel formulas on top for their own exploration, without either side touching the other's work. The script can even write its data as an Excel table so that xl("Sales[#All]", headers=True) picks up every refresh, using the technique in Create an Excel Table with Python.

Python
import pandas as pd
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo

data = pd.DataFrame({"Date": pd.date_range("2026-09-01", periods=4),
                     "Region": ["North", "South", "North", "West"],
                     "Rep": ["Ana", "Cara", "Ben", "Dev"],
                     "Amount": [1200.0, 950.0, 800.0, 400.0]})
data.to_excel("analysis_base.xlsx", sheet_name="Data", index=False)

book = load_workbook("analysis_base.xlsx")
sheet = book["Data"]
table = Table(displayName="Sales", ref=f"A1:D{len(data) + 1}")
table.tableStyleInfo = TableStyleInfo(name="TableStyleMedium2", showRowStripes=True)
sheet.add_table(table)
book.save("analysis_base.xlsx")
print("wrote table Sales with", len(data), "rows")

Where xlwings fits into that picture is the narrow set of steps that need Excel itself: refreshing a Power Query connection, recalculating a model built from Excel formulas, or running a legacy macro — covered in When to Use xlwings Instead of openpyxl.

Common pitfalls

MistakeWhy it hurtsBetter choice
Building a nightly report in Python in ExcelNothing runs until someone opens the fileA scheduled pandas or openpyxl script
Using xlwings on a Linux serverThere is no Excel to driveopenpyxl or xlsxwriter
Sharing a =PY workbook with external clientsTheir Excel may show errors instead of resultsConvert results to values, or generate the file with a script
Reimplementing interactive analysis as a scriptEvery question needs a code change and a rerunPython in Excel for exploration
Calling APIs from a =PY cellThe runtime has no network accessPower Query, or a script

Performance and scale notes

Python in Excel round-trips data to the cloud and caps each calculation at 100 MB, so it suits analysis of workbook-sized data rather than bulk processing. File-level libraries scale with the machine and with techniques such as streaming writes — see Working with Large Excel Files in Python. xlwings is bounded by Excel's own speed and by the cost of crossing the process boundary, so it should move data in whole ranges rather than cell by cell.

Conclusion

Choose by where the work has to happen. Python in Excel is for interactive analysis inside a workbook by the people who use it, with data that already lives there. openpyxl, xlsxwriter and pandas are for scheduled, reproducible file generation that must run without Excel and reach external systems. xlwings is for the steps that genuinely need the Excel application — recalculation, refresh, macros. Many real setups use two of them: a script to produce the data, and in-cell Python for the questions people ask of it.

Frequently asked questions

Does Python in Excel replace xlwings? No. Python in Excel runs code inside cells in the cloud; xlwings controls Excel from a local script. xlwings can automate the application, reach local files and networks, and run on a schedule, none of which Python in Excel does.

Can Python in Excel read the files my openpyxl script writes? Not directly from disk. Open the generated workbook and reference its tables with xl(), or load it into another workbook through Power Query and reference the query.

Is Python in Excel free? It is included with eligible Microsoft 365 plans, and Microsoft offers a paid add-on for faster premium compute. Check the current plan list, because availability has widened over time. openpyxl, pandas and xlwings' open-source edition cost nothing but need a Python environment.

Which is best for a beginner? For analysis of data already in a workbook, Python in Excel has the least setup. For automating a recurring report, start with pandas and openpyxl, which teach skills that transfer to every other kind of automation.

More on python in excel

More on python in excel →