Search code examples
pythonpython-3.xexcelxlrdgeopy

How to write multiple rows in column excel python?


I have 'column A' contains Hotel Name, i want to write 'loc.address' for each hotel at 'column B' in excel

ex:

This should it look like

i use this code:

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('---------------------------------------------------')

Solution

  • openpyxl can update xlsx files

    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')