Inserting a table with openpyxl

Tom picture Tom · Jan 29, 2016 · Viewed 9.4k times · Source

Is there any way with openpyxl (or perhaps another library) to insert a table into an Excel worksheet? By "insert a table", I'm referring to the process outlined here, where--in Excel--one would highlight a group of cells, select the Insert tab, and click on the Table icon.

I haven't found any suitable methods in the worksheet module. I also see a table module, but I can't find any example of how to use it.

Answer

Dan Stangel picture Dan Stangel · Feb 14, 2017

Openpyxl version 2.4.0 added support for tables. However, as you noted, the documentation for tables thus far does not provide any examples.

Here is a brief example of how to create a table within a worksheet:

import openpyxl

# create a new workbook and select the active worksheet
workbook = openpyxl.Workbook()
worksheet = workbook.active

# populate some sample data    
worksheet["A1"] = "Fruit"
worksheet["B1"] = "Color"
worksheet["A2"] = "Apple"
worksheet["B2"] = "Red"
worksheet["A3"] = "Banana"
worksheet["B3"] = "Yellow"
worksheet["A4"] = "Coconut"
worksheet["B4"] = "Brown"

# define a table style
mediumStyle = openpyxl.worksheet.table.TableStyleInfo(name='TableStyleMedium2',
                                                      showRowStripes=True)
# create a table
table = openpyxl.worksheet.table.Table(ref='A1:B4',
                                       displayName='FruitColors',
                                       tableStyleInfo=mediumStyle)
# add the table to the worksheet
worksheet.add_table(table)

# save the workbook file
workbook.save('fruit.xlsx')

Note: Be sure that you have the latest version of the openpyxl library installed