Automating a Recurring Excel Report From Production Data: Mapping, Reconciliation and Safe Reruns
Automating a weekly Excel report is mostly not about Excel. It's about deciding which rows belong to the period, what happens to the rows that don't fit, and proving the totals before anyone opens the file. A worked, tested example with synthetic data.


Text equivalent. Production reporting Teaching diagram • Map, reconcile, then decide to send SYNTHETIC SAMPLE / 23 LOCAL CHECKS; NOT A GENERAL IMPORTER 1 / File gate Exact columns; unique product_code Invalid configuration stops the run 2 / Validate each row UTC marker: Z or +00:00 only Naive / other offset / invalid > quarantine Validate BEFORE period filtering 3 / Period ISO week in plant time Half-open [start, next start) 4 / Duplicate + row outcomes event_id: exact resend > count once Conflicting versions > quarantine both 10 = 4 accepted + 3 quarantined + 1 duplicate + 2 outside period 5 / Workbook Summary + Exceptions Imported strings forced to text One trusted formula: Summary!G2 6 / Reconcile saved workbook Good 485; scrap 8 (named values) + body + row accounting Only intended formula: =SUM(D6:D7) in G2 Three unresolved exceptions > send_allowed = false Consistency with accepted rows, NOT export completeness SEND BLOCKED Source control total still needed No actual sending implemented RERUN LIMITS / RECOMMENDATIONS ARE NOT IMPLEMENTED SHA-256: input + mapping + period + time zone + rules version + code hash Same record: identical CELL VALUES, not identical XLSX bytes. 8-character filename tag is NOT unique. Send ledger, approval, input freeze and write-then-rename: recommendations only; not a scheduler. Synthetic v2 example / 23 checks reported in draft; spreadsheet recalculation and source completeness not proved
Most recurring production reports start as one person's Monday morning. They export last week's rows, paste them into a workbook leadership already knows how to read, fix the product names that don't match, delete the rows that came through twice, check the total against the system, and send it. Automating that report means automating every one of those judgement calls, not just the paste.
This article walks through the decisions that make a generated workbook safe to send: a mapping table, a written period boundary, explicit handling of missing, duplicate and stale rows, a reconciliation step that can block the send, and reruns that don't produce a second, different report for the same week.
About the example. The production system I built for an industrial import and manufacturing client generates Excel reports as one of its functions (case study). Serial traceability from intake to dispatch is the stage model beside this report. That case file doesn't document which library or method it uses, and nothing here is attributed to it. Every row, product code, label and line of code below is a synthetic example written for this article. The Python script was run locally on the sample files shown (Python 3.13.5, openpyxl 3.1.5); results are listed under What the example run showed. It's a teaching sample for exports of this exact shape, not a general-purpose importer or scheduler.
If you're still deciding whether this kind of report is worth automating at all, what to automate first in a small business covers that decision. This article assumes you've decided, and you want the result to be trustworthy.
Start from the layout people already trust
The fastest way to lose leadership's confidence is to "improve" the report while automating it. If the current workbook has a summary block at the top, families grouped in a particular order and an exceptions tab someone checks, the generated version should reproduce that before changing anything.
Write down the current report as a spec before writing code:
| Part of the report | What to record | Why it matters for automation |
|---|---|---|
| Period | Exactly which days, in which time zone, and what "end of week" means | Most silent errors are rows on the wrong side of a boundary |
| Rows → groups | Which source field becomes each grouping (line, family, product label) | Defines the mapping table |
| Measures | Which numbers are summed, and which are copied | Defines what reconciliation must check |
| Exceptions | What the person currently fixes by hand, and how | Each fix becomes a rule or a quarantine reason |
| Recipients and timing | Who gets it, when, and whether a resend is ever allowed | Defines rerun behaviour |
The "exceptions" row is the one people skip. Ask the person who builds the report today what they change before sending it. Each answer is either a rule the code applies, or a reason the code stops and asks.
The example: input rows, mapping, expected workbook
The synthetic source is an export of completed production events. Timestamps are in UTC, as many systems store them.
input.csv (synthetic):
event_id,completed_at_utc,line,product_code,qty_good,qty_scrap
E-1001,2026-11-01T20:40:00Z,L1,PC-100,120,3
E-1002,2026-11-01T20:20:00Z,L1,PC-100,80,1
E-1003,2026-11-02T08:15:00Z,L2,PC-210,200,4
E-1004,2026-11-03T11:05:00Z,L1,PC-100,95,0
E-1004,2026-11-03T11:05:00Z,L1,PC-100,95,0
E-1005,2026-11-04T14:30:00Z,L2,PC-215,60,2
E-1006,2026-11-05T09:00:00Z,,PC-210,40,1
E-1007,2026-11-06T16:45:00Z,L2,PC-999,10,0
E-1008,2026-11-08T20:10:00Z,L1,PC-100,70,1
E-1009,2026-11-08T20:40:00Z,L2,PC-210,55,0Ten rows, and almost every one of them carries a lesson: two sit on period boundaries, one is sent twice, one uses a retired label, one has no line, and one has a product code nobody mapped.
The column is called completed_at_utc, so the example holds it to that: every timestamp must carry an explicit UTC marker (Z or +00:00). A timestamp with no offset is quarantined rather than guessed. Python's datetime.fromisoformat would accept it and astimezone() would then read it in whatever time zone the server happens to run in. A timestamp with a different offset is quarantined too. If your source legitimately sends local offsets, convert them deliberately and rename the field.
mapping.csv (synthetic) turns system codes into the labels leadership reads:
product_code,report_label,family,active
PC-100,Valve body 100,Valves,yes
PC-210,Pump housing 210,Pumps,yes
PC-215,Pump housing 215 (retired label),Pumps,noKeep the mapping as data, owned by someone in operations, not as if statements in the script. When a product is renamed, the fix is a row edit that can be reviewed, not a code change.
Two file-level problems stop the run instead of quarantining rows: unexpected columns in either file, and the same product_code listed twice in the mapping. Loading a mapping into a dictionary would otherwise let the last row silently win.
The expected workbook for ISO week 45 of 2026, read back from the generated file:
Summary sheet
| Line | Family | Product | Good | Scrap |
|---|---|---|---|---|
| L1 | Valves | Valve body 100 | 285 | 4 |
| L2 | Pumps | Pump housing 210 | 200 | 4 |
| Total | 485 | 8 |
Exceptions sheet
| event_id | reason |
|---|---|
| E-1005 | inactive mapping label (stale) |
| E-1006 | missing line |
| E-1007 | unmapped product_code |
The rest of this article explains how each row ended up where it did.
Period and time-zone boundaries
"Last week" needs a definition precise enough for code: which calendar, which first day, which time zone, and whether the end is inclusive.
The example uses ISO week 45 in the plant's local time (the sample uses Asia/Tehran, UTC+03:30), as a half-open interval: from Monday 00:00 local, up to but not including the next Monday 00:00 local. Half-open intervals mean every instant belongs to exactly one week, with no "23:59:59" gaps.
Converting each UTC timestamp to plant time before testing it against the interval changes four rows' fate:
| Event | UTC | Plant time | In week 45? |
|---|---|---|---|
| E-1002 | Sun 1 Nov 20:20 | Sun 1 Nov 23:50 | No — previous week |
| E-1001 | Sun 1 Nov 20:40 | Mon 2 Nov 00:10 | Yes |
| E-1008 | Sun 8 Nov 20:10 | Sun 8 Nov 23:40 | Yes |
| E-1009 | Sun 8 Nov 20:40 | Mon 9 Nov 00:10 | No — next week |
Filter on the UTC date instead and E-1001 and E-1009 land in the wrong week. Both errors look plausible in a total, which is why nobody notices.
Decide these explicitly and print them on the report:
- Whose time zone? Usually the plant's, because that's how shifts are planned. If several sites report together, pick one and say so.
- Which timestamp? Completion, posting or approval time can differ by days. Choose the one that matches what the report claims to measure.
- Daylight saving. Use a time-zone database (Python's
zoneinfo, for example), not a fixed offset, if the plant's zone has DST. - Late arrivals. A row posted on Tuesday for last Friday either reopens last week's report or counts in this week's. Pick one rule. Option 1 needs the rerun rules below.
Missing, duplicate and stale rows
Every row that doesn't fit gets one of three outcomes: dropped with a reason, quarantined for a person, or accepted. "Silently fixed" isn't an option.
| Situation in the sample | Outcome in the example | Why |
|---|---|---|
| E-1004 appears twice with identical content | Count once; log the duplicate | An exact resend is a transport artefact, not two events |
Same event_id appears twice with different content | Quarantine both versions | Picking one guesses which is true; summing both double counts |
| E-1005 maps to an inactive label | Quarantine (stale label) | Reporting it under a retired name misleads; reporting it under the new name guesses |
| E-1006 has no line | Quarantine (missing line) | Defaulting to a line invents data |
| E-1007's product code isn't in the mapping | Quarantine (unmapped) | A new product needs a mapping decision by a person |
| Quantity is negative or not an integer | Quarantine | Bad source data should be fixed at source |
The identity rule matters. Deduplicating on a stable event_id is safe. Deduplicating on "same product, same quantity, same hour" isn't: two genuine runs can look identical. If the source has no stable event identifier, that's worth fixing before automating the report, because no downstream rule can reliably tell a resend from a real repeat.
Quarantined rows go on the Exceptions sheet with their reason, so the reader sees what was left out rather than discovering it in a different system's total.
The example validates every row before checking the period. That's a deliberately conservative policy: an invalid row blocks the send even if it may belong to another week, because without a trustworthy timestamp or line you can't be sure it doesn't belong to this one. If that's too strict for your data, filter by period first and accept that some broken rows go unreported.
Reconcile before you send
Reconciliation is the step that turns "the script ran" into "the workbook matches what we meant to report". The example reads the saved workbook back from disk and compares it with the accepted rows. Reading the file back, rather than trusting the variables the script just used, catches errors in the writing step too. These are consistency checks between the accepted rows and the file. They don't prove the export itself was complete, which is what the source-system control total is for.
Reconciliation checklist (the example implements the first four and the formula-cell check below):
- Row accounting. Input rows = accepted + quarantined + duplicates dropped + out-of-period. Sample: 10 = 4 + 3 + 1 + 2.
- Totals match the accepted rows. Sample: good 485 and scrap 8, each read back from its named total cell.
- Body matches the summary. Every line/family/product row read back from the sheet equals the computed summary.
- No unresolved exceptions — or an explicit, named approval to send with them.
- Control total from the source system. If the production system shows its own weekly total, compare against it. A mismatch here means the export query is wrong, which no workbook check can see.
- Period and source fingerprint printed on the report, so a reader can tell which data produced it.
- Only intended formulas. Reloaded without
data_only, the only formula cell is the one the code wrote on purpose (see Imported text must stay text).
In the sample, the first three checks pass and the fourth fails: three rows are quarantined. So the example sets send_allowed = false. That's the correct outcome. Somebody needs to map PC-999, decide what PC-215 is now called and find E-1006's line before the report goes out, or explicitly approve sending with those exclusions listed.
Make the send step depend on the checks, not on a person remembering to look at them.
Safe reruns
The report will be rerun: a late row arrives, a mapping gets fixed, the job fails halfway. A rerun should never produce a second, conflicting report for the same week without anyone knowing.
The example makes the cell contents deterministic for a given run record. That record is the input file, the mapping file, the period, the time zone, a rules version and a hash of the script itself:
- A SHA-256 fingerprint is computed over that whole record. The file name carries the period and the first 8 hex characters, for example
production-2026-W45-11cc41d9.xlsx. Those 8 characters are a convenience for people, not a unique ID. Keep the full digest in your records. - Rerunning with the same record produced the same file name and identical cell values in the test script. That's a claim about cell values, not byte-identical files: XLSX files contain metadata such as creation times.
- Changed inputs or code normally produce a different fingerprint, so a corrected report is distinguishable from the one already sent. Compare full digests, not the short name.
The example stops there. The controls below are recommendations it does not implement:
- A send ledger. Record period, full fingerprint, rules and code version, recipients and time for each send. Before sending, check whether this period has already been sent with a different hash. If so, the email must say it's a correction and what changed.
- Write, then rename. Save to a temporary name and rename once complete, so a crash never leaves a half-written file where the sender will pick it up.
- Freeze the inputs for a sent report. Keep the exact input and mapping files and the code version used for every sent report, so last month's numbers can be reproduced.
- An approval step for sends with exceptions, and a correction message when a period is resent.
openpyxl as one illustrative option
The example uses openpyxl, which describes itself as "a Python library to read/write Excel 2010 xlsx/xlsm/xltx/xltm files." It's one reasonable option for a Python pipeline, not the only one. A reporting tool, a database export or an automation platform's spreadsheet step can do the same job. The decisions above apply whichever tool writes the file.
Three openpyxl behaviours matter for this kind of report and were checked in the example run:
It writes formulas but doesn't calculate them. The example writes =SUM(D6:D7) into a check cell. Reloaded with data_only=True, that cell's value is None: openpyxl has stored the formula text, and no calculated value exists until a spreadsheet application opens and saves the file. For a report reconciled before sending, that means:
- Write totals as values computed in code, and reconcile those, or
- If the template relies on formulas, accept that you can't verify them from openpyxl alone. Recalculate them with a spreadsheet engine before sending, or reconcile the inputs and treat the formulas as presentation.
Defined names avoid hard-coded addresses, but someone has to maintain them. The openpyxl docs define them as "descriptive text that is used to represents a cell, range of cells, formula, or constant value" (defined names). The example names the total cells total_good and total_scrap after it has written the rows, and the reconciliation reads them by name rather than by D8. Don't assume a name follows the cell when rows move. In the test, inserting a row with openpyxl's insert_rows left the name pointing at the old address. Whether a spreadsheet application adjusts the name when a person inserts rows wasn't tested here. Whatever edits the template has to keep the references correct, and you have to test that.
Imported text must stay text. openpyxl treats any string starting with = as a formula. A product label or event ID arriving as =HYPERLINK(...) or =1+1 from an export would be saved as a live formula in the report, and in the test it was: an unforced write of =1+1 produced a formula cell. The example writes every imported value through one routine that forces the string type, so the hostile label and event ID in the test were saved as text, and the file contained exactly one formula, the one written on purpose. Reading a workbook back with data_only=True doesn't protect you. It hides formulas rather than removing them. Check with a normal load, as the test does. CSV-style escaping, such as prefixing an apostrophe, isn't the remedy for XLSX output. The cell type is what matters.
The core of the example script (a partial excerpt; the full script also validates, deduplicates and reconciles):
# SYNTHETIC teaching excerpt. openpyxl is one illustrative option. Tested: Python 3.13.5, openpyxl 3.1.5.
from openpyxl import Workbook, load_workbook
from openpyxl.workbook.defined_name import DefinedName
from openpyxl.utils import quote_sheetname, absolute_coordinate
def put_text(ws, row, col, value):
"""Write imported text as a literal string. openpyxl treats a str starting with '='
as a formula; forcing the string type stores it as text instead."""
cell = ws.cell(row=row, column=col, value=value)
if isinstance(value, str):
cell.data_type = "s"
return cell
def append_values(ws, values):
r = ws.max_row + 1 if ws.max_row > 1 or ws.cell(1, 1).value is not None else 1
for c, v in enumerate(values, start=1):
put_text(ws, r, c, v)
return r
def write_summary(path, period_label, fingerprint, summary, quarantined):
wb = Workbook(); ws = wb.active; ws.title = "Summary"
append_values(ws, ["Weekly production summary"])
append_values(ws, ["Period", period_label])
append_values(ws, ["Run fingerprint", fingerprint[:16]])
append_values(ws, [None])
append_values(ws, ["Line", "Family", "Product", "Good", "Scrap"])
for row in summary: # labels come from imported data
append_values(ws, list(row))
total_row = append_values(ws, ["Total", "", "", sum(r[3] for r in summary), sum(r[4] for r in summary)])
for name, col in (("total_good", "D"), ("total_scrap", "E")): # values, not formulas
ref = f"{quote_sheetname(ws.title)}!{absolute_coordinate(f'{col}{total_row}')}"
wb.defined_names[name] = DefinedName(name, attr_text=ref)
ex = wb.create_sheet("Exceptions"); append_values(ex, ["event_id", "reason"])
for q in quarantined: # event ids are imported data too
append_values(ex, [q["event_id"], q["reason"]])
wb.save(path)
def read_named(path, name):
wb = load_workbook(path, data_only=True)
sheet, coord = next(wb.defined_names[name].destinations)
return wb[sheet][coord.replace("$", "")].valueNotes on the snippet:
- Trusted formulas, if you need any, should be written by separate code that never receives imported text.
wb.defined_names[...] = DefinedName(...)is the workbook-scoped assignment style in openpyxl 3.1. Older tutorials usewb.defined_names.append(...), which is a different API. Pin the version you test with.- Writing into an existing branded template (
load_workbook("template.xlsx")) is usually closer to "keep the layout people trust" than building sheets from scratch. Test that path separately: charts, images and some formatting in an existing file may not survive a load-and-save round trip with any library. Open the generated file in the spreadsheet application your readers use before the first send.
What the example run showed
The test script exits with an error if any check fails. All 23 checks passed on Python 3.13.5 with openpyxl 3.1.5:
| Area | Checks |
|---|---|
| Reruns | Same run record → same file name and fingerprint, identical cell values. Changed input → different fingerprint |
| Period | E-1001 (00:10 plant time Monday) in, E-1002 (23:50 the Sunday before) out, E-1009 (00:10 next Monday) out. Totals 485 good / 8 scrap |
| Rows | Exact duplicate counted once. Conflicting duplicate quarantined in both versions. Stale label quarantined. Invalid out-of-period row still quarantined |
| Timestamps | No offset → quarantined. +03:30 on a UTC field → quarantined. +00:00 accepted like Z. Malformed → quarantined |
| Configuration | Duplicate mapping key and a missing input column each stop the run |
| Workbook | Hostile =1+1 label and =2+2 event ID stored as text. Exactly one formula element in the saved file. Trusted formula reads None with data_only=True. Named totals, body and row accounting reconcile. Send blocked while rows are quarantined |
| Limitation | insert_rows didn't update the defined name (recorded as observed behaviour) |
Three deliberately broken copies of the script were run as negative controls: one without the text-forcing step, one that accepts naive timestamps, and one that lets the last mapping row win. The suite failed (exit 1) on each, on the checks you'd expect.
These checks show the example behaves as described on this data. They don't show it's ready for your data. Your export will have its own edge cases, and those need their own fixtures before the first automated send. DST transitions (the sample zone has none in 2026), very large exports and writing into an existing template weren't tested.
Where this stops
This article covers turning rows into a report someone can trust for one period. It doesn't cover lineage: tracing a finished unit back through the parts and stages that produced it. That's a record-design problem upstream of any report. It also assumes the production records already exist in a form you can read; if status still lives only in a sheet, start with outgrowing the production spreadsheet.
It also doesn't make any claim about time saved. How long the manual version takes, and how much of it disappears, depends on how many exceptions your data produces each week. Measure that before and after if it matters to your decision.
If you want help
If your weekly report is still a Monday-morning job, I can help plan the period rules, mapping, reconciliation and safe-rerun path for your data as part of operations and reporting work.
What could this change for you?
Tell me what you’re building — I’ll tell you honestly where I’d start.
Start a project with me