我想将Python列表中的每个值写入Excel单元格中的新行。我从中生成列表的对象不支持索引,这给了我一个问题。如果我的列表只生成一个值,那么没有问题,但是当我生成多个值时,我会遇到多个错误。我是一个使用64位OS X和Python 2.7的Python初学者。任何帮助将非常感激。
import mlbgame
month = mlbgame.games(2016, 7, 21, home ="Pirates")
games = mlbgame.combine_games(month)
for game in games:
print(game)
import xlwt
from datetime import datetime
wb = xlwt.Workbook()
ws = wb.add_sheet('PiratesG')
for game in games:
ws.write(0, 0, str(game))
#ws.write(1, 0, str(game[1]))
wb.save('Pirates.xls')
Error: Traceback (most recent call last):
File "/Users/Max/Code/PiratesGameToExcel.py", line 14, in <module>
ws.write(0, 0, str(game))
File "/usr/local/lib/python2.7/site-packages/xlwt/Worksheet.py", line 1088, in write
self.row(r).write(c, label, style)
File "/usr/local/lib/python2.7/site-packages/xlwt/Row.py", line 241, in write
StrCell(self.__idx, col, style_index, self.__parent_wb.add_str(label))
File "/usr/local/lib/python2.7/site-packages/xlwt/Row.py", line 160, in insert_cell
raise Exception(msg)
Exception: Attempt to overwrite cell: sheetname=u'PiratesG' rowx=0 colx=0
答案 0 :(得分:2)
您可以使用enumerate()
获取列表的索引。然后你可以像这样写入连续的行:
for i,game in enumerate(games):
ws.write(i,0,str(game))