用Python自动调整Excel表格的所有列宽

10 投票
2 回答
25438 浏览
提问于 2025-04-18 08:28

有没有人知道有什么Python到Excel的库,可以根据给定的Excel文件名,自动调整工作表中所有列的宽度?

2 个回答

-2

你可能会对 styleframe 感兴趣。

from styleframe import StyleFrame, Styler, utils

# initialize a styleframe object from a pandas dataframe.
sf2 = StyleFrame(pd_df,
                 styler_obj=Styler(horizontal_alignment='left',
                                   **other_kwrags))

# autofit widths of assigned columns and save it as a .xlsx file.
sf2.to_excel(best_fit=list(df2.columns),
             **other_kwrags)

只需要把列名(以可迭代的形式)提供给 StyleFrame.to_excel() 函数的 "best_fit" 参数就可以了。

想了解更多信息,可以查看这里: https://styleframe.readthedocs.io/en/latest/installation.html

警告: 最新的稳定版本的 pandas 已经是 2.1.1 了。但是 styleframe 在它的 setup.py 文件中需要 'pandas<2'。使用时请自行承担风险。

16

你可以使用 pywin32 这个库:

from win32com.client import Dispatch

excel = Dispatch('Excel.Application')
wb = excel.Workbooks.Open("D:\\output.xlsx")

#Activate second sheet
excel.Worksheets(2).Activate()

#Autofit column in active sheet
excel.ActiveSheet.Columns.AutoFit()

#Save changes in a new file
wb.SaveAs("D:\\output_fit.xlsx")

#Or simply save changes in a current file
#wb.Save()

wb.Close()

撰写回答