Search code examples
pythonxlwtxlsxwriter

python how to port from xlsxwriter to xlwt


I want to recreate an xlsxwriter program in xlwt. I have issues writing a row. Can someone help me with the xlwt module? I found alot of code with xlwt using enumerate, but I am not too familiar with xlwt. The problem I have is, xlwt is writing the whole list as a string in the first cell, so I end up with one column full of data. The xlsxwriter writes each item in the list in its separate cell, which is what I want to do with xlwt. If someone can guide me in right direction, it will be greatly appreciated. thanks

this is my code:

def xlsxwriter_res(result):
    workbook = xlsxwriter.Workbook('filename.xlsx')

    for key,value in result.items():
        worksheet = workbook.add_worksheet(key)
        row, col = 0, 0

        for line in value:
            worksheet.write_row(row, col, line) ### Writes each item in list in separate cell
            row += 1

    workbook.close()


def xlwt_res(result):
    workbook = xlwt.Workbook(encoding="utf-8")

    for key,value in result.items():
        worksheet = workbook.add_sheet(key)
        row, col = 0, 0

        for line in value:
            worksheet.write(row, col, line) ### Writes the whole list as string in one cell
            row += 1

    workbook.save('filename.xls')

Solution

  • Try that:

    import xlwt
    
    
    def xlwt_res(result):
        workbook = xlwt.Workbook(encoding="utf-8")
    
        for key, value in result.items():
            worksheet = workbook.add_sheet(key)
            row = 0  # we assign 'col' later instead
    
            for line in value:
                # we're going to iterate over the line object
                # and write directly to a cell, incrementing the column id
                for col, cell in enumerate(line):
                    worksheet.write(row, col, cell)  # writes the list contents just like xlsxwriter.write_row!
                row += 1
    
        workbook.save('filename.xls')
    
    
    xlwt_res({'one': ["just one element"], 'two': ["that's a list", "did you know it"], 'three': ["let's", "have", "3"]})
    

    So both xlwt and xlsxwriter yield the same results:
    enter image description here