在excel中打印python脚本输出

时间:2012-11-22 09:51:27

标签: python

我想在excelfile中打印python脚本的输出。我尝试了这段代码,但它从选定的输入文件中读取每一行,然后将其写入名为output.xls的新excel文件中?谢谢

 import xlwt
 from Tkinter import *            
 from tkFileDialog   import askopenfilename      

 def callback():
     filename = askopenfilename()
     wb = xlwt.Workbook()
     ws0 = wb.add_sheet('Sheet1')

     with open(filename, 'r') as f:
         for i, line in enumerate(f):
             ws0.write(i, 0, line.strip())
     wb.save('output.xls')

 errmsg = 'Error!'
 a = Button(text='click me', command=callback)
 a.pack()
 mainloop()

2 个答案:

答案 0 :(得分:0)

如果你的意思与你正在做的相反 - 例如,从excel文件中读取行,那么你可以使用它(根据你的代码将生成的文件作为输入)

import xlrd

wb = xlrd.open_workbook('output.xls')
ws = wb.sheet_by_name('Sheet1')
for rowno in xrange(ws.nrows):
    print ws.row_values(rowno)

答案 1 :(得分:0)

import xlwt

x = (("a",1),("b",2),("c",3))

wb = xlwt.Workbook()
ws = wb.add_sheet("test")
for i, row in enumerate(x):
    for j, col in enumerate(row):
        ws.write(i, j, col)
wb.save("sample.xls")