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)
相关推荐
好家伙VCC1 天前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
前端玖耀里1 天前
如何使用python的boto库和SES发送电子邮件?
python
serve the people1 天前
python环境搭建 (十二) pydantic和pydantic-settings类型验证与解析
java·网络·python
小天源1 天前
Error 1053 Error 1067 服务“启动后立即停止” Java / Python 程序无法后台运行 windows nssm注册器下载与报错处理
开发语言·windows·python·nssm·error 1053·error 1067
喵手1 天前
Python爬虫实战:HTTP缓存系统深度实战 — ETag、Last-Modified与requests-cache完全指南(附SQLite持久化存储)!
爬虫·python·爬虫实战·http缓存·etag·零基础python爬虫教学·requests-cache
喵手1 天前
Python爬虫实战:容器化与定时调度实战 - Docker + Cron + 日志轮转 + 失败重试完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·容器化·零基础python爬虫教学·csv导出·定时调度
2601_949146531 天前
Python语音通知接口接入教程:开发者快速集成AI语音API的脚本实现
人工智能·python·语音识别
寻梦csdn1 天前
pycharm+miniconda兼容问题
ide·python·pycharm·conda
Java面试题总结1 天前
基于 Java 的 PDF 文本水印实现方案(iText7 示例)
java·python·pdf
不懒不懒1 天前
【决策树算法实战指南:从原理到Python实现】
python·决策树·id3·c4.5·catr