表格#

工作表的表格是对单元格组的引用。这使得某些操作(如样式化表中的单元格)更加容易。

创建表格#

from openpyxl import Workbook
from openpyxl.worksheet.table import Table, TableStyleInfo

wb = Workbook()
ws = wb.active

data = [
    ['Apples', 10000, 5000, 8000, 6000],
    ['Pears',   2000, 3000, 4000, 5000],
    ['Bananas', 6000, 6000, 6500, 6000],
    ['Oranges',  500,  300,  200,  700],
]

# 添加列标题。NB. 这些必须是字符串
ws.append(["Fruit", "2011", "2012", "2013", "2014"])
for row in data:
    ws.append(row)

tab = Table(displayName="Table1", ref="A1:E5")

# 添加带有条纹行和条纹列的默认样式
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
                       showLastColumn=False, showRowStripes=True, showColumnStripes=True)
tab.tableStyleInfo = style

'''
Table must be added using ws.add_table() method to avoid duplicate names.
Using this method ensures table name is unque through out defined names and all other table name. 
'''
ws.add_table(tab)
wb.save("../build/table.xlsx")
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[1], line 1
----> 1 from openpyxl import Workbook
      2 from openpyxl.worksheet.table import Table, TableStyleInfo
      4 wb = Workbook()

ModuleNotFoundError: No module named 'openpyxl'

表名在工作簿中必须是唯一的。默认情况下,创建表时,第一行有一个标题,所有列的过滤器和表标题和列标题必须始终包含字符串。

警告

在仅写模式下,您必须手动向表中添加列标题,并且值必须始终与相应单元格的值相同(参见下面的示例),否则 Excel 可能会认为文件无效并删除表。

样式是使用 TableStyleInfo 对象管理的。这允许您条纹行或列,并应用不同的配色方案。

ws.tables 是类似字典的对象,包含特定工作表中的所有表:

ws.tables
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[2], line 1
----> 1 ws.tables

NameError: name 'ws' is not defined

按名称或范围获取表#

ws.tables["Table1"] # 或者 ws.tables["A1:E5"]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 ws.tables["Table1"] # 或者 ws.tables["A1:E5"]

NameError: name 'ws' is not defined

遍历工作表中的所有表格#

for table in ws.tables.values():
    print(table)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 for table in ws.tables.values():
      2     print(table)

NameError: name 'ws' is not defined

获取工作表中所有表的表名和范围#

返回表名及其范围的列表。

ws.tables.items()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 ws.tables.items()

NameError: name 'ws' is not defined

删除表格#

del ws.tables["Table1"]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 del ws.tables["Table1"]

NameError: name 'ws' is not defined

工作表中的表格数#

len(ws.tables)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 1
----> 1 len(ws.tables)

NameError: name 'ws' is not defined

手动添加列标题#

在只写模式下,你可以只添加没有标题的表格:

table.headerRowCount = False
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[8], line 1
----> 1 table.headerRowCount = False

NameError: name 'table' is not defined

或者手动初始化列标题:

headings = ["Fruit", "2011", "2012", "2013", "2014"] # all values must be strings
table._initialise_columns()
for column, value in zip(table.tableColumns, headings):
    column.name = value
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 2
      1 headings = ["Fruit", "2011", "2012", "2013", "2014"] # all values must be strings
----> 2 table._initialise_columns()
      3 for column, value in zip(table.tableColumns, headings):
      4     column.name = value

NameError: name 'table' is not defined

过滤器#

过滤器将自动添加到包含标题行的表中。不可能在没有过滤器的情况下创建带有标题行的表格。

表格作为打印区域#

Excel 可以生成打印区域设置为表名的文档。然而,Openpyxl 不能解析这样的动态定义,并且在尝试这样做时会引发警告。

如果需要处理这个问题,可以提取表格的范围,并将打印区域定义为适当的单元格范围。

from openpyxl import load_workbook
wb = load_workbook("../build/QueryTable.xlsx")
ws = wb.active
table_range = ws.tables["InvoiceData"]
ws.print_area = table_range.ref  # Ref 是表当前覆盖的单元格范围