Home β€Ί Curriculum β€Ί Excel & Office Automation
Updated for Python 3.12+ Β· November 2026

πŸ“— Excel & Office Automation
in Python

Automate Excel, Word and PDF work with Python: openpyxl, python-docx and pypdf, formulas vs values, merging files, safe backups, plus runnable stdlib practice.

Intermediate 8 lessonsβ‰ˆ 52 min read by Glenn Pansensoy

What this lesson is about

Almost every office runs on files that people open by hand: a monthly sales workbook, a Word letter that gets edited fifty times with different names, a stack of PDFs that someone has to merge before a meeting. These jobs are boring, repetitive and easy to get subtly wrong when a tired human does them. They are also exactly the kind of work a short Python script does well, because the rules are clear and the script never gets tired halfway through file forty.

In this lesson I want to show you how to automate that work without treating the file formats as magic. We start with what an .xlsx file really is (a zip archive of XML files), then build reports from plain rows with the standard library, and only then move to openpyxl for real workbooks, python-docx for Word and pypdf for PDFs. I think this order matters: if you understand rows, summaries and the difference between a formula and its value, the libraries become thin wrappers around ideas you already own.

A practical note about this page. The libraries openpyxl, python-docx and pypdf are not installed in the in-browser runner, so those examples are marked as run-on-your-computer. I tested them locally, and every one of them has a neighbouring runnable example that teaches the same idea with only the standard library, so you can press Run on every section and still learn something real. The last section covers backups and dry runs, which is the habit that keeps automation from damaging the files it is meant to help with.

What you will learn

  • βœ“Why an .xlsx file is a zip of XML parts and what that means for tools
  • βœ“How to build summaries and totals from rows using csv, io.StringIO and dictionaries
  • βœ“How to create, read and edit workbooks with openpyxl
  • βœ“The difference between a formula and its cached value, and why data_only surprises people
  • βœ“How to format cells and add a chart from code
  • βœ“How to merge many spreadsheets into one tidy file safely
  • βœ“How to generate Word documents and read or merge PDFs
  • βœ“How to protect real files with backups, dry runs and atomic writes

Why programmers should learn this

  • β˜…Repetitive office work is the most common first automation project, and it saves real time because the task recurs every week or month.
  • β˜…A script gives the same result every time, so totals, formats and file names stop depending on who did the work that day.
  • β˜…Reports can be rebuilt from raw data on demand, so you never maintain a hand-edited copy that drifts away from the source.
  • β˜…The same skills (rows, dictionaries, file handling) lead directly into pandas, databases and web back ends.
  • β˜…Knowing how Office files are built lets you debug strange problems, such as a formula that reads as empty or a merged file that doubled in size.

What an .xlsx file really is

When you save a workbook as .xlsx, Excel does not write a mysterious binary blob. It writes a zip archive containing several XML files: one describing the workbook and its sheet names, one per worksheet holding the cells, one for shared strings, one for styles, and so on. Word's .docx and PowerPoint's .pptx follow the same Open Packaging idea. You can rename a copy of any of them to .zip, open it, and see the parts.

This matters for two reasons. First, it explains why libraries such as openpyxl can read and write workbooks without Excel installed: they simply read and write those XML parts. Second, it explains the limits. A library edits the XML it understands, so features it does not model (some pivot tables, certain macros, exotic charts) can be dropped when you load and save. Never assume a round trip is lossless until you have tested it on a copy.

Let me prove the idea with the standard library. The block below builds a tiny zip in memory that looks like the skeleton of a workbook, lists its parts, and then parses the sheet XML to pull the text back out. It is not a complete Excel file (Excel would want more parts), but it shows exactly the mechanism real libraries rely on.

python
import io
import zipfile
import xml.etree.ElementTree as ET

sheet_xml = (
    '<worksheet><sheetData>'
    '<row r="1"><c r="A1" t="inlineStr"><is><t>Region</t></is></c>'
    '<c r="B1" t="inlineStr"><is><t>Units</t></is></c></row>'
    '<row r="2"><c r="A2" t="inlineStr"><is><t>North</t></is></c>'
    '<c r="B2"><v>120</v></c></row>'
    '</sheetData></worksheet>'
)

buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
    archive.writestr("[Content_Types].xml", "<Types/>")
    archive.writestr("xl/workbook.xml", '<workbook><sheets><sheet name="Sales"/></sheets></workbook>')
    archive.writestr("xl/worksheets/sheet1.xml", sheet_xml)

with zipfile.ZipFile(io.BytesIO(buffer.getvalue())) as archive:
    for info in archive.infolist():
        print(info.filename, "-", info.file_size, "bytes")
    root = ET.fromstring(archive.read("xl/worksheets/sheet1.xml"))

for cell in root.iter("c"):
    text = cell.findtext("is/t")
    number = cell.findtext("v")
    print(cell.get("r"), "=", text if text is not None else float(number))
Expected output
[Content_Types].xml - 8 bytes
xl/workbook.xml - 59 bytes
xl/worksheets/sheet1.xml - 252 bytes
A1 = Region
B1 = Units
A2 = North
B2 = 120.0

Line by line

  1. 1-3Import io (an in-memory file), zipfile (read and write zip archives) and ElementTree (parse XML).
  2. 5-13A hand-written worksheet. Each <c> is a cell with a reference such as A1; text uses an inline string, numbers use a <v> value element.
  3. 15-19Create an in-memory zip and write three named parts into it. The names with slashes are folder paths inside the archive, just like in a real workbook.
  4. 21-23Reopen the bytes as a zip and list every part with its uncompressed size, the same thing you would see by unzipping a real file.
  5. 24Parse the sheet part as XML so we can walk the cells.
  6. 26-30Loop over every <c> element, read the text or number inside, and print the cell reference with its value. This is, in miniature, what a spreadsheet library does when it loads a sheet.
ℹ️

Try this on your own computer: copy any .xlsx, rename the copy to .zip, and open it. Look inside xl/worksheets. Never edit and re-zip the original by hand; a malformed archive is the quickest way to corrupt a workbook.

Build a report from rows with the standard library

Before reaching for a spreadsheet library, I like to solve the data problem on its own: given rows, what totals do I need? Most reporting scripts are really three steps: read rows, group and add them up, write a result. The spreadsheet is only the container at either end, and CSV is the simplest container there is.

The example below reads sales rows from a string using io.StringIO, which behaves like a file, so the same code works with a real file opened by open(). It groups units and revenue by region using a dictionary, then writes a small summary CSV, again to an in-memory buffer so we can print it. Notice that numbers arrive from CSV as text and must be converted; forgetting that is the most common bug in this kind of script.

Once this part works, replacing the input with an Excel file or the output with a formatted workbook is a small change. Keep the calculation separate from the file reading and writing, and you can test the calculation with a few hand-written rows, which is much faster than opening Excel every time.

python
import csv
import io

raw = """region,product,units,price
North,Pen,120,2.50
South,Pen,80,2.50
North,Notebook,40,4.00
East,Pen,95,2.50
South,Notebook,60,4.00
"""

totals = {}
for row in csv.DictReader(io.StringIO(raw)):
    units = int(row["units"])
    revenue = units * float(row["price"])
    entry = totals.setdefault(row["region"], {"units": 0, "revenue": 0.0})
    entry["units"] += units
    entry["revenue"] += revenue

out = io.StringIO()
writer = csv.writer(out, lineterminator="\n")
writer.writerow(["region", "units", "revenue"])
for region in sorted(totals):
    writer.writerow([region, totals[region]["units"], f"{totals[region]['revenue']:.2f}"])
grand = sum(t["revenue"] for t in totals.values())
writer.writerow(["TOTAL", sum(t["units"] for t in totals.values()), f"{grand:.2f}"])
print(out.getvalue())
Expected output
region,units,revenue
East,95,237.50
North,160,460.00
South,140,440.00
TOTAL,395,1137.50

Line by line

  1. 1-2csv parses and writes comma-separated text; io.StringIO makes a string act like a file.
  2. 4-10Sample data as one triple-quoted string. With a real file you would write open('sales.csv', newline='') instead.
  3. 12totals will map each region to its running units and revenue.
  4. 13DictReader turns each line into a dictionary keyed by the header row.
  5. 14-15Everything from CSV is text, so convert units to int and price to float, then compute revenue.
  6. 16-18setdefault creates the region entry the first time we see it; then we add this row's numbers to it.
  7. 20-22Prepare an in-memory output and a csv writer, then write the header row. lineterminator keeps newlines predictable.
  8. 23-24Write one summary row per region in sorted order, formatting revenue to two decimals.
  9. 25-27Compute and write a grand total row, then print the whole report.

Sorting the region names before writing is not decoration. A dictionary remembers insertion order, so without sorted the report order would depend on the order of the input rows, and two runs on shuffled data would look different.

Writing and reading workbooks with openpyxl

openpyxl is the standard library for reading and writing .xlsx files from Python. You install it with pip install openpyxl, ideally inside a virtual environment (see virtual environments and pip). Its main objects are a Workbook, the worksheets inside it, and cells addressed like ws['B2'] or by row and column numbers. Rows and columns are numbered from 1, not 0, which trips up people used to Python lists.

To write, you create a workbook, take its active sheet, append rows, and save. ws.append() adds a row after the last used row, which is the easiest way to dump a table. To read, you call load_workbook() and loop with iter_rows(values_only=True), which gives you plain tuples of values instead of cell objects. That is usually what you want for data processing; keep the cell objects for when you need to change formatting.

These two blocks run on your own computer, not in the browser runner, because openpyxl is not available there. I ran both with openpyxl 3.1 and the output shown is what I saw. Notice the empty tuple at the end of the read loop: iter_rows also returns blank rows inside the used range, so real scripts skip rows where every value is None.

Write a workbookrun on your computer
from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws.title = "Sales"

ws.append(["Region", "Units", "Price"])
for row in [("North", 120, 2.5), ("South", 80, 2.5), ("East", 95, 3.0)]:
    ws.append(row)

ws["A6"] = "Notes"
ws["B6"] = "Prices in USD"
wb.save("sales.xlsx")
print("saved", ws.max_row, "rows")
Expected output
saved 6 rows

Line by line

  1. 1Import the Workbook class.
  2. 3-5Create a new workbook, grab the sheet that is created automatically, and give it a friendly name.
  3. 7-9Append a header row, then one row per tuple. Each call to append lands on the next empty row.
  4. 11-12You can also set a single cell by its address. Here we leave a gap, which is why the sheet reports six rows.
  5. 13-14Save to disk, overwriting any file of that name, and print the used row count. Remember that save() replaces files silently.
Read a workbookrun on your computer
from openpyxl import load_workbook

wb = load_workbook("sales.xlsx")
print(wb.sheetnames)
ws = wb["Sales"]

for region, units, price in ws.iter_rows(min_row=2, max_col=3, values_only=True):
    if region is None:
        continue
    print(region, units, price)
Expected output
['Sales']
North 120 2.5
South 80 2.5
East 95 3

Line by line

  1. 1-3Open an existing workbook. By default formulas come back as their text, which we discuss in the next section.
  2. 4sheetnames lists the tabs in order.
  3. 5Pick a sheet by name; this is safer than relying on whichever sheet happens to be active.
  4. 7Iterate from row 2 (skipping the header), only the first three columns, and receive plain values instead of cell objects. Tuple unpacking names each column.
  5. 8-10Skip blank rows, which appear inside the used range, then process the rest.
⚠️

wb.save('name.xlsx') overwrites the file with no warning, and it cannot save while Excel has the same file open on some systems. Save to a new name while you are developing a script.

Formulas versus values

A cell can hold a value, or it can hold a formula such as =SUM(D2:D4). With openpyxl you write a formula by assigning a string that begins with an equals sign. The file then stores the formula text. Crucially, Excel stores the last calculated result next to the formula, but openpyxl does not calculate anything itself. A workbook that was only ever written by openpyxl has formulas and no cached results at all until Excel (or LibreOffice) opens and saves it.

That produces the most surprising behaviour for newcomers. If you load a workbook normally you see the formula text; if you load it with data_only=True you see the cached results, and for a file generated by openpyxl those are None. So the rule is: to read numbers someone else's Excel calculated, use data_only=True; to inspect or edit formulas, do not use it; and never load with data_only=True and then save, because you will replace every formula with its stale value and lose the live spreadsheet.

A good design question is whether to write formulas or values at all. Formulas keep the sheet live for human editors, which suits a report people will adjust. Values are safer when the Python script is the single source of truth and nobody should edit the numbers. In many reports I compute in Python and write values, and add formulas only for totals people may want to audit. The second block below models the difference with a tiny evaluator: cells hold formulas, and the value is derived from them every time you ask.

Formulas in openpyxl (static)run on your computer
from openpyxl import Workbook, load_workbook

wb = Workbook()
ws = wb.active
ws.append(["Units", "Price", "Revenue"])
ws.append([120, 2.5, "=A2*B2"])
ws.append([80, 2.5, "=A3*B3"])
ws["C5"] = "=SUM(C2:C3)"
wb.save("formulas.xlsx")

print(load_workbook("formulas.xlsx")["Sheet"]["C2"].value)
print(load_workbook("formulas.xlsx", data_only=True)["Sheet"]["C2"].value)
Expected output
=A2*B2
None

Line by line

  1. 1-5Create a workbook with a header and the first data row. The default sheet is called Sheet.
  2. 6-8Strings starting with = are stored as formulas. The =SUM total sits in C5, leaving row 4 blank.
  3. 9Save the file. Nothing has been calculated yet.
  4. 11A normal load returns the formula text.
  5. 12data_only=True asks for cached results. Because this file was never opened in Excel, no results were cached.
A tiny formula evaluator you can run
import re

cells = {"B2": 120, "C2": 2.5, "B3": 80, "C3": 2.5,
         "D2": "=B2*C2", "D3": "=B3*C3", "D4": "=SUM(D2:D3)"}

def value(ref):
    raw = cells[ref]
    if not (isinstance(raw, str) and raw.startswith("=")):
        return raw
    body = raw[1:]
    m = re.fullmatch(r"SUM\(([A-Z])(\d+):([A-Z])(\d+)\)", body)
    if m:
        col, first, _, last = m.groups()
        return sum(value(f"{col}{r}") for r in range(int(first), int(last) + 1))
    m = re.fullmatch(r"([A-Z]\d+)\*([A-Z]\d+)", body)
    if m:
        return value(m.group(1)) * value(m.group(2))
    raise ValueError(f"unsupported formula {raw}")

for ref in ["D2", "D3", "D4"]:
    print(ref, cells[ref], "->", value(ref))

cells["B2"] = 200
print("after editing B2:", value("D4"))
Expected output
D2 =B2*C2 -> 300.0
D3 =B3*C3 -> 200.0
D4 =SUM(D2:D3) -> 500.0
after editing B2: 700.0

Line by line

  1. 1re lets us recognise the two formula shapes we support.
  2. 3-4A sheet as a dictionary: references map to numbers or formula strings.
  3. 6-9value() returns plain numbers unchanged. Anything starting with = is a formula to evaluate.
  4. 10-13Match SUM(D2:D3): capture the column and the first and last row, then add up the value of each cell in the range. Note that it calls itself, because those cells may be formulas too.
  5. 14-16Match a product of two references and multiply their values, again recursively.
  6. 17Anything else is an error, which is better than a silent wrong answer.
  7. 19-20Print each formula next to its computed result.
  8. 22-23Change an input and ask again. The total follows automatically, which is the whole point of a formula.

The evaluator is deliberately small; real spreadsheets support hundreds of functions, ranges across sheets and circular-reference checks. It is here to make one idea concrete: a formula is stored as text and its value is computed from other cells when needed.

Formatting and charts

A report that is correct but ugly gets ignored, so formatting is part of the job. In openpyxl each cell has font, fill, alignment, border and number_format properties. You build style objects (Font(bold=True), PatternFill(...)) and assign them. Column widths are set on ws.column_dimensions, and ws.freeze_panes = 'A2' keeps the header visible when scrolling. Number formats such as '#,##0.00' control how a number is shown without changing the stored value, which is far better than rounding the data itself.

Charts are objects too. You create a BarChart, point Reference ranges at the data and the category labels, add them to the chart and place the chart on the sheet with an anchor cell like 'F2'. The chart stays linked to the cells, so if a person edits the numbers in Excel the chart updates. I keep to simple bar and line charts in scripts; anything elaborate is usually quicker to design once by hand and then fill with data.

Styling every cell in a big sheet one by one can be slow and produces large files, because each unique combination of style is stored. Apply styles to the header row and to specific columns, and reuse the same style objects rather than creating new ones inside a loop. The block below ran locally with openpyxl 3.1.

pythonrun on your computer
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Alignment, Font, PatternFill

wb = Workbook()
ws = wb.active
ws.title = "Sales"
ws.append(["Region", "Units", "Price"])
for row in [("North", 120, 2.5), ("South", 80, 2.5), ("East", 95, 3.0)]:
    ws.append(row)

header_font = Font(bold=True, color="FFFFFF")
header_fill = PatternFill("solid", fgColor="1F4E78")
for cell in ws[1]:
    cell.font = header_font
    cell.fill = header_fill
    cell.alignment = Alignment(horizontal="center")

ws.column_dimensions["A"].width = 14
ws.freeze_panes = "A2"
for (cell,) in ws.iter_rows(min_row=2, min_col=3, max_col=3):
    cell.number_format = "#,##0.00"

chart = BarChart()
chart.title = "Units by region"
data = Reference(ws, min_col=2, min_row=1, max_row=4)
labels = Reference(ws, min_col=1, min_row=2, max_row=4)
chart.add_data(data, titles_from_data=True)
chart.set_categories(labels)
ws.add_chart(chart, "F2")
wb.save("styled.xlsx")

Line by line

  1. 1-3Import the workbook, chart and style helpers.
  2. 5-10Create the sheet and fill it with the same sample rows as before.
  3. 12-13Build one font and one fill and reuse them, which keeps the file small.
  4. 14-17ws[1] is the first row; give every header cell the white bold font, dark blue fill and centred text.
  5. 19-20Widen column A and freeze the top row so the header stays visible.
  6. 21-22Show prices with thousands separators and two decimals. The stored number is unchanged.
  7. 24-25Create a bar chart with a title.
  8. 26-27data includes the header cell so the series gets its name; labels are the region names without the header.
  9. 28-30Attach the data and labels, place the chart at F2, and save.
πŸ’‘

Hex colours in openpyxl are written without the leading hash, such as 1F4E78. A leading # produces an error or a wrong colour.

Merging many files into one

Merging is the classic automation request: twelve monthly files, or one file per branch, that must become a single table. The pattern is always the same. Find the files, check that each one has the structure you expect, read the rows, tag each row with where it came from, and write one combined output. The tagging step is easy to forget and painful to add later, because once rows are mixed you cannot tell which file they came from.

Validation is where merges go wrong in practice. One person renames a column, another adds a blank row above the header, a third saves the file with the columns in a different order. If you blindly stack the rows, the totals will be wrong and nothing will crash to warn you. So compare each file's header with the expected header and stop with a clear message naming the file. The runnable example does this with in-memory CSV text standing in for three files, so you can break a header on purpose and see the error.

After the runnable version comes the openpyxl version for real files, which uses pathlib to find every workbook in a folder (see pathlib). If your merged data becomes large, or you need joins and group-bys, that is the point to move to pandas, where this whole job becomes a concat call. I still teach the manual version first, because it shows what pandas is doing for you.

Merge with validation (runnable)
import csv
import io

files = {
    "jan.csv": "region,units\nNorth,120\nSouth,80\n",
    "feb.csv": "region,units\nNorth,100\nEast,70\n",
    "mar.csv": "region,units\nSouth,90\nEast,60\n",
}
expected = ["region", "units"]

merged = []
for name in sorted(files):
    reader = csv.DictReader(io.StringIO(files[name]))
    if reader.fieldnames != expected:
        raise SystemExit(f"{name}: unexpected columns {reader.fieldnames}")
    for row in reader:
        merged.append({"source": name, "region": row["region"], "units": int(row["units"])})

by_region = {}
for row in merged:
    by_region[row["region"]] = by_region.get(row["region"], 0) + row["units"]

print(len(merged), "rows from", len(files), "files")
for region in sorted(by_region):
    print(f"{region:<6}{by_region[region]:>5}")
Expected output
6 rows from 3 files
East    130
North   220
South   170

Line by line

  1. 4-8Three fake monthly files held in a dictionary, so the example runs without touching disk.
  2. 9The header every file must have.
  3. 11-12Go through the files in sorted order so results are reproducible.
  4. 13-15Compare each file's actual header to the expected one and stop with a message that names the offender.
  5. 16-17Add every row to one list, tagging it with the file it came from and converting units to a number.
  6. 19-21Total the units for each region across all files using dict.get with a default of 0.
  7. 23-25Print the row count and a neat aligned summary; the format codes left-align the name and right-align the number.
Merge real workbooks (static)run on your computer
from pathlib import Path
from openpyxl import Workbook, load_workbook

expected = ["region", "units"]
out = Workbook()
out_ws = out.active
out_ws.append(["source", *expected])

for path in sorted(Path("monthly").glob("*.xlsx")):
    ws = load_workbook(path, read_only=True, data_only=True).active
    rows = ws.iter_rows(values_only=True)
    header = [str(h).strip().lower() for h in next(rows)]
    if header != expected:
        raise SystemExit(f"{path.name}: unexpected columns {header}")
    for row in rows:
        if any(v is not None for v in row):
            out_ws.append([path.name, *row])

out.save("merged.xlsx")

Line by line

  1. 1-2Path finds files; openpyxl reads and writes workbooks.
  2. 4-7Define the expected header and start an output workbook whose first column records the source file.
  3. 9Loop over every .xlsx in a folder called monthly, sorted for a stable order.
  4. 10read_only=True streams large files; data_only=True reads cached values instead of formula text.
  5. 11-14Take the first row as the header, normalise it, and refuse to continue if it differs.
  6. 15-17For the remaining rows, skip completely blank ones and append the rest with the file name in front.
  7. 19Save to a new file, never over one of the inputs.

Word documents and PDFs

Two other office formats come up constantly. For Word, python-docx (installed with pip install python-docx, imported as docx) lets you create documents with headings, paragraphs, tables and formatted runs of text, and open existing ones to read or edit paragraphs. A paragraph is made of runs, and each run can be bold or italic separately, which is why replacing text inside a formatted paragraph is trickier than it looks: the words you want may be split across several runs.

For PDFs, pypdf reads and rearranges them. PdfReader gives you pages and page.extract_text() pulls out text. PdfWriter can add pages from one or many readers and write a new file; its append() method merges whole documents. Two honest limits: text extraction depends on how the PDF was made, and a scanned page is only a picture, so it returns nothing without OCR. And pypdf is for manipulating PDFs, not for designing them; if you need to create attractive PDFs from scratch, generating HTML and converting is often easier.

The runnable block shows the part you can practise in the browser: a mail merge. The logic of filling a template for each person is identical whether the output is a text file, a Word document or an email, so I use string.Template to build the letters and leave the final step to python-docx. The static block then shows that last step, tested with python-docx 1.2 and pypdf 6.

Mail-merge logic (runnable)
from string import Template

letter = Template(
    "Dear $name,\n"
    "Your invoice $invoice for $$${amount} is due on $due.\n"
)

customers = [
    {"name": "Ana", "invoice": "A-101", "amount": "250.00", "due": "2026-12-15"},
    {"name": "Ben", "invoice": "A-102", "amount": "80.50", "due": "2026-12-20"},
]

letters = [letter.substitute(c) for c in customers]
for text in letters:
    print(text)
print(len(letters), "letters ready")

try:
    letter.substitute({"name": "Cy"})
except KeyError as error:
    print("missing field:", error)
Expected output
Dear Ana,
Your invoice A-101 for $250.00 is due on 2026-12-15.

Dear Ben,
Your invoice A-102 for $80.50 is due on 2026-12-20.

2 letters ready
missing field: 'invoice'

Line by line

  1. 1-5A template with $name-style placeholders. $$ produces a literal dollar sign, so $$${amount} prints a dollar sign followed by the amount.
  2. 7-10Each customer is a dictionary whose keys match the placeholder names.
  3. 12Build one finished letter per customer with a list comprehension.
  4. 13-15Print each letter and a count. In the Word version each of these strings becomes a paragraph.
  5. 17-20substitute raises KeyError if a field is missing, which is exactly what you want from a mail merge: fail loudly rather than send a letter saying $invoice.
python-docx and pypdf (static)run on your computer
from docx import Document
from pypdf import PdfReader, PdfWriter

doc = Document()
doc.add_heading("Monthly report", level=1)
para = doc.add_paragraph("Total revenue was ")
para.add_run("1,234.50").bold = True
table = doc.add_table(rows=1, cols=2)
table.style = "Table Grid"
table.rows[0].cells[0].text = "Region"
table.rows[0].cells[1].text = "Units"
cells = table.add_row().cells
cells[0].text, cells[1].text = "North", "120"
doc.save("report.docx")

reader = PdfReader("input.pdf")
print(len(reader.pages), "pages")
print(reader.pages[0].extract_text())

merged = PdfWriter()
for name in ["part1.pdf", "part2.pdf"]:
    merged.append(name)
with open("combined.pdf", "wb") as handle:
    merged.write(handle)

Line by line

  1. 1-2docx comes from the python-docx package; pypdf provides the reader and writer.
  2. 4-5Start an empty document and add a level-1 heading.
  3. 6-7Add a paragraph, then append a separate run of text and make just that run bold.
  4. 8-12Create a table with one row and two columns, use the built-in Table Grid style, and fill the header cells.
  5. 13-14Add a second row and fill its cells.
  6. 15Save the document as report.docx.
  7. 17-19Open an existing PDF, report the page count and extract the text of the first page. Scanned PDFs return an empty string.
  8. 21-25Create a writer, append whole PDF files in order, and write the merged result in binary mode.

Safety: backups, dry runs and trusting nothing

Automation multiplies mistakes as efficiently as it multiplies work. A script that rewrites two hundred workbooks with a wrong formula does damage in seconds. So I build in four habits from the very first draft. Work on copies while you develop. Write output to a new file name instead of overwriting inputs. Add a dry-run mode that prints what would change without changing anything. And keep a backup before any in-place edit, with a timestamp or a .bak suffix.

The write itself can fail too. If your script crashes halfway through writing a file, you may be left with half a workbook. The safer pattern is to write to a temporary file in the same folder and then replace the original in a single step with Path.replace, which the operating system performs atomically on the same disk. Either you get the old complete file or the new complete file, never a torn one.

Finally, treat incoming files as untrusted. Real spreadsheets contain blank rows, text where numbers should be, merged cells, hidden sheets and dates stored as text. Check the things you rely on and print a clear message when something is off. And remember that workbooks can contain macros or external links; a script that only reads data does not run them, but do not open files from unknown senders just because a script made it convenient. The example below combines a dry run, a backup and an atomic replace using temporary files, so it is safe to run here.

python
import shutil
import tempfile
from pathlib import Path

def safe_update(path, transform, dry_run=True):
    path = Path(path)
    old = path.read_text()
    new = transform(old)
    if new == old:
        return "no change"
    if dry_run:
        return f"dry run: would change {len(old)} -> {len(new)} characters"
    backup = path.with_name(path.stem + ".bak" + path.suffix)
    shutil.copy2(path, backup)
    temp = path.with_name(path.name + ".tmp")
    temp.write_text(new)
    temp.replace(path)
    return f"changed; backup saved as {backup.name}"

with tempfile.TemporaryDirectory() as folder:
    target = Path(folder) / "prices.csv"
    target.write_text("item,price\npen,2.50\nbook,4.00\n")
    raise_prices = lambda text: text.replace("2.50", "2.75")

    print(safe_update(target, raise_prices))
    print(target.read_text().splitlines()[1])
    print(safe_update(target, raise_prices, dry_run=False))
    print(target.read_text().splitlines()[1])
    print(sorted(p.name for p in Path(folder).iterdir()))
Expected output
dry run: would change 30 -> 30 characters
pen,2.50
changed; backup saved as prices.bak.csv
pen,2.75
['prices.bak.csv', 'prices.csv']

Line by line

  1. 1-3Standard-library helpers for copying files, making temporary folders and handling paths.
  2. 5-8The function reads the file, applies a transform function to get the new content, and compares.
  3. 9-10If nothing would change, say so and stop.
  4. 11-12By default we only report what would happen. Making the safe behaviour the default means forgetting an argument cannot cause damage.
  5. 13-14Name a backup next to the original (prices.bak.csv) and copy the file, preserving timestamps.
  6. 15-17Write the new content to a temporary file, then atomically replace the original with it.
  7. 18Report what happened.
  8. 20-22Use a temporary folder that disappears afterwards, and create a small sample file.
  9. 23A transform is just a function from old text to new text, so it can be tested on its own.
  10. 25-29Run a dry run (file untouched), then a real run, printing the price line each time and finally the folder contents, which now include the backup.

For Excel files the same structure applies: copy the workbook first, load the copy, make changes, save under a new name, and only then decide whether to replace the original.

Common mistakes

❌ Loading with data_only=True and saving

This replaces every formula with its last cached value. The file looks fine until someone changes an input and nothing updates. Load once for reading values and once, separately, for editing.

❌ Expecting openpyxl to calculate formulas

openpyxl writes formula text but does not evaluate it, so a freshly generated workbook has no cached values. Either write computed values from Python or let Excel or LibreOffice calculate the file on opening.

❌ Overwriting the original file

Saving over the input means one bug destroys the only copy. Write to a new name, or back up first and replace atomically.

❌ Stacking files without checking headers

If one file has its columns in a different order, the merged table is silently wrong. Validate headers and name the offending file before merging.

❌ Forgetting that CSV values are text

Numbers read from CSV arrive as strings, so '120' + '80' gives '12080'. Convert with int or float as soon as you read each row.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. What is an .xlsx file?

Q2. You generate a workbook with openpyxl containing =SUM(A1:A3) and load it with data_only=True. What do you get for that cell?

Q3. Why use sorted() on dictionary keys before writing a report?

Q4. What is the safest way to update a file in place?

Q5. Which method merges whole PDF files with pypdf?

Q6. Why is a dry-run mode useful?

Frequently asked questions

No. openpyxl reads and writes the XML inside the file itself. You only need Excel (or LibreOffice) if you want formulas calculated, charts previewed or macros run.

No, openpyxl supports the modern .xlsx family. For legacy .xls you would convert the files to .xlsx first, or use a library that reads that older format.

Use pandas when the job is mostly analysing tabular data and writing a plain table. Use openpyxl when you care about the workbook itself: formatting, formulas, charts, specific cells. Many scripts use both, with pandas for the data and openpyxl for the polish.

openpyxl only preserves what it models. Items such as some charts, images, pivot tables or macros may not survive a load and save, so test on a copy and compare the result before trusting it.

The runner uses Pyodide, which ships a fixed set of packages. openpyxl, python-docx and pypdf are not included, so those blocks are marked as run-on-your-computer and the page offers standard-library versions of the same ideas.

Key takeaways

  • βœ“An .xlsx or .docx file is a zip of XML parts, which is why Python can handle them without Office.
  • βœ“Solve the data problem with rows and dictionaries first; spreadsheets are just the input and output containers.
  • βœ“openpyxl writes formulas as text and never calculates them; data_only=True reads cached values and must not be used for editing.
  • βœ“Reuse style objects, set number formats instead of rounding data, and keep charts simple.
  • βœ“When merging files, validate headers, tag each row with its source and never overwrite the inputs.
  • βœ“Use backups, dry runs and atomic replacement so automation cannot quietly destroy real files.