【问题标题】:How to write multiple rows in column excel python?如何在列excel python中写入多行?
【发布时间】:2021-04-27 09:00:32
【问题描述】:

我的“A 列”包含酒店名称,我想在 Excel 的“B 列”中为每家酒店写“loc.address”

例如:

我使用这个代码:

import pandas as pd
from geopy.geocoders import Nominatim
import xlrd

# Give the location of the file
loc = "C:/Users/UI UX/Desktop/test.xlsx"


# To open Workbook
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

sheet.cell_value(0, 0)

for i in range(sheet.nrows):
    hotel_column = (sheet.cell_value(i, 0))
    geolocator = Nominatim(user_agent="abd")
    
    loc = geolocator.geocode(hotel_column, country_codes='', language='')
    if loc is None:
        print('Cant find latitude & longitude of this place :(')
    else:
        print("latitude is :", loc.latitude, "\nlongitude is:", loc.longitude)
        print('Location Address: ' + loc.address)
        print('---------------------------------------------------')

【问题讨论】:

  • 您需要找到并安装一些第三方模块,使您可以读写Excel文件。
  • 我只需要遍历特定列中的单元格并输入数据
  • 输入数据至少需要修改工作表的一些内存表示,无论您是否将最终结果写入文件。允许读取和写入 Excel 数据的模块应该支持这样做。
  • 不能新建一个excel文件或者覆盖现有的吗?
  • @AbdullahMd 我使用 openpyxl 发布了一个答案,可以帮助您实现更新。我注意到你重用了变量 loc 这就是我硬编码文件读取和保存的原因,但你可以修复它并使用变量

标签: python python-3.x excel xlrd geopy


【解决方案1】:

openpyxl可以更新xlsx文件

import pandas as pd
from geopy.geocoders import Nominatim
import xlrd
import openpyxl

# To open Workbook
loc = "C:/Users/UI UX/Desktop/test.xlsx"
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

sheet.cell_value(0, 0)

locs=[]
for i in range(sheet.nrows):
    hotel_column = (sheet.cell_value(i, 0))
    geolocator = Nominatim(user_agent="abd")
    
    loc = geolocator.geocode(hotel_column, country_codes='', language='')
    if loc is None:
        print('Cant find latitude & longitude of this place :(')
        locs.append('Cant find latitude & longitude of this place :(')
    else:
        print("latitude is :", loc.latitude, "\nlongitude is:", loc.longitude)
        print('Location Address: ' + loc.address)
        print('---------------------------------------------------')
        locs.append('Location Address: ' + loc.address)

xfile = openpyxl.load_workbook("C:/Users/UI UX/Desktop/test.xlsx")
sheet = xfile.worksheets[0]

for i,val in enumerate(locs):
    sheet.cell(row=i+1, column=2).value = val
xfile.save('C:/Users/UI UX/Desktop/test.xlsx')

【讨论】:

  • @Jeyvee AttributeError: 'Location' 对象没有属性 'append'
  • @AbdullahMd 方法 append 仅在 locs 中使用,这是在读取循环之前创建的列表,我只是自己尝试了代码并且无法重现错误。如果您修改了此代码,请确保 locs 被定义为列表,并且您正在向其附加字符串。
  • @Jeyvee 感谢您的回复.. 效果很好。
  • 如果我想为每家酒店打印 loc.latitude 怎么做?
  • 你可以用 "latitude is: " + str(loc.latitude) 填充列表 locs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-04
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多