pandas 导出 Excel 文件的时候自动列宽,自动加上边框

尝试过 xlrd、xlwt、openpyxl、xlwings、pandas 来处理 Excel,如果说除了读写 Excel,还要做数据分析,还是 pandas 最好用,大多数情况下,你根本不需要把数据插入数据库,再用 SQL 去做数据分析。

至于 pandas 怎么用,官方网站有个 10 分钟上手 pandas 的教程[1],没有体验过的可以去体验下。也可以参考 API 说明[2]

今天主要分享一段代码,可以让 pandas 导出 Excel 文件的时候自动列宽,自动加上边框,省去了手工调整的麻烦。

def to_excel_autowidth_and_border(writer, df, sheetname, startrow,startcol):
    df.to_excel(
        writer, sheet_name=sheetname, index=False, startrow=startrow, startcol=startcol
    )  # send df to writer
    workbook = writer.book
    worksheet = writer.sheets[sheetname]  # pull worksheet object
    formater = workbook.add_format({"border"1})
    for idx, col in enumerate(df):  # loop through all columns
        series = df[col]
        max_len = (
            max(
                (
                    series.astype(str).map(len).max(),  # len of largest item
                    len(str(series.name)),  # len of column name/header
                )
            )
            * 3
            + 1
        )  # adding a little extra space
        # print(max_len)
        worksheet.set_column(
            idx + startcol, idx + startcol, max_len
        )  # set column width
    first_row = startrow
    first_col = startcol
    last_row = startrow + len(df.index)
    last_col = startcol + len(df.columns)
    worksheet.conditional_format(
        first_row,
        first_col,
        last_row,
        last_col - 1,
        options={"type""formula""criteria""True""format": formater},
    )

def main():
    writer = pd.ExcelWriter("./result.xlsx")
    df = pd.read_excel(
        sheet_name=sheet_name, io="/Users/aaron/Desktop/xxxx.xlsx"
    )
    to_excel_autowidth_and_border(writer, df, sheetname="缺陷分析结果", startrow=1, startcol=1)
    writer.save()

最后的话

本文分享了如何在导出 Excel 文件的时候自动列宽,自动加上边框。如果有帮助,还请点赞、在看、转发支持。

参考资料

[1]

10 分钟上手 pandas 的教程: https://pandas.pydata.org/docs/user_guide/10min.html

[2]

API 说明: https://pandas.pydata.org/docs/reference/index.html#api



原文始发于微信公众号(Python七号):pandas 导出 Excel 文件的时候自动列宽,自动加上边框

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/39701.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!