Python 如何将列表转换为excel?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47771582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:22:18  来源:igfitidea点击:

How to convert list into excel?

python

提问by Shravan Kumar

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

我有列表 po = [('Mon', 6421), ('Tue', 6412), ('Wed', 12416), ('Thu', 23483), ('Fri', 8978), ('Sat' , 7657), ('Sun', 6555)]。我必须在 Excel 表中打印此列表,例如

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

回答by Vivek Harikrishnan

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)

回答by mhawke

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

只需遍历po列表。它已经有头部字段和数据字段。使用enumerate()提供的行号。

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.

我没有费心为日期名称添加交替大小写 - 我认为您不是真的想要那样。