为美化openpyxl表格,特设置样式,把有关参数与大家分享
from openpyxl import load_workbook
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],
]
ws.append(["Fruit", "2011", "2012", "2013", "2014"])
for row in data:
ws.append(row)
tab = Table(displayName="Table1", ref="A1:E5") #名称管理器 如E超出数据范围出错:warn("File may not be readable: column headings must be strings.")
# 'TableStyleLight11' 1-21 还有此样式 "TableStyleMedium9" 1-28 TableStyleDark1 1-11
# showFirstColumn=True,
# showLastColumn=True, showRowStripes=True, showColumnStripes=True)
# 第一行是否和样式第一行颜色一样,第二列是否···
# 是否隔行换色,是否隔列换色
style = TableStyleInfo(name='TableStyleDark11', showFirstColumn=True,
showLastColumn=True, showRowStripes=False, showColumnStripes=True)
tab.tableStyleInfo = style
ws.add_table(tab)
wb.save('d:\\s2.xlsx')
ws.append(["Fruit", "2011", "2012", "2013", "2014"])
for row in data:
ws.append(row)
tab = Table(displayName="Table2", ref="A6:E10") #名称管理器
# 'TableStyleLight11' 1-21 还有此样式 "TableStyleMedium9" 1-28 TableStyleDark1 1-11
# showFirstColumn=True,
# showLastColumn=True, showRowStripes=True, showColumnStripes=True)
# 第一行是否和样式第一行颜色一样,第二列是否···
# 是否隔行换色,是否隔列换色
style = TableStyleInfo(name='TableStyleDark11', showFirstColumn=False,
showLastColumn=True, showRowStripes=True, showColumnStripes=True)
tab.tableStyleInfo = style
ws.add_table(tab)
wb.save('d:\\s2.xlsx')
ws.append(["Fruit", "2011", "2012", "2013", "2014"])
for row in data:
ws.append(row)
tab = Table(displayName="Table3", ref="A11:E15") #名称管理器
# 'TableStyleLight11' 1-21 还有此样式 "TableStyleMedium9" 1-28 TableStyleDark1 1-11
# showFirstColumn=True,
# showLastColumn=True, showRowStripes=True, showColumnStripes=True)
# 第一行是否和样式第一行颜色一样,第二列是否···
# 是否隔行换色,是否隔列换色
style = TableStyleInfo(name='TableStyleDark11', showFirstColumn=False,
showLastColumn=True, showRowStripes=True, showColumnStripes=False)
tab.tableStyleInfo = style
ws.add_table(tab)
wb.save('d:\\s2.xlsx')
运行结果,后面是参数,T代表True,F代表Flase,分别代表与前行、列的同样样式,跳行列是否变样式
三种大类样式
‘TableStyleLight11’ 1-21 还有此样式 “TableStyleMedium9” 1-28 TableStyleDark1 1-11
分别代表浅中深三大种类,后面是编号