您的位置:首页 >聚焦 >

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

2022-06-10 05:46:17    来源:程序员客栈

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

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

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

defto_excel_autowidth_and_border(writer,df,sheetname,startrow,startcol):df.to_excel(writer,sheet_name=sheetname,index=False,startrow=startrow,startcol=startcol)#senddftowriterworkbook=writer.bookworksheet=writer.sheets[sheetname]#pullworksheetobjectformater=workbook.add_format({"border":1})foridx,colinenumerate(df):#loopthroughallcolumnsseries=df[col]max_len=(max((series.astype(str).map(len).max(),#lenoflargestitemlen(str(series.name)),#lenofcolumnname/header))*3+1)#addingalittleextraspace#print(max_len)worksheet.set_column(idx+startcol,idx+startcol,max_len)#setcolumnwidthfirst_row=startrowfirst_col=startcollast_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},)defmain():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

关键词: 数据分析 手工调整 官方网站

相关阅读