0
ordered_list = [ "Mon","Tue","Wed","Thu","Fri","Sat","Sun"]

wb = Workbook('dem.xlsx')
ws = wb.add_worksheet("New Sheet")

first_row=0
for header in ordered_list:
     col=ordered_list.index(header)
     ws.write(first_row,col,header)
col=1
for j in po:
    row=ordered_list.index(j[0])
    ws.write(col,row,j[1])
    col+=1
wb.close()

I have list po = [('Mon', 6421), ('Tue', 6412), ('Wed', 12416), ('Thu', 23483), ('Fri', 8978), ('Sat', 7657), ('Sun', 6555)]. I have to print this list in Excel Sheet like

mon 6421
Tue  6412
wed  12416
 '''
 '''
Sun  6555

But I am getting like this. Can anyone help me to solve this.

   Mon  Tue Wed Thu Fri Sat Sun
  6421                      
       6412                 
           12416                
               23483            
                    8978        
                       7657 
                           6555
DavidG
  • 24,279
  • 14
  • 89
  • 82
Shravan Kumar
  • 57
  • 1
  • 1
  • 6
  • 1
    Your desired output looks... unusual. Are you sure that's what you want? – timgeb Dec 12 '17 at 11:32
  • Yup .. I want the same answer as I requested in my question. – Shravan Kumar Dec 12 '17 at 11:33
  • 3
    Ok so why are some days capitalized while others are not, even though they are all capitalized in your list of tuples? What's up with the random quotation mark before "Sun"? Why is there sometimes more than one space between day and integer value? Why do you want a weird two columns format for seven types of values? Why do you even need an excel sheet for seven trivial string-value pairs? Why not a csv file or a json dump? – timgeb Dec 12 '17 at 11:35
  • Check out [list of tuples to pandas dataframe](https://stackoverflow.com/questions/19961490/construct-pandas-dataframe-from-list-of-tuples). You can subsequently turn a dataframe into an excel worksheet. – tipanverella Dec 12 '17 at 12:14

2 Answers2

6

With the help of pandas you may get it simple.

import pandas as pd

po = [('Mon', 6421), ('Tue', 6412), ('Wed', 12416), ('Thu', 23483), ('Fri', 8978), ('Sat', 7657), ('Sun', 6555)]

# Generate dataframe from list and write to xlsx.
pd.DataFrame(po).to_excel('output.xlsx', header=False, index=False)
1

Just iterate over the po list. It already has the header field and the data field. Use enumerate() to provide the row numbers.

wb = Workbook('dem.xlsx')
ws = wb.add_worksheet("New Sheet")

po = [('Mon', 6421), ('Tue', 6412), ('Wed', 12416), ('Thu', 23483), ('Fri', 8978), ('Sat', 7657), ('Sun', 6555)]

for row, item in enumerate(po):
    ws.write_row(row, 0, item)

wb.close()

I haven't bothered to add alternating capitalisation for the day names - I don't think that you really want that.

mhawke
  • 84,695
  • 9
  • 117
  • 138