MysticCodes
MysticCodes

Reputation: 3282

Python - Write list values in xlwt

I have a list of lists in Python. I want to write individual list as a row in xlwt.

 datalist = [['India', 'Yes', '99%'], [['China', 'Yes', '89%'], ['Brazil', 'No', '90%']], ['Russia', 'Yes', '92%'], [['Germany', 'No', '97%'], ['Spain', 'No', '70%']]]

First I calculated the total number of list def count(local_list):

def listcount(lst):
  listsum = 0
  for item in lst:
    if not isinstance(l,list):
      return 1
    else:
      listsum+= listcount(item) 

  return listsum

excel_export.py

import xlwt

book = xlwt.Workbook()
sheet = book.add_sheet("PySheet1")


for rownum in range(listcount(datalist)):
  row = sheet.row(rownum)

  for index, col in enumerate(datalist):
    # do something similar like in listcount()
    # check if instance is list if not then write the value
    # rownum will act as a row
    # column value will come from list item

    row.write(row, col, val)


book.save("test.xls")

Samplesheet

enter image description here

How can I write list value in appropriate row and column?

Upvotes: 0

Views: 1503

Answers (1)

Alex Hall
Alex Hall

Reputation: 36033

It is much simpler to deal with the weird structure of the list once and for all from the beginning:

datalist = [['India', 'Yes', '99%'], [['China', 'Yes', '89%'], ['Brazil', 'No', '90%']], ['Russia', 'Yes', '92%'],
            [['Germany', 'No', '97%'], ['Spain', 'No', '70%']]]

new_datalist = []
for lst in datalist:
    if isinstance(lst[0], list):
        new_datalist.extend(lst)
    else:
        new_datalist.append(lst)
datalist = new_datalist

print(datalist)

Output:

[['India', 'Yes', '99%'], ['China', 'Yes', '89%'], ['Brazil', 'No', '90%'], ['Russia', 'Yes', '92%'], ['Germany', 'No', '97%'], ['Spain', 'No', '70%']]

Now you can write the values to the sheet in a straightforward manner. You can also get rid of listcount.

Upvotes: 1

Related Questions