In Excel, applying "Format as Table" to a range gives you more than a nicely colored table — it creates a real Table object (ListObject under the hood): columns can be renamed, filter buttons appear automatically, and you can append a totals row with SUM/AVERAGE calculations. All of it is persisted with the file and can be read back by code.
This article shows how to create a Table from scratch with Spire.XLS for Python, apply a built-in table style, rename columns, and turn on a totals row. All code runs as-is under Python 3; the sample documents are available for download at the end.
Prerequisites
pip install Spire.XLS
The imports are fixed at two lines:
from spire.xls import *
from spire.xls.common import *
The Table API lives on sheet.ListObjects: Create(name, range) builds a table, BuiltInTableStyle applies a built-in style, Columns[i] manages columns, and DisplayTotalRow controls the totals row.
Step 1: Write Data and Convert It to a Table
A Table is attached to cell data, so first write some inventory data with Spire, then convert the A1:C4 range into a table:
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
sheet = workbook.Worksheets[0]
# Write some inventory data
sheet.Range["A1"].Value = "Product"
sheet.Range["B1"].Value = "Units"
sheet.Range["C1"].Value = "Price"
data = [("Laptop", 12, 5999), ("Keyboard", 30, 199), ("Mouse", 45, 99)]
for i, (product, units, price) in enumerate(data):
sheet.Range[2 + i, 1].Value = product
sheet.Range[2 + i, 2].NumberValue = units
sheet.Range[2 + i, 3].NumberValue = price
# Convert the range to a Table (ListObject)
table = sheet.ListObjects.Create("InventoryTable", sheet.Range["A1:C4"])
workbook.SaveToFile("CreateTable.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
The first argument of Create is the table's internal name (the Name property), which must be unique within the workbook. One detail worth knowing: when a table is created, Spire also assigns a default DisplayName (such as Table1). The two are separate attributes in the XML, but the internal name is what structured references use.
The distinction between NumberValue and Value matters here: use Value for text and NumberValue for numbers, so the cells are truly numeric and the totals row calculates meaningful results.
Step 2: Apply a Built-in Table Style
A freshly created table looks plain. The TableBuiltInStyles enum mirrors Excel's built-in styles one to one (TableStyleLight1–21, TableStyleMedium1–28, TableStyleDark1–28):
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
workbook.LoadFromFile("CreateTable.xlsx")
sheet = workbook.Worksheets[0]
table = sheet.ListObjects[0]
# Apply a built-in table style
table.BuiltInTableStyle = TableBuiltInStyles.TableStyleMedium9
# Control the stripes that come with the style
table.ShowTableStyleRowStripes = True
table.ShowTableStyleColumnStripes = False
workbook.SaveToFile("StyledTable.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Row stripes (alternating shading per row) and column stripes can be toggled independently — they correspond to two checkboxes in Excel's "Table Style Options". In the saved XML you'll find <tableStyleInfo name="TableStyleMedium9" showRowStripes="1" showColumnStripes="0" />, which confirms the settings took effect.
Step 3: Rename Columns
Table column names are stored in tableColumns and are linked to the header cells — renaming a column updates the header cell too:
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
workbook.LoadFromFile("StyledTable.xlsx")
sheet = workbook.Worksheets[0]
table = sheet.ListObjects[0]
# Renaming a column also updates the header cell
table.Columns[2].Name = "Unit Price"
print(sheet.Range["C1"].Value) # Unit Price
workbook.SaveToFile("RenamedColumns.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Columns is zero-indexed, and the Name property is read-write. Open the file in Excel and you'll notice the filter button tooltips use the new name as well, because the <tableColumn name="Unit Price" /> entry in the XML has been synchronized.
Step 4: Add a Totals Row
The totals row is one of the most useful differences between a Table and a plain range. Once enabled, a row is appended below the table and each column can use a different calculation:
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
workbook.LoadFromFile("RenamedColumns.xlsx")
sheet = workbook.Worksheets[0]
table = sheet.ListObjects[0]
# Show the total row and set per-column calculations
table.DisplayTotalRow = True
table.Columns[0].TotalsCalculation = ExcelTotalsCalculation.Count
table.Columns[1].TotalsCalculation = ExcelTotalsCalculation.Sum
table.Columns[2].TotalsCalculation = ExcelTotalsCalculation.Average
workbook.CalculateAllValue()
workbook.SaveToFile("TableWithTotals.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
ExcelTotalsCalculation offers nine options: Sum, Average, Max, Min, Count, CountNums, StdDev, Var, and Custom. Spire actually generates SUBTOTAL formulas (for example =SUBTOTAL(109,B2:B4)), so the totals row responds correctly to filtering — the standard behavior of Excel table totals.
The label cell on the left of the totals row defaults to "Total"; no extra setup is needed.
Call CalculateAllValue() after setting up, otherwise the formulas are saved without cached values and some readers (including openpyxl's data_only mode) will not see any numbers.
Step 5: Read Back and Verify the Table
Finally, load the result and confirm the table structure survived the round trip:
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
workbook.LoadFromFile("TableWithTotals.xlsx")
sheet = workbook.Worksheets[0]
table = sheet.ListObjects[0]
print("Total row:", table.DisplayTotalRow)
print("Columns:", [table.Columns[i].Name for i in range(table.Columns.Count)])
print("Label cell:", sheet.Range["A5"].Formula)
print("Units total:", sheet.Range["B5"].Formula)
workbook.Dispose()
Output:
Total row: True
Columns: ['Product', 'Units', 'Unit Price']
Label cell: =SUBTOTAL(103,A2:A4)
Units total: =SUBTOTAL(109,B2:B4)
Two things to note: the totals-row label cell is itself written as a SUBTOTAL(103,...) count formula — it just displays as the count 3 in Excel, while the text label "Total" is stored separately in the totalsRowLabel of tableColumns. Also, when reading back, .Formula returns the formula itself; to get the calculated results (87 and 3), open the file in Excel, or read the cached values with openpyxl's data_only=True.
table.Columns.Count works in the read-back scenario. For verification independent of Spire, unzip the xlsx and look at xl/tables/table1.xml — the table name, range, column names, totals configuration, and style are all stored there in full.
Summary
This article walked a Table object through its full lifecycle in five pieces of code: create, style, rename columns, totals row, and read-back verification. Compared with auto-filtering (article 111) and conditional formatting (article 60), a Table's advantage is that it is a named structure — column names, totals formulas, and style settings are all persisted in xl/tables/*.xml, and what the program reads back is the same object the Excel user sees.
A few practical points:
- Table internal names must be unique within the workbook;
Createwith a duplicate name throws an exception. - Use
Valuefor text andNumberValuefor numbers; mixing them up makes the totals row calculate 0. - The totals row is really
SUBTOTALformulas and needsCalculateAllValue()to have cached values. - A worksheet can hold multiple Tables, each maintaining its own range and style.


Top comments (0)