DEV Community

Allen Yang
Allen Yang

Posted on

Generating a Printable Excel Sales Report from Scratch with Python

Month-end means a sales report: five products, six months of figures, totals, trends, a summary chart, and a printout on A4. Doing it by hand takes a quarter of an hour — doing it again next month takes the same quarter of an hour, because every total, every format, and the print area have to be rechecked once the numbers change.

A report with a fixed structure and monthly data is exactly what a script is good at: the numbers go in, and the styles, formulas, sparklines, chart, and print settings land on the worksheet according to written rules. This article builds such a report from an empty workbook to print-ready using Spire.XLS for Python, saving one file per step so each stage can be inspected on its own.

Setting Up the Environment

Install Spire.XLS and import the modules:

pip install Spire.XLS
Enter fullscreen mode Exit fullscreen mode
from spire.xls import *
from spire.xls.common import *
Enter fullscreen mode Exit fullscreen mode

Step One: Build the Data Skeleton

Set up the structure first: a title merged across the table, a shaded header row, five products of monthly data, and totals in both directions — a half-year total per product with SUM, and monthly totals with SUBTOTAL(9, ...):

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
workbook.Version = ExcelVersion.Version2013
workbook.CreateEmptySheets(1)
sheet = workbook.Worksheets[0]
sheet.Name = "Report"

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
products = {
    "Alpha": [128, 135, 122, 150, 168, 172],
    "Beta": [96, 88, 91, 105, 110, 118],
    "Gamma": [204, 190, 215, 232, 228, 241],
    "Delta": [56, 62, 60, 71, 75, 80],
    "Epsilon": [143, 138, 147, 155, 149, 160],
}

# Title across the whole table
sheet.Range["A1"].Text = "Monthly Sales Report - H1 2026"
sheet.Range["A1:I1"].Merge()
sheet.Range["A1"].Style.Font.IsBold = True
sheet.Range["A1"].Style.Font.Size = 14

# Header row
headers = ["Product"] + months + ["Total", "Trend"]
for c, text in enumerate(headers, start=1):
    cell = sheet.Range[2, c]
    cell.Value = text
    cell.Style.Font.IsBold = True
    cell.Style.FillPattern = ExcelPatternType.Solid
    cell.Style.KnownColor = ExcelColors.LightGreen1
    cell.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium

# One row per product, with a row total
for r, (name, values) in enumerate(products.items(), start=3):
    sheet.Range[r, 1].Value = name
    for c, value in enumerate(values):
        sheet.Range[r, c + 2].NumberValue = value
    sheet.Range[r, 8].FormulaR1C1 = "=SUM(RC[-6]:RC[-1])"

# Column totals
sheet.Range[8, 1].Value = "Total"
for c in range(2, 8):
    column = chr(ord('A') + c - 1)
    sheet.Range[8, c].Formula = f"=SUBTOTAL(9,{column}3:{column}7)"
sheet.Range[8, 8].Formula = "=SUM(H3:H7)"

workbook.CalculateAllValue()

workbook.SaveToFile("ReportData.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Three details matter here. Range["A1:I1"].Merge() spans the title over the whole table; the header style is applied in one pass through FillPattern, KnownColor, and a bottom border, which is more reliable than per-cell assignments; and the row totals use FormulaR1C1 with relative references, so the same six-column sum fits every row. CalculateAllValue() computes the totals before saving, so they are visible the moment the file opens.

Step Two: Layout and In-row Trends

With data and totals in place, three layout tasks remain: thousands separators, column widths, and freezing the first two rows. At the same time, each product gets a line sparkline carrying its half-year trend in the Trend column:

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
workbook.LoadFromFile("ReportData.xlsx")
sheet = workbook.Worksheets[0]

# Thousands separators on every number cell
sheet.Range[3, 2, 8, 8].NumberFormat = "#,##0"

# Comfortable column widths
sheet.SetColumnWidth(1, 12)
for c in range(2, 9):
    sheet.SetColumnWidth(c, 8)
sheet.SetColumnWidth(9, 14)

# Keep the title and header visible while scrolling
sheet.FreezePanes(3, 1)

# One sparkline per product, next to the row total
group = sheet.SparklineGroups.AddGroup(SparklineType.Line)
group.SparklineColor = Color.get_Blue()
group.ShowHighPoint = True
group.HighPointColor = Color.get_Green()
group.ShowLowPoint = True
group.LowPointColor = Color.get_Red()
sparklines = group.Add()
for r in range(3, 8):
    sparklines.Add(sheet.Range[r, 2, r, 7], sheet.Range[r, 9])

workbook.CalculateAllValue()

workbook.SaveToFile("ReportFormatted.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Range[3, 2, 8, 8] covers every numeric cell in both the data block and the totals row, so one statement applies the thousand-separator format. FreezePanes(3, 1) freezes the title and header rows, keeping the column names in view while scrolling. The sparkline group uses a blue line with the highest point green and the lowest red, so an unusual month shows up before anyone reads the numbers.

Step Three: Add a Summary Chart

The Total column already holds each product's half-year volume; a column chart makes it visible:

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
workbook.LoadFromFile("ReportFormatted.xlsx")
sheet = workbook.Worksheets[0]

# Column chart of the half-year total per product
chart = sheet.Charts.Add(ExcelChartType.ColumnClustered)
chart.DataRange = sheet.Range["H2:H7"]
chart.SeriesDataFromRange = False
chart.Series[0].Name = "Total"
chart.Series[0].CategoryLabels = sheet.Range["A3:A7"]
chart.ChartTitle = "Half-year Total by Product"

# Place the chart below the table
chart.TopRow = 10
chart.BottomRow = 26
chart.LeftColumn = 1
chart.RightColumn = 9

workbook.CalculateAllValue()

workbook.SaveToFile("ReportChart.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

DataRange takes H2:H7 — H2 is the "Total" header and the rest are the five totals. The category axis binds the product names and the series name is set to "Total" explicitly. The chart sits below the table, rows 10 to 26, on the same page.

Step Four: One Printable A4 Landscape Page

Nine columns with a chart underneath do not fit a portrait A4 page. The print settings fix the paper to A4 landscape, scale to one page wide, and define the print area with a repeated header row:

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
workbook.LoadFromFile("ReportChart.xlsx")
sheet = workbook.Worksheets[0]

# Print the report on one A4 landscape page
page_setup = sheet.PageSetup
page_setup.PrintArea = "A1:I27"
page_setup.PrintTitleRows = "$2:$2"
page_setup.PaperSize = PaperSizeType.PaperA4
page_setup.Orientation = PageOrientationType.Landscape
page_setup.FitToPagesWide = 1
page_setup.FitToPagesTall = 0

# Open the file in page-break preview
sheet.ViewMode = ViewMode.Preview
sheet.ZoomScalePageBreakView = 80

workbook.SaveToFile("SalesReport.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

PrintArea bounds everything from the title to the bottom of the chart, and PrintTitleRows repeats the header row on every printed page — it is spare capacity for when the data grows, since one page is enough today. FitToPagesWide = 1 with FitToPagesTall = 0 means "squeeze to one page wide, take as many pages tall as needed". The file opens straight into page-break preview, so the print boundaries can be checked immediately.

Practical Tips

  • Structure before style: merge the title and set the header first, then fill data and totals — styles stay aligned if rows are inserted later.
  • Two totals, two tools: row totals use FormulaR1C1 relative references; column totals use SUBTOTAL(9, ...), which stays correct if a filter is added later.
  • Calculate before saving: put CalculateAllValue() before SaveToFile, and totals are visible on open.
  • Format by region: number formats, column widths, and frozen panes are all region-level settings — less work and nothing gets missed.
  • Leave print headroom: PrintTitleRows and FitToPagesWide keep the report printable as the data grows.
  • Release resources: call Dispose() on each workbook when done.

Conclusion

This article took a sales report from an empty workbook to print-ready in four steps: a data skeleton built from merged titles, header styles, and totals in both directions; layout with thousand separators, column widths, frozen panes, and per-row sparklines; a column chart for the totals; and print settings with a bounded print area, repeated header, and A4 landscape scaling. Each step saved its own file — next month, swap the products dictionary for the new numbers and run it again.

Top comments (0)