工作表¶
工作表是对单元格组的引用。这使得某些操作(如为表中的单元格设置样式)变得更容易。
创建表格¶
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],
]
# add column headings. NB. these must be strings
ws.append(["Fruit", "2011", "2012", "2013", "2014"])
for row in data:
ws.append(row)
tab = Table(displayName="Table1", ref="A1:E5")
# Add a default style with striped rows and banded columns
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("table.xlsx")
表名在工作簿中必须唯一。默认情况下,表是从第一行创建的,所有列的筛选器、表标题和列标题必须始终包含字符串。
警告
在只写模式下,必须手动将列标题添加到表中,并且这些值必须始终与相应单元格的值相同(请参阅下面的示例以了解如何执行此操作),否则Excel可能会认为文件无效并删除表。
样式是使用 TableStyleInfo 对象。这允许您对行或列进行条纹处理,并应用不同的颜色方案。
使用表格¶
ws.tables
是特定工作表中所有表的类似字典的对象:
>>> ws.tables
{"Table1", <openpyxl.worksheet.table.Table object>}
按名称或范围获取表¶
>>> ws.tables["Table1"]
or
>>> ws.tables["A1:D10"]
迭代工作表中的所有表¶
>>> for table in ws.tables.values():
>>> print(table)
获取工作表中所有表的表名和范围¶
返回表名及其范围的列表。
>>> ws.tables.items()
>>> [("Table1", "A1:D10")]
删除表¶
>>> del ws.tables["Table1"]
工作表中的表数¶
>>> len(ws.tables)
>>> 1
手动添加列标题¶
在只写模式下,只能添加没有标题的表:
>>> table.headerRowCount = False
或手动初始化列标题:
>>> 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