1
votes

Assuming that I have the following code snippet and an ordered_list containing my values appended together, one row of contents which printed out on my test in this format:

[text:u'LT4974', text:u'MRNAMEID', number:14, number:121]

If I didn't enclose the row in a str() method, a different error would occur. However it will result to an output file that writes every character per column... Which is wrong. How would I correctly write it in such a way that it will only get the following contents in their respective columns?

COL1 || COL2 || COL3 || COL4

LT4974 || MRNAMEID || 14 || 121

new_workbook = xlsxwriter.Workbook()
sheet = new_workbook.add_worksheet('test')

for row_index, row in enumerate(ordered_list):
    #for col_index, cell_value in enumerate(row):
        sheet.write_row(row_index, 0, str(row))

new_workbook.save('output.xlsx')

1.) If I try uncommenting the for col_index, cell_value in enumerate(row) and change str(row) with str(cell_value) it would still write per character and this time not getting some values that falls as text.

2.) If I try to directly give row as in : sheet.write_row(row_index, 0, row) it will say an error TypeError: Unsupported type <class 'xlrd.sheet.Cell'> in write()

2

2 Answers

2
votes

you can add one more for loop to write it into different columns as needed

new_workbook = xlsxwriter.Workbook()
sheet = new_workbook.add_worksheet('test')

for row_index, row in enumerate(ordered_list):
        for col_index,item in enumerate(row):
            sheet.write_row(row_index, col_index, str(item))

new_workbook.save('output.xlsx')

kindly lemme know if this change helps you

1
votes

Found the answer, I just made some modification from Vivek's suggestion. It should be sheet.write(row_index, col_index, str(item)) instead.

new_workbook = xlsxwriter.Workbook()
sheet = new_workbook.add_worksheet('test')

for row_index, row in enumerate(ordered_list):
        for col_index,item in enumerate(row):
            sheet.write(row_index, col_index, str(item))

new_workbook.save('output.xlsx')