简体   繁体   中英

Reading Excel File using python

I have set of data in excel file containing names of users which i wanted to copy that value for a variable and run the script for example, currently i am doing something like

z = "Xyz"
Enter_Name = driver.find_element_by_xpath('//*[@id="Name"]')
Enter_Name.send_keys(Z)

where i'm copy pasting each name manually

kindly suggest a solution

So you want to read names from a spreadsheet and send each name somewhere with webdriver?

Assuming your Excel file is structured like this (ie names in the first column):

| Name  | Age | Gender |
| ----- | --- | ------ |
| Jane  | 22  | F      |
| Jim   | 45  | M      |
| Janet | 38  | F      |
import openpyxl
from openpyxl.utils import get_column_letter

def load_excel(filename, sheet_number=1, start_at_row=2):
    '''Read the contents of an excel file & return as a list'''
    contents = []
    book = openpyxl.load_workbook(filename)
    sheet = book.worksheets[sheet_number -1]
    for row_number in range(start_at_row, sheet.max_row +1):
        row_content = []
        for col_number in range(1, sheet.max_column):
            address = f'{get_column_letter(col_number)}{row_number}'
            row_content.append(sheet[address].value)
        contents.append(row_content)
    return contents

def main():
    data = load_excel('your_excel_file.xlsx')
    for row in data:
        name = row[0]
        print(name) # Use `name` to do your webdriver stuff here


if __name__ == '__main__':
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM