Skip to main content
 首页 » 编程设计

python之使用 xlwt 将 Python 列表写入 Excel 行

2024年10月17日8dyllove98

我想将 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     

请您参考如下方法:

您可以使用enumerate() 获取列表的索引。然后你可以像这样写入连续的行:

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