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

10

有没有人知道有哪些Python --> Excel库包含一种方法,可以在给定Excel文件名的情况下自动调整工作表中的所有列的宽度?


在这种情况下,使用VBA会更自然一些吧? - MaxPowers
@MaxPowers Excel电子表格已转换为PDF文档,因此在转换之前必须完成任何操作。我找到了以下用于自适应工作表的VBA代码:Option Explicit Public Sub AutoFitSheet() If ActiveWorkbook Is Nothing Then Exit Sub Dim i# If ActiveWindow.SelectedSheets.Count > 1 Then For i = 1 To ActiveWindow.SelectedSheets.Count ActiveWindow.SelectedSheets(i).Cells.EntireColumn.AutoFit Next Else Cells.EntireColumn.AutoFit End If End Sub 我该如何将其纳入我的Python脚本中? - Shankar Kumar
抱歉,这是链接: http://www.vbaexpress.com/kb/getarticle.php?kb_id=450或者有没有一种方法可以在启动时始终启动宏? - Shankar Kumar
2个回答

14
你可以使用 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()

-2

你可能会对 styleframe 感兴趣。

from styleframe import StyleFrame, Styler, utils

sf2 = StyleFrame(<your dataframe>,styler_obj=Styler(bg_color=None, bold=False, font='Arial', font_size=10.0, font_color=None, number_format='General', protection=False, underline=None ,border_type='thin', horizontal_alignment='left', vertical_alignment='center', wrap_text=True, shrink_to_fit=True, fill_pattern_type='solid', indent=0.0, comment_author=None, comment_text=None, text_rotation=0))

sf2.to_excel(sf2,index=False,float_format='%.2f',sheet_name="Sheet1",best_fit=list(df2.columns.values))

更多信息:

https://styleframe.readthedocs.io/en/latest/installation.html


请解释你的代码,而不仅仅是粘贴答案。 - whitepanda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接