Python Openpyxl 不写入电子表格

Python Openpyxl doesn't write to spreadsheet

我正在尝试自动执行一项任务,它获取用户位置并将它们转换为纬度和经度,然后将它们写入我所做的电子表格。但它不会向电子表格写入任何内容。我也尝试添加保存,另一个 for 循环,甚至将其设置为只写,但没有成功。这是我的代码:

# Problem: Get for all locations the latitude and longitude
# Solution: loop through all of them turn them into geolocation values and write them back to spreadsheet. This is the code:

# 1. Import modules
import openpyxl

import os
import geocoder
from openpyxl.workbook import Workbook
# 2. Set up spread sheet
print('Opening workbook...')
wb = openpyxl.load_workbook('/Users/user/Downloads/plswork.xlsx', )
sheet = wb.get_sheet_by_name('results')
sheet = wb.active

# 3. Loop through all data
print('Reading rows...')

for row in range(3, sheet.max_row + 1):
    country = sheet['E' + str(row)].value
    city =  sheet['F' + str(row)].value
    both = country + ' ' + city
    print both
# 4. Convert into location
    g = geocoder.google(both)
    location = g.latlng
    print location
# 5. Write to spreadsheet 
    sheet['K' + str(row)] = str(location) 
  
print('Saving...')
wb.save('plswork.xlsx')
print('Saved..')

这是 excel 电子表格。由于个人数据,内容已被审查!

无法轻松测试,但在您发布的代码中,“5 写入电子表格”下面一行的缩进是否正确?如果正确则此行不在循环中,它只执行一次。我希望你应该缩进这一行,以便它在 for 循环中。