Python Openpyxl不会写入电子表格

时间:2016-08-01 03:13:30

标签: python xlsx openpyxl

我尝试自动完成一项任务,在该任务中获取用户位置并将其转换为纬度和经度并将其写入我所做的电子表格中。但它没有向电子表格写任何内容。我尝试添加另外的保存,另一个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..')

This is the excel spreadsheet. Due to personal data the content is censored!

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

1 个答案:

答案 0 :(得分:2)

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