I only know of a way to do this with COM.
import contextlib, os, win32com.client
@contextlib.contextmanager
def load_xl_file(xlfilepath):
''' Open an existing Excel file using a context manager
`xlfilepath`: path to an existing Excel file '''
xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.Workbooks.Open(xlfilepath)
try:
yield wb
finally:
wb.Close(SaveChanges=True)
xl.Quit()
xl = None # this actually ends the process
def xlautofit(xlfilepath,skip_first_col=False):
''' relies on win32com.client to autofit columns on data sheets
remember that this is using COM so sheet numbers start at 1 (not 0),
so to avoid requiring the caller to remember this, we increment
returns full path (including dir) to file '''
if os.path.splitext(xlfilepath)[1] not in ('.xls','.xlsx'):
raise
return -1
autofitbegcol = 1
if skip_first_col:
autofitbegcol += 1
# Autofit every sheet
with load_xl_file(xlfilepath) as wb:
for ws in wb.Sheets:
autofitendcol = ws.UsedRange.Columns.Count
ws.Range(ws.Cells(1, autofitbegcol),
ws.Cells(1, autofitendcol)).EntireColumn.AutoFit()
return xlfilepath