You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import pandas as pd
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
def save_to_excel(data, filename):
"""
将数据集保存为格式化的Excel文件
参数:
data - 数据集 (列表字典格式,例如:[{"列1": "值1", "列2": "值2"}, ...])
filename - 输出文件名 (需包含.xlsx扩展名)
"""
# 转换数据为DataFrame
df = pd.DataFrame(data)
# 创建Excel写入对象
with pd.ExcelWriter(filename, engine='openpyxl') as writer:
df.to_excel(writer, index=False, sheet_name='Sheet1')
# 获取工作表对象
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# 定义边框样式
thin_border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
# 设置全局行高
for row in worksheet.iter_rows():
worksheet.row_dimensions[row[0].row].height = 20
# 为所有单元格添加边框
for cell in row:
cell.border = thin_border
# 设置标题样式
header_font = Font(bold=True, size=14)
header_fill = PatternFill(start_color='ADD8E6', end_color='ADD8E6', fill_type='solid')
for cell in worksheet[1]:
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal='center', vertical='center')
# 设置数据行样式
data_font = Font(size=14)
for row in worksheet.iter_rows(min_row=2):
for cell in row:
cell.font = data_font
cell.alignment = Alignment(vertical='center', wrap_text=True)
# 设置列宽第一列固定40其他自动调整
for idx, column in enumerate(worksheet.columns):
column_letter = get_column_letter(idx + 1)
worksheet.column_dimensions[column_letter].width = 60
max_length = 0
for cell in column:
try:
value_len = len(str(cell.value))
if value_len > max_length:
max_length = value_len
except:
pass
adjusted_width = (max_length * 1.2 + 5)
worksheet.column_dimensions[column_letter].width = adjusted_width