说明:
1、通过python3中openpyxl模块,实现table表格数据写入
2、批量实现写入excel表格数据
3、调整table表格样式,通过更改数据能实现想要的样式格式
#! /usr/bin/python3
# -*- coding: utf-8 -*-
from openpyxl import Workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
class WriteTable():
def __init__(self, file_name):
self.file_name = file_name
# table表格数据写入
def write_table(self):
# 创建excel文件
wb = Workbook()
# 激活工作表并命名
sheet = wb.active
sheet.title = "2024木材价格"
# 写入表头
title_list = ("Fruit", "2011", "2012", "2013", "2014", "2015")
sheet.append(title_list)
# 批量写入表头
# title_list = (
# ("Fruit", "2011", "2012", "2013", "2014", "2015"),
# )
# for item in title_list:
# sheet.append(item)
# 批量写入数据
data = (
['Apples', 10000, 5000, 8000, 6000, 5500],
['Pears', 2000, 3000, 4000, 5000, 4500],
['Bananas', 6000, 6000, 6500, 6000, 7800],
['Oranges', 500, 300, 200, 700, 8900],
['Cheery', 1500, 700, 900, 1700, 4300],
)
for row in data:
sheet.append(row)
# 'TableStyleLight11' 1-21 另外样式 'TableStyleMedium9' 1-28 'TableStyleDark1' 1-11
tab = Table(displayName="Table1", ref="A1:F6")
style = TableStyleInfo(name="TableStyleMedium11", showFirstColumn=True,
showLastColumn=False, showRowStripes=True, showColumnStripes=True)
tab.tableStyleInfo = style
sheet.add_table(tab)
wb.save(self.file_name)
print("写入table表数据完成!!!")
if __name__ == '__main__':
# 定义变量
file_name = "fruit/2025统计木材价格表.xlsx"
html = WriteTable(file_name)
html.write_table()