简体   繁体   English

将python代码的输出写入excel中的多行

[英]Writing the output of a python code to multiple rows in excel

I am trying to write the output of a python code in an excel sheet. 我试图在Excel工作表中编写python代码的输出。

Here's my attempt: 这是我的尝试:

import xlwt

wbk = xlwt.Workbook() 
sheet = wbk.add_sheet('pyt')
row =0 # row counter
col=0  # col counter
inputdata = [(1,2,3,4),(2,3,4,5)]
for c in inputdata:
    for d in c:
        sheet.write(row,col,d) 

        col +=1 
    row +=1
wbk.save('pyt.xls')

Result obtained:
1 2 3 4
      2 3 4 5

Desired result
row1:  1 2 3 4 
row2:  2 3 4 5

Any ideas on how to get the desired result? 关于如何获得理想结果的任何想法? thanks 谢谢

You're seeing that behaviour because you're not setting col back to zero at the end of the row. 您正在看到该行为,因为您没有在行的末尾将col设置为零。

Instead, though, you should use the built-in enumerate() which handles the incrementing for you. 相反,您应该使用内置的enumerate()来处理递增。

for row, c in enumerate(inputdata):
    for col, d in enumerate(c):
        sheet.write(row,col,d) 

row+=1之后的下一行添加col = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM