df保存为excel

df保为excel

pandas的dataframe保存为excel,设置列宽,行高和自动换行。

python 复制代码
from openpyxl.styles import Alignment, Font
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.workbook import Workbook


def save_excel(df, filename, col_width=50, row_height=40):
    wb = Workbook()
    ws = wb.active
    # 设置表头字体为加粗
    bold_font = Font(bold=True)
    # 将DataFrame写入Excel工作表
    for r_idx, row in enumerate(dataframe_to_rows(df, index=False, header=True)):
        for c_idx, value in enumerate(row, 1):
            cell = ws.cell(row=r_idx + 1, column=c_idx, value=value)
            # 设置表头加粗
            if r_idx == 0:
                cell.font = bold_font
            # 设置单元格的换行功能
            cell.alignment = Alignment(wrap_text=True)
    # 调整列宽
    for col in ws.columns:
        column = col[0].column_letter
        ws.column_dimensions[column].width = col_width
    # 调整行高
    for row in ws.iter_rows():
        for cell in row:
            if cell.row > 1:  # 不调整第一行(表头)
                ws.row_dimensions[cell.row].height = row_height
    # 保存Excel文件
    wb.save(filename)
相关推荐
共享家95273 小时前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Hgfdsaqwr4 小时前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
一晌小贪欢5 小时前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
小文数模5 小时前
2026年美赛数学建模C题完整参考论文(含模型和代码)
python·数学建模·matlab
Halo_tjn5 小时前
基于封装的专项 知识点
java·前端·python·算法
Hgfdsaqwr5 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
weixin_395448915 小时前
export_onnx.py_0130
pytorch·python·深度学习
s1hiyu5 小时前
使用Scrapy框架构建分布式爬虫
jvm·数据库·python
2301_763472465 小时前
使用Seaborn绘制统计图形:更美更简单
jvm·数据库·python
无垠的广袤6 小时前
【VisionFive 2 Lite 单板计算机】边缘AI视觉应用部署:缺陷检测
linux·人工智能·python·opencv·开发板