ReportGeneration/test_files/excel_temp.py

61 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill
from openpyxl.worksheet.table import Table, TableStyleInfo
# 创建一个新的工作簿
workbook = openpyxl.Workbook()
# 获取默认的工作表
sheet = workbook.active
sheet.title = 'Sales Data'
# 设置列宽
sheet.column_dimensions['A'].width = 20
sheet.column_dimensions['B'].width = 15
sheet.column_dimensions['C'].width = 15
sheet.column_dimensions['D'].width = 15
# 写入标题行
title_font = Font(bold=True, color="FFFFFF")
title_fill = PatternFill(start_color="0072BA", end_color="0072BA", fill_type="solid")
title_alignment = Alignment(horizontal="center", vertical="center")
title_row = ['Product', 'Sales Q1', 'Sales Q2', 'Sales Q3']
sheet.append(title_row) # 添加标题行数据
# 添加数据
data = [
('Product A', 1000, 1200, 1100),
('Product B', 800, 900, 950),
('Product C', 1100, 1000, 1200),
('Product D', 950, 1100, 1050),
]
for row in data:
sheet.append(row)
# 创建第二个工作表
sheet2 = workbook.create_sheet(title='Summary')
# 写入数据到第二个工作表
summary_data = [
('Total Sales', sum(row[1] for row in data), sum(row[2] for row in data), sum(row[3] for row in data)),
]
for row in summary_data:
sheet2.append(row)
# 创建一个Excel表格对象
table = Table(displayName="SalesTable", ref="A1:D6")
style = TableStyleInfo(name="xmlColumnPr", showFirstColumn=False,
showLastColumn=False, showRowStripes=True, showColumnStripes=True)
table.tableStyleInfo = style
# 将表格添加到工作表
sheet.add_table(table)
# 保存工作簿
workbook.save('example.xlsx')
print("Excel文件已生成")