Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python To Autofit All Columns of an Excel Sheet

Tags:

python

excel

Does anyone know of any Python --> Excel libraries that contains a method to autofit all columns within a sheet given a Excel filename?

like image 553
Shankar Kumar Avatar asked Jun 03 '14 19:06

Shankar Kumar


1 Answers

You can use pywin32 library:

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()
like image 131
NorthCat Avatar answered Sep 22 '22 23:09

NorthCat