Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a table with openpyxl

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.

like image 501
Tom Avatar asked Jan 28 '16 23:01

Tom


2 Answers

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

like image 51
Dan Stangel Avatar answered Sep 28 '22 12:09

Dan Stangel


openpyxl currently does not support table styles. You might want to look at using Xlsxwriter if you need this. See https://xlsxwriter.readthedocs.org/en/latest/working_with_tables.html

like image 30
Charlie Clark Avatar answered Sep 28 '22 13:09

Charlie Clark