Spreadsheet Pricing Audit: Rebuild the Math in Python14 min read2,718 words

Spreadsheet Pricing Audit: Rebuild the Math in Python

Audit a pricing workbook without trusting its displayed totals. Extract XLSX formulas, rebuild money math with Decimal, and find errors hidden in the paperwork.

spreadsheet pricing auditXLSX formula extractionPython Decimal money calculationsspreadsheet validation auditpricing workbook testing
Spreadsheet Pricing Audit: Rebuild the Math in Python

How to Audit a Pricing Workbook Without Opening Excel

A pricing workbook can look trustworthy because it contains formulas, formatted totals, and a polished explanation of how the numbers work. But none of that proves the math is right - or that customers are actually using the same rules the spreadsheet assumes.

A good audit treats the workbook like a claim you have to test. Pull the formulas (and any saved values), rebuild the calculations on your side using the underlying rate card, then compare what you get with any paper forms or written instructions that describe the pricing rules. That's how you catch mistakes that disappear if you only open the file and decide the totals "look reasonable."

This walkthrough uses a small septic-pumping business kit as a case study: twelve files, one XLSX workbook, fourteen pricing constants, and three worked examples. It covers how to inspect an XLSX file as raw XML, how to reproduce money calculations with Python's Decimal, and how comparing against the printed quote form uncovered a pricing defect that wasn't fixed inside the workbook itself.

Why is a pricing workbook a claim rather than proof?

A spreadsheet combines three things: executable logic, cached results, and presentation. That's convenient, but it also makes it easy to confuse "plausible" with "verified."

A workbook can show a correct formula alongside a stale cached result. Written instructions can describe a different formula than the one in the spreadsheet. And a worked example can match the author's intent while still contradicting what the printed instructions tell a customer to do.

A simple way to avoid that trap is to separate three questions:

  • What calculation does the workbook specify? Read its formulas and inputs.
  • What result does an independent implementation produce? Recalculate from the documented constants.
  • What calculation will a person using the paperwork actually perform? Follow the form as written, then compare it to the workbook.

Those tests cover different failure modes. Getting the arithmetic right in one implementation doesn't guarantee the paperwork tells people the same story.

Start with the files that define the rules

For this audit, the workbook wasn't the only source of pricing information. The kit also included a CSV rate card with fourteen parameter rows. That made it a better starting point for an independent rebuild: CSV values are easy to parse, and the file can't hide logic behind cached results.

The workbook still mattered. It showed how the pricing rules were implemented, what values had been saved, and whether inputs had validation. The paper quote form mattered for a different reason: it showed what a user would be told to calculate outside the spreadsheet.

Treat these artifacts as separate evidence. If the workbook, rate card, and paper form disagree, the disagreement is the finding. Don't quietly "choose the most reasonable version" and call it consistent.

Define the limits of the result

A rebuild can show that someone else can reproduce the workbook's examples from the supplied constants. It can't prove the constants are commercially sensible, legally compliant, or appropriate for a particular county - that needs local pricing and regulatory context outside a spreadsheet audit.

In this case, three worked examples matched to the cent, and a seventeen-row startup ladder with a 10% contingency and first-month cash requirement also matched. That supports a narrow conclusion: the documented pricing engine is internally reproducible for the supplied inputs. It doesn't automatically mean the rates are correct for every business.

How do you inspect XLSX formulas without Excel?

An XLSX file is a ZIP archive containing XML documents. A worksheet's XML can show cell references, formulas, cached values, and validation rules - without launching Excel or installing a spreadsheet library. For a focused audit, Python's zipfile and xml.etree.ElementTree are enough.

import zipfile

from xml.etree import ElementTree as ET

NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"

with zipfile.ZipFile(path) as z:

shared_strings = []

if "xl/sharedStrings.xml" in z.namelist():

root = ET.fromstring(z.read("xl/sharedStrings.xml"))

for item in root.findall(NS + "si"):

shared_strings.append(

"".join(text.text or "" for text in item.iter(NS + "t"))

)

sheet = ET.fromstring(z.read("xl/worksheets/sheet2.xml"))

for row in sheet.iter(NS + "row"):

for cell in row.findall(NS + "c"):

value_node = cell.find(NS + "v")

formula_node = cell.find(NS + "f")

value = value_node.text if value_node is not None else None

if cell.get("t") == "s" and value is not None:

value = shared_strings[int(value)]

formula = formula_node.text if formula_node is not None else None

print(cell.get("r"), repr(value), formula)

A cell's <f> element contains the formula. Its <v> element may contain the value saved the last time the workbook was recalculated and saved. Shared strings require one extra step: for cells marked t="s", the value is an index into sharedStrings.xml, not the text itself.

Compare the formula with its saved value

That pairing is useful because it shows the intended calculation and the workbook's last saved result. In the audited calculator sheet, the total cell contained the formula ROUND(SUM(B13:B21),2) and a cached value of 508.75.

A cached value isn't independent confirmation. It can be stale if inputs changed without a recalculation, and not every file will even store a cached value. The point is to see what's actually in the file, then compute what you expect from the inputs yourself. If the formula and cache don't line up with your rebuild, investigate before trusting the displayed total.

Check validation rules and workbook structure

The XML also showed input validation for nine calculator inputs: "No" and "Yes" lists for four flag cells, whole-number values from 0 to 4 for two count cells, and minimum-value rules for tank size and mileage. That supports the claim that inputs were validated - and also shows why formula-only inspection isn't enough.

One practical caveat: the sample code reads sheet2.xml directly. In a general-purpose auditor, you can't assume the worksheet you see in Excel corresponds to that exact filename. Excel uses workbook relationships (xl/workbook.xml and xl/_rels/workbook.xml.rels) to map sheet names to worksheet XML paths. Resolve the intended sheet through those relationships before relying on a hard-coded path.

Raw XML is handy when you want a small, dependency-free inspection or you need to verify exactly what the file stores. For editing, navigating many sheets, or handling more of the XLSX format, a library like openpyxl is usually easier. Choose based on the audit task, not on a blanket preference for low-level code.

How do you rebuild pricing calculations accurately?

Rebuilding should start from the rate card, not from values copied out of the workbook. Parse the constants as decimal strings, re-implement each pricing rule explicitly, and compare intermediate line items as well as final totals. Checking only the final number can hide two mistakes that cancel each other out.

For the case study, the pricing logic selected:

  • a base charge by tank capacity,
  • a travel charge beyond a free mileage allowance,
  • a disposal charge (also with a free allowance),
  • and optional service fees.

Mileage works like this: only miles beyond the allowance are billable.

from decimal import Decimal as D, ROUND_HALF_UP

def q(value):

return D(value).quantize(D("0.01"), rounding=ROUND_HALF_UP)

def line_items(tank, travel, disposal, after_hours, filter,

risers, digs, locate, commercial, rates):

tank = D(str(tank))

travel = D(str(travel))

disposal = D(str(disposal))

if tank <= 1000:

base = rates["b1"]

elif tank <= 1500:

base = rates["b2"]

else:

base = rates["b3"]

travel_charge = max(D("0"), travel - rates["free_travel"]) * rates["travel_rate"]

disposal_charge = (

rates["drop_fee"]

+ max(D("0"), disposal - rates["free_disposal"]) * rates["disposal_rate"]

)

return [

q(base),

q(travel_charge),

q(disposal_charge),

q(rates["after_hours"] if after_hours else D("0")),

q(rates["filter"] if filter else D("0")),

q(D(str(risers)) * rates["riser"]),

q(D(str(digs)) * rates["dig"]),

q(rates["locate"] if locate else D("0")),

q(rates["commercial"] if commercial else D("0")),

]

Load the rate values into rates as decimals too - again from strings like D("1.25"). Don't pass binary floats straight into Decimal; you'll preserve the float's approximation instead of the decimal amount you think you're using.

Why use Decimal instead of float?

Money calculations often depend on rounding at the cent boundary. Binary floating point can't represent many decimal fractions exactly: 0.1 + 0.2 is close to 0.3, but not exactly 0.3. If your workbook uses half-up rounding and your audit uses floats, a difference around a half-cent can come from your implementation, not the spreadsheet.

Decimal from strings keeps arithmetic in base ten and makes the rounding rule explicit. But it still doesn't automatically guarantee you matched the workbook. You have to match the workbook's order of operations: whether it rounds each line item, only the final sum, or both.

In this example, each returned line item is rounded to two decimals, so your implementation needs the same behavior if you want to reproduce the workbook.

Make floors and thresholds explicit

The mileage rule uses a floor like max(0, miles - free_allowance). That isn't defensive programming - it's part of the pricing rule. Without it, a trip inside the free band produces a negative mileage charge.

Test boundaries too: values immediately below, at, and above each threshold. For a 15-mile free travel allowance, test 14, 15, and 16 miles. These cases expose off-by-one errors and missing floors faster than "another ordinary example."

What does comparing the workbook with the form reveal?

In this kit, the spreadsheet charged mileage using a zero floor. The printed paper quote form didn't. The form computed travel as "one-way miles − 15 free" multiplied by the per-mile rate, and disposal as "one-way miles − 12 free" multiplied by its rate (plus a fixed fee). It didn't tell the reader to clamp negative results to zero.

That matters because customers following the form literally can arrive at a lower price than the workbook would produce. For example, a nine-mile disposal run gives:

$45 + (9 − 12) × $0.85 = $42.45

while the spreadsheet yields $45.00. Eight travel miles creates the same issue: the printed arithmetic implies a negative travel charge.

The kit's filled example shows what the author likely intended: it charged the full disposal fee and notes that the trip was inside the free allowance. But the note doesn't fix the formula printed above it. An example can reveal intent; it can't make inconsistent instructions safe.

Job Spreadsheet Paper form Delta
1,250 gal · 18 mi · 9 mi $293.75 $291.20 −0.9%
950 gal · 8 mi · 6 mi $220.00 $206.15 −6.3%
1,250 gal · 10 mi · 8 mi $290.00 $280.35 −3.3%
950 gal · 5 mi · 4 mi $220.00 $200.70 −8.8%
2,200 gal · 30 mi · 25 mi $399.80 $399.80 0.00%

The final row is the diagnostic case: both mileage inputs are beyond their free allowances, so the form and workbook agree. The other examples are lower on the paper form because one or both values fall inside a free band. That pattern points to a missing zero floor on the form rather than a general arithmetic error.

Fix the instruction without erasing the evidence

The correction is straightforward: add a zero floor to both calculations, or explicitly state that mileage inside the free allowance is charged as zero. But during an audit, you shouldn't "silently edit" the product you're reviewing. Doing so changes the evidence and makes it harder for the owner to see what users received.

Instead, record the mismatch, show the cases that reproduce it, and give the owner a clear correction. Then the owner can update the form, examples, and any other published instructions as a controlled change.

Also pay attention to the direction of the error. Here, the paper form underprices jobs whenever a mileage value falls inside a free band. That's a potential margin leak, not just a hypothetical risk of customer overbilling or a future support issue.

Add checks that fail loudly

A self-check that prints only "PASS" is weak evidence. Add a deliberately broken input or alter a rule in the test run and confirm the comparison fails. Keep a table of inputs, per-line outputs, totals, and expected values. If rates change later, that record helps separate "result changed" from "calculation changed."

For a reusable audit, include at least:

  • ordinary examples from the provided documentation;
  • values just below, at, and above each threshold;
  • zero or blank optional charges where those inputs are allowed;
  • a deliberate mismatch that proves the test can detect failure;
  • and a separate comparison of workbook logic versus non-workbook forms.

One last helpful check: print effective unit prices. Here, dividing the base charge by tank capacity at 1,000, 1,250, and 2,200 gallons gives $0.175, $0.196, and $0.148 per gallon. The rate card cited a range of $0.30 to $0.70 for very large tanks. The numbers may be talking about different things (base charge versus total invoice), but lining them up makes it clear that the rate card needs clarification. The audit should flag that question, not invent an answer.

Conclusion

A pricing workbook is just one part of a pricing system. Inspecting its XML shows formulas, saved values, and input validation. Rebuilding the engine with Decimal tests whether the documented arithmetic can be reproduced. Comparing against the paperwork checks whether customers are given the same rules.

The practical sequence is simple: start from the source constants, extract the workbook logic, test threshold cases, compare intermediate and final values, then follow the instructions outside the spreadsheet as written. In this audit, that sequence matched the workbook's calculations and also exposed a missing zero floor on the paper form - something a normal spreadsheet review would likely miss.

Keep the evidence separate from the recommendation. Show the mismatch, explain the consequence, and let the product owner make a controlled correction. That's what keeps an audit useful instead of turning into an undocumented edit.

Frequently Asked Questions

Yes. An XLSX file is a ZIP archive containing XML. Python’s built-in zipfile and XML tools can extract formulas, cached values, shared strings and validation rules. For complex workbook navigation or editing, a spreadsheet library may save time, but Excel is not required for a basic inspection.
No. A cached value is the result saved the last time the workbook was calculated and saved. It can be missing or stale, and it does not independently verify the formula. Recalculate the result from the inputs and rules before treating it as evidence of correctness.
Decimal represents base-ten values and lets you specify a rounding rule such as ROUND_HALF_UP. Create decimal values from strings, not floats, and reproduce the workbook’s rounding order to avoid false discrepancies around cent boundaries.
Compare the workbook with every other artifact that explains the price, including paper forms, examples and rate cards. A workbook can be internally consistent while its instructions cause people to calculate a different result. Test the documented process as a user would follow it.

Related articles