简体   繁体   中英

How should I grab data one by one from excel and print with loop function using python and store it in list

I have data like this in an excel sheet. Want to get the company name on the list? 在此处输入图像描述

Try this, and replace the filename and sheet name with yours:

from openpyxl import load_workbook

wb = load_workbook(filename='111.xlsx', read_only=True)

ws = wb['Sheet1']

data = []
for row in ws.rows:
    for cell in row:
        data.append(cell.value)

print(data)

Hope it helps.

First install pandas library with the below command:

➜ pip install pandas

Then running below code snippet you can print the values of Company name column row by row and add them to a list called values :

import pandas as pd

values = []
df = pd.read_excel('sample.xls', 'Sheet1')
for index, row in df.iterrows():
    company_name = row["Company Name"]
    print(company_name)
    values.append(company_name)

print(values)

Also, you can do this with xlrd but just for .xls files, So install xlrd library with the below command:

➜ pip install pandas xlrd

Then with running below code snippet you can print the values of Company name column row by row and add them to a list called values :

from xlrd import open_workbook

values = []

wb = open_workbook('<your_excel_file_name>.xls')
for sheet in wb.sheets():
    # print('Sheet:',sheet.name)
    
    for row in range(sheet.nrows):
        value  = sheet.cell(row,sheet.ncols(1)).value
        print(value)
        values.append(value)

print(values)

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