Python openpyxl写入列表为Excel错误

我是Python新手,正在开发我的第一个项目。 我试图让我的代码从一个电子表格中复制数据列,并将其附加到当前存在于主表单中的数据。 我能够捕捉每张表中的数据,并创build一个新的主列表,将两个数据集合在一起,但是我无法将其写入文件。 当我testing打印组合列表他们看起来是正确的,但是当我添加代码将列表写入文件它被挂起。

任何援助,你可以提供将是非常有益的!

以下是我的代码。 这是我得到的错误

Traceback(最近的最后一次调用):在destSheet.cell(row = rowNum,column = 1).value = masterList1中的第50行的文件“/Path/Path/Path/extractData.py”

文件“/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/openpyxl/cell/cell.py”,行313,值为self._bind_value(value)

文件“/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/openpyxl/cell/cell.py”,第217行,在_bind_value中引发ValueError(“无法将{0}转换为Excel ” .format(值))

ValueError:无法将['Reinsurer','Market 1','Market 2','Market 3','Market 4','Market 5','Market 1','Market 2','Market 3','市场4“,”市场5“,”市场1“,”市场2“,”市场3“,”市场4“,”市场5“]到Excel

import openpyxl #Open source data file sourceFile = openpyxl.load_workbook('/Path/Path/Path/testAuth.xlsx') sourceSheet = sourceFile.get_sheet_by_name('Sheet1') #read data from source file and create lists of new data newList1 = [] newList2 = [] newList3 = [] for row in range(2, sourceSheet.get_highest_row()): data1 = sourceSheet['A' + str(row)].value newList1.append(data1) data2 = sourceSheet['B' + str(row)].value newList2.append(data2) data3 = sourceSheet['C' + str(row)].value newList3.append(data3) #open destination workbook that includes the master database destFile = openpyxl.load_workbook('/Path/Path/Path/testHist.xlsx') destSheet = destFile.get_sheet_by_name('Sheet1') #create empty lists for copying the historical data already in the workbook masterList1 = [] masterList2 = [] masterList3 = [] #grab master spreadsheet data and write to list for row in range(1, destSheet.get_highest_row()+1): masterData1 = destSheet['A'+ str(row)].value masterList1.append(masterData1) masterData2 = destSheet['B'+ str(row)].value masterList2.append(masterData2) masterData3 = destSheet['C'+ str(row)].value masterList3.append(masterData3) #append new data to the history list masterList1.append(newList1) masterList2.append(newList2) masterList3.append(newList3) #write new master list to a new file for rowNum in range(2, len(masterList1)): destSheet.cell(row=rowNum, column=1).value = masterList1 destSheet.save("updatedTest.xlsx") 

而不是将每个单元格的值分配给masterList1 ,您可能打算使用masterList1[rowNum]作为值:

 for rowNum in range(2, len(masterList1)): destSheet.cell(row=rowNum, column=1).value = masterList1[rowNum] 

另外,正如@mgrant指出的,你以前应该扩展(不附加)主列表:

 masterList1.extend(newList1) 

你有没有试过使用extend而不是appendappend将单个项目添加到列表的末尾,而extend需要一个列表参数并添加每个项目。