2016-07-22 2 views
1

파이썬 목록의 각 값을 Excel 셀의 새 행에 쓰고 싶습니다. 목록을 생성하는 객체는 문제를 일으키는 색인 생성을 지원하지 않습니다. 내 목록에서 하나의 값만 생성하면 아무 문제가 없지만 여러 값을 생성 할 때 여러 오류가 발생합니다. 저는 64 비트 OS X와 ​​Python 2.7을 사용하는 Python 초보자입니다. 어떤 도움이라도 대단히 감사 할 것입니다.xlwt를 사용하여 Excel 행에 파이썬 목록 쓰기

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  

답변

1

enumerate()을 사용하면 목록의 색인을 얻을 수 있습니다. 그런 다음 연속 행에 쓸 수 있습니다.

for i,game in enumerate(games): 
    ws.write(i,0,str(game)) 
+1

감사합니다. – mtb2434

+0

건배, 친구. 당신에게 행복한 코딩! – bernie

관련 문제