所以我想要做的是从字典中写入现有的excel文件:
wb = load_workbook(filename='test.xlsx')
ws2 = wb.get_sheet_by_name("Blad3")
tuple(ws2.iter_rows('A2:I1000'))
for i in ws2.iter_rows('A2:I1000'):
print str(row[0].value)
for i in Candidates:
row[0].value = i['Start Location']
row[1].value = i['Distance']
row[2].value = i['End Location']
for p in Potential_candidates:
row[4].value = p['Start Location']
row[5].value = p['Distance']
row[6].value = p['End Location']
for n in No_coords:
row[8].value = No_coords
print 'Saving to file "test.xlsx"'
wb.save('test.xlsx')
“print str(row [0] .value)”从工作表中获取正确的值,但是当我尝试设置它所说的值时: TypeError:'NoneType'对象没有属性' getitem '。
错误发生在第[0]行.value = i ['开始位置']
我一直想弄清楚为什么,或者我错过了最明显的事情,或者我完全迷失了。如果你,你不能写入单元格 可以从中读取吗?
所以我想出了NoneType错误的错误,显然列表在[0]处有一个None元素。 所以我添加了一个函数来从所有列表中删除这些元素,现在我有一个新的错误:
TypeError:'tuple'对象不支持项目分配
答案 0 :(得分:1)
所以我想出了我做错了什么,这很多,首先,我的代码试图用整个字典而不是第一个元素填充每一行。 其次row [0] =因为......原因而无效。所以我做了一个凌乱的解决方案(但是有效):
def write_excel():
wb = load_workbook(filename='test.xlsx')
ws = wb.get_sheet_by_name("Blad3")
count = 0
for row in ws.iter_rows('A2:I500'):
x = str(row[0].coordinate)
x1 = str(row[1].coordinate)
x2 = str(row[2].coordinate)
x3 = str(row[4].coordinate)
x4 = str(row[5].coordinate)
x5 = str(row[6].coordinate)
x6 = str(row[8].coordinate)
try:
Start = Candidates[count]['Start Location']
Dist = Candidates[count]['Distance']
End = Candidates[count]['End Location']
ws[x] = Start
ws[x1] = Dist
ws[x2] = End
except IndexError:
pass
try:
Pstart = Potential_candidates[count]['Start Location']
Pdist = Potential_candidates[count]['Distance']
Pend = Potential_candidates[count]['End Location']
ws[x3] = Pstart
ws[x4] = Pdist
ws[x5] = Pend
except IndexError:
pass
try:
NoCoo = No_coords[count]
ws[x6] = NoCoo
except IndexError:
pass
count=count+1
print 'Saving to file "test.xlsx"'
wb.save('test.xlsx')
我知道它可以清理很多,但它帮助我理解了什么是poopoo所以希望它可以帮助其他人:) 当我为整个程序创建更好的代码结构时,我会被清理干净。