DEV Community

Felix Nullbyte
Felix Nullbyte

Posted on

win32com vs xlwings vs openpyxl for Scheduled Reports

A recurring Excel report is easy to prototype and hard to own. The prototype runs on your laptop; the production version has to start from a scheduler, survive a locked file, produce the same numbers every morning, and be debuggable by whoever is on call. The library you choose determines most of that.

openpyxl, xlwings, and win32com are often listed as three ways to do the same job, but they operate at different layers. This comparison of win32com vs xlwings vs openpyxl separates them by what they actually control, covers the requirements that force you to drive Excel itself, prices the operational cost, and finishes with a decision table and a migration path for an existing report.

Table of Contents

The one-line distinction

openpyxl edits the file. xlwings and win32com drive an installed copy of Excel.

openpyxl reads and writes the Office Open XML package directly. No Excel process starts, no desktop session is needed, and the same code runs on a Linux build agent and a developer's laptop. The catch is that openpyxl only understands the file format, not Excel's behavior.

Windows COM is a binary component standard that lets one program call another. win32com is Python's binding to that standard, so a Python script can ask Excel to open a workbook, recalculate it, refresh a pivot cache, or export a PDF. xlwings is a friendlier wrapper over the same interface on Windows, using AppleScript on macOS, and it adds DataFrame conversion, a context manager, and Python-shaped objects.

The practical consequence is simple. If the job can be done by changing cells, formatting, and structure, a file-level library is enough. If the answer must come from Excel's calculation engine, its pivot and query refresh, or its print engine, something has to drive Excel.

What each library actually controls

openpyxl xlwings win32com
What it controls The .xlsx file Excel through COM or AppleScript Excel through COM
Excel installed No Yes Yes
Linux Yes No, for classic automation No
Formula engine No Yes Yes
Abstraction level File API Pythonic wrapper Raw COM object model
Typical best fit Generating and editing files Excel features with lifecycle help Exact object model and VBA ports

openpyxl: the file

openpyxl is a pure file library. It handles bulk reads and writes efficiently compared with cell-by-cell COM calls, works on any platform, and is straightforward to test because a test only needs a temporary workbook. It can write a formula such as =SUM(B2:B100) into a cell, but openpyxl's formula documentation states that it never evaluates a formula. When you open the same file with data_only=True, openpyxl returns the value Excel stored the last time it read the sheet, not a freshly computed result. The openpyxl load_workbook documentation describes that flag as returning the value stored the last time Excel read the sheet, which is the key limitation for unattended work.

The same file-level view means openpyxl does not preserve every Excel object on a round trip. Pivot table caches, slicers, some chart types, ActiveX controls, and Power Query connections can be lost. If the deliverable depends on those objects, a file-only edit is risky.

xlwings: the application with guardrails

xlwings is a Python library for calling Python from Excel and Excel from Python. It can drive a workbook through an API that feels close to VBA, supports NumPy arrays and pandas DataFrames, and runs on Windows and macOS. For automation, it normally starts an Excel instance, opens the workbook, and performs the requested operations.

The useful part for a production job is not the syntax but the lifecycle help. The App object is designed to be used as a context manager so the Excel process is cleaned up, and its .api property exposes the underlying pywin32 object when you need a corner of Excel that xlwings has not wrapped. That means you can use the higher-level wrapper for most of the job and still reach the raw COM model for one stubborn property.

win32com: the application directly

win32com gives you Excel's documented object model with almost nothing in between. You create or attach to an Excel.Application, open a workbook, and call the same methods the VBA editor would call. Early binding through EnsureDispatch generates a cached type library, which provides named constants and better error messages; late binding through Dispatch resolves everything at runtime. For a walkthrough of the raw interface, see this guide to Python win32com, early binding, late binding, and COM automation basics, which also covers the Excel and Outlook examples that translate closely from recorded VBA.

Raw COM is the right choice when you are porting an existing macro almost line for line or when you need a property that xlwings does not expose. The trade is that you own the application lifetime, dialog suppression, thread initialization, and process cleanup yourself.

Four requirements that force an application driver

A useful breakdown of when xlwings is worth its cost instead of openpyxl identifies four jobs: recalculated formulas, workbook objects that openpyxl drops, a workbook that is already open on someone's screen, and output that only Excel can produce. It also names the price: Excel installed, Windows or macOS only, and a cross-process call for every operation. Those four jobs are a good checklist for deciding whether you need an application driver at all.

Recalculated formula results

If the report contains formulas that you wrote, the cheapest fix is usually to compute the result in Python and write a plain value. The formula is then a presentation detail, and the scheduled job stays portable and testable.

The calculation engine becomes necessary when the formulas belong to a model somebody else maintains. A finance model with linked assumptions, depreciation schedules, and circular references is not something you want to reimplement in pandas. In that case, openpyxl can change the inputs but cannot tell you what the model now produces. Loading with data_only=True on a freshly generated file can return None, because no Excel process has saved a calculated value yet. Driving Excel with book.app.calculate() and then saving gives you Excel's own result.

Preserved pivot caches and workbook objects

A pivot table is more than a range of cells. It has a cache, field definitions, and layout state. openpyxl may not round-trip all of that, and a rebuilt sheet can look right while losing the refreshable structure the report depends on. The same applies to slicers, some chart types, ActiveX controls, and Power Query connections.

Through COM, you can refresh the workbook's external data ranges and PivotTable reports with Workbook.RefreshAll. Microsoft's Workbook.RefreshAll documentation notes that objects with BackgroundQuery set to True refresh in the background, so a save immediately after the call may capture the previous run's numbers. It also warns that a failing Power Query table does not raise a run-time error from RefreshAll; other connections still refresh, and the affected table keeps its old data. For an unattended report, that silent failure is worth an explicit check.

A workbook that is already open

openpyxl reads and writes files on disk. It cannot see unsaved changes in an open workbook, and it may fail with a permission error when Excel holds a lock. COM can attach to the running Excel instance and edit the live workbook, including changes that are not on disk yet.

That capability is valuable for interactive tools, but it is a warning sign for a scheduled report. A scheduled job should not depend on a person leaving a workbook open. If the requirement is truly "edit what the user is looking at," the job is interactive automation, not an unattended report, and it needs a different operational plan.

Native PDF and print output

If the PDF has to paginate exactly as Excel prints it, with the company's page setup, headers, footers, and print area, the PDF has to come from Excel's print path. openpyxl can set page layout properties, but it does not render a PDF. xlwings exposes Book.to_pdf, which exports the whole workbook or a selected set of sheets to PDF using Excel. The Book.to_pdf documentation lists the path, sheet selection, and quality options.

On Linux, the alternative is LibreOffice in headless mode. The LibreOffice file-conversion documentation shows the soffice --convert-to pdf form and the Calc PDF filter name. It is a legitimate route for a server when close-enough pagination is acceptable, but it is not Excel's engine and should be tested against the real templates rather than assumed to match.

The operational bill: platform, latency, licensing, and tests

The requirement that decides most scheduled jobs is not a feature. It is where the job runs.

Classic xlwings requires an installation of Excel and therefore works only on Windows and macOS, as the xlwings installation documentation states. The same is true of win32com: COM is a Windows technology, and a Linux container has no Excel application to drive. xlwings PRO's file reader can read workbooks on Linux without Excel, but that is a read mode, not a replacement for Excel's calculation and print engines.

Microsoft is blunt about the server case. Its support article on server-side Automation of Office says Microsoft does not recommend or support automating Office from an unattended, non-interactive client, including a Windows service. It also points out that code started by Task Scheduler under the SYSTEM account runs in the same kind of environment. Office assumes an interactive desktop and a user profile; when a modal dialog appears on a non-interactive desktop, nobody can dismiss it and the job hangs instead of failing. The same article notes that licensing guidelines prevent using Office on a server to serve client requests unless those clients have licensed copies.

Latency is the second cost. With COM, the expensive part is crossing the process boundary, not the number of bytes. Writing ten thousand cells one at a time makes ten thousand cross-process calls; assigning the same block as one range write makes one. A loop over cells is the usual reason an xlwings or win32com job is slow, and batching the write is the usual fix. Even then, a file-level library will beat an application driver for bulk data.

Testability is the third. A unit test for an openpyxl function can create a temporary file and assert on cells in milliseconds. A test for an xlwings function needs Excel, a desktop session, and several seconds of startup, which rules it out of most continuous integration pipelines. The practical answer is to keep the Excel-dependent surface tiny and test the business logic separately.

Decision table for a scheduled report

Start with the requirement, not the library.

Report requirement Best fit Why Watch out
Generate an .xlsx from a database or API openpyxl No Excel needed; fast and testable Rebuild pivot tables and charts rather than assuming a round trip preserves them
Write formulas that a person will open later openpyxl Excel normally calculates on open Do not read the formula result with data_only=True before Excel has saved a cache
Deliver a file containing recalculated results xlwings or win32com Excel's calculation engine produces the values Needs Excel and a Windows or macOS host
Preserve pivot caches, slicers, or Power Query xlwings or win32com The objects stay inside Excel Refresh must finish before you save; check for silent query failures
Edit a workbook already open on screen xlwings or win32com COM can attach to the live workbook Not suitable for an unattended scheduler
Pixel-accurate PDF or Excel print output xlwings or win32com on Windows Uses Excel's print engine Excel licensing and desktop session required
PDF on a headless Linux server openpyxl plus LibreOffice No Excel or desktop needed Pagination may differ; test against real templates
Run an existing VBA macro win32com, or xlwings via .api The VBA object model is available directly Macro security and trusted locations still apply
Unit-testable business logic in CI openpyxl, with COM behind an adapter Pure functions run anywhere Keep the adapter small and smoke-test it on Windows
Scheduled task on Linux, Docker, or a service account openpyxl COM is unsupported in that environment Do not schedule Excel automation under a non-interactive account

The server case deserves its own sentence. If the report runs in a Linux container or under a service account, openpyxl is the only one of these three that belongs in the job. Build the workbook there. If a PDF is required and close-enough pagination is acceptable, convert it with LibreOffice. If genuine Excel recalculation is non-negotiable, move that step to a Windows host with a logged-in interactive session, keep it as a separate adapter, and monitor for orphan EXCEL.EXE processes. Do not put COM in the service-account path and hope.

Migrating an existing report job

The safest migration is not a rewrite. It is a separation: business logic in plain Python, Excel confined to a thin adapter at the edge.

from pathlib import Path
import openpyxl
import xlwings as xw


def build_workbook(rows: list[tuple[str, float]], path: Path) -> None:
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Summary"
    ws.append(["Region", "Revenue"])
    for region, revenue in rows:
        ws.append([region, revenue])
    ws["D2"] = "=SUM(B2:B100)"
    wb.save(path)


def finalize_with_excel(path: Path, pdf_path: Path) -> None:
    with xw.App(visible=False) as app:
        app.display_alerts = False
        book = app.books.open(path)
        try:
            book.app.calculate()
            book.save()
            book.to_pdf(pdf_path)
        finally:
            book.close()


def finalize_with_libreoffice(path: Path, outdir: Path) -> Path:
    import subprocess

    subprocess.run(
        [
            "soffice",
            "--headless",
            "--convert-to",
            "pdf",
            "--outdir",
            str(outdir),
            str(path),
        ],
        check=True,
    )
    return outdir / f"{path.stem}.pdf"
Enter fullscreen mode Exit fullscreen mode

build_workbook is testable anywhere and holds the part that changes when the report requirements change. finalize_with_excel is the small part that needs Excel, and it uses a context manager and display_alerts = False so an exception does not leave a hidden dialog or an orphan process behind. finalize_with_libreoffice is the portable fallback for PDF only.

A migration can follow these steps:

  1. Capture the current output. Run the existing job, save the workbook and PDF, and record key cell values, sheet names, row counts, and page counts. That is your regression baseline.
  2. Move data preparation out of COM. Replace cell-by-cell reads with queries or bulk range reads, and turn the calculations into plain functions that accept and return data.
  3. Define a narrow adapter. Give it one job, such as "recalculate, save, and export this file," so the rest of the code does not know whether Excel is involved.
  4. Build with openpyxl first. Generate the workbook file, write the values, and apply the formatting. Only call the adapter for the operations that genuinely need Excel.
  5. Harden the Excel step. Suppress alerts, disable screen updating, close the book in a finally block, quit the app through the context manager, and log the process ID so orphan processes are easy to find.
  6. Pin versions. Record the Python, openpyxl, and xlwings versions, and the Excel build on the automation host. xlwings currently requires at least Python 3.11, so an old runtime is a migration blocker rather than a detail.
  7. Cut over behind a flag. Run the new job in parallel for a few cycles, compare outputs, then remove the old path. Keep the baseline until the new report has survived a month-end run.

If the existing job is raw win32com, the same split applies, but you will also want to standardize binding. EnsureDispatch gives you cached constants and clearer errors; Dispatch avoids the type cache but resolves everything at runtime. Either way, translate the recorded VBA method names rather than guessing at the object model, and keep the COM session as short as possible.

Conclusion

openpyxl is the default for generating and editing report files. It is efficient for bulk work, testable, runs on any platform, and does not require Excel. Its limits are real: no formula engine, no native PDF rendering, and no guarantee that complex workbook objects survive a round trip.

xlwings is the sensible default when you need Excel's behavior but want lifecycle help, DataFrame conversion, and an escape hatch to raw COM. win32com is the better fit when you are porting VBA, need an unwrapped corner of the object model, or want one fewer layer. Both of them require an installed, licensed Excel on Windows or macOS.

For a scheduled report, the deployment target makes the decision. A Linux container or a service account rules out COM, no matter how attractive the feature list looks. Build the file with openpyxl, convert with LibreOffice if a PDF is needed, and reserve Excel automation for a Windows host with an interactive session. Where COM is unavoidable, keep the business logic in ordinary functions and confine Excel to a small, monitored adapter so the next migration is a change of a dozen lines rather than a rewrite.

Top comments (1)

Collapse
 
chenwinny profile image
chenwinny •

Great comparison — the file vs. application distinction is the part most guides skip. One pitfall I'd add from running scheduled reports: dates. openpyxl writes datetime values as Excel serial numbers, and if you don't set the cell's number format explicitly, the recipient opens the file to a column of numbers like 45981 instead of dates. The reverse is just as confusing: reading a date column back gives you a datetime only when the cell is actually typed as a date — a text column that looks like dates stays text, so a downstream sort or filter silently breaks. My rule now is to always set number formats when writing dates and to validate the column type after reading, before any calculation. Thanks for the migration checklist, especially the parallel-run step — that's the one that saves you when the new job looks right but rounds differently.