how to convert xls to xlsx

前端 未结 14 1304
生来不讨喜
生来不讨喜 2020-11-27 03:58

I have some *.xls(excel 2003) files, and I want to convert those files into xlsx(excel 2007).

I use the uno python package, when I save the documents, I can set the

14条回答
  •  眼角桃花
    2020-11-27 04:34

    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
    

提交回复
热议问题