──────────────────────────────────────

53. Work with Spreadsheets, PDFs and Images · Read and Write a Spreadsheet

Turn worksheet rows into counts that distinguish zero from a missing cell.

Lesson files · lessons/documents-and-images/read-spreadsheet-rows

Before you start
- Loop through rows of data and skip a heading row.
- Read lists from JSON with json.loads().

By the end
- Use a separate check for empty cells and zero values.
- Explain how openpyxl reads a worksheet and saves a new workbook.
- Test a sheet with a heading row and no data.

Where you can use it
Prepare a stock report from a club spreadsheet. Record a counted stock of zero and flag any supply that has yet to be counted.

In an XLSX workbook, each worksheet is a table with rows and columns. On your computer, openpyxl can open an XLSX workbook, select the sheet by name, and return its cell values one row at a time. A blank cell in these fixtures comes back as None. A zero comes back as the number 0.

Studio supplies the same kind of rows as JSON. JSON null becomes Python None. Skip the heading with rows[1:], then use is None to detect a blank count. The actual workbook lab will put the summary rows in a new sheet and save a separate XLSX output. Use literal numbers for the lab. Formula results depend on what a spreadsheet application last calculated and saved.

Predict
Which club will the example flag for a count?
- Chess only.
- Music and Chess.

Worked example (example.py)

rows = [("Club", "Kits"), ("Art", 2), ("Music", 0), ("Chess", None)]
for club, kits in rows[1:]:
    if kits is None:
        print(f"{club} - needs a count")
    else:
        print(f"{club} - {kits}")


Example result
Art - 2
Music - 0
Chess - needs a count

Read a JSON table on one line. Its first row contains Club and Kits. Each later row contains a club name and a whole number or null. Print Known: and the number of rows with a count, Kits: and the sum of those counts, then Missing: and the number of blank counts on separate lines.

Starter program (starter.py)

import json

rows = json.loads(input())
print(f"Data rows: {len(rows[1:])}")


Starter input
[["Club","Kits"],["Art",4],["Music",0],["Chess",null]]

Hint
Keep three totals. Treat the value None as missing, and add every recorded value to the kit total.

Case 1. Try the sample
Input
[["Club","Kits"],["Art",4],["Music",0],["Chess",null]]
Expected output
Known: 2
Kits: 4
Missing: 1

Case 2. Headings only
Input
[["Club","Kits"]]
Expected output
Known: 0
Kits: 0
Missing: 0

Case 3. Zero is known
Input
[["Club","Kits"],["Dance",0],["Drama",0]]
Expected output
Known: 2
Kits: 0
Missing: 0

Stretch
In the local lab, change the kit count in a fresh fixture workbook. Predict which rows in the report will change.

Reflect
What information would be lost if a blank cell and a zero both counted as missing?

Check your prediction
Chess only. Chess has a blank cell. Music has a recorded count of zero.
