How to convert xml file to xlsx format in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to convert xml file to xlsx format in python?

Is it possible to automatically convert xml file into excel xlsx format in pyton to use it with openpyxl module?

19th Nov 2017, 3:32 PM
Dimon
Dimon - avatar
1 Answer
+ 3
I've had to do this before. The main idea is to use the xlrd module to open and parse a xls file and write the content to a xlsx file using the openpyxl module. Here's my code. Attention! It cannot handle complex xls files, you should add you own parsing logic if you are going to use it. import xlrd from openpyxl.workbook import Workbook from openpyxl.reader.excel import load_workbook, InvalidFileException def open_xls_as_xlsx(filename): # first open using xlrd book = xlrd.open_workbook(filename) index = 0 nrows, ncols = 0, 0 while nrows * ncols == 0: sheet = book.sheet_by_index(index) nrows = sheet.nrows ncols = sheet.ncols index += 1 # prepare a xlsx sheet book1 = Workbook() sheet1 = book1.get_active_sheet() for row in xrange(0, nrows): for col in xrange(0, ncols): sheet1.cell(row=row, column=col).value = sheet.cell_value(row, col) return book1
20th Nov 2017, 8:59 PM
Ben
Ben - avatar