Rsaha
Rsaha

Reputation: 75

How to convert xls to xlsx using python?

I have tried all the methodologies from, how to convert xls to xlsx. However, none of them worked for me, probably because i am new to python and programming.

So i have come up with my own solution. Utilizing Win32com, i am able to move all the sheets from an xls file to an xlsx file. See my answer below.

I hope this will help other down the road.

Upvotes: 0

Views: 4217

Answers (1)

Rsaha
Rsaha

Reputation: 75

import win32com.client as win32
#excel = win32.DispatchEx('Excel.Application') #uses new instance of excel
excel = win32.gencache.EnsureDispatch('Excel.Application') #uses current instance of excel

#create new workbook
wb_new = excel.Workbooks.Add()
wb_new.SaveAs(r'C:\Users\new.xlsx')
wb_old=excel.Workbooks.Open(r'C:\Users\old.xls')

for sh in wb_old.Sheets:
    wb_old.Worksheets(sh.Name).Move(Before=wb_new.Worksheets("Sheet1"))

wb_new.Worksheets('Sheet1').Delete()
wb_new.Save()
#excel.Application.Quit()
del excel # ensure Excel process ends

Upvotes: 1

Related Questions