python - 无法通过使用 openpyxl 的列标题读取内容
问题描述
我正在尝试使用使用openpyxl库的列标题来读取 excel 文件的内容,但我找不到这样做的任何想法。
这通常是我使用列索引(工作之一)读取项目时所做的。
from openpyxl import load_workbook
wb = load_workbook('company_info.xlsx')
ws = wb['Sheet1']
for i in range(1, ws.max_row + 1):
if ws.cell(row=i,column=1).value==None:break
print(ws.cell(row=i,column=1).value,ws.cell(row=i,column=2).value,ws.cell(row=i,column=3).value)
excel中的内容如下:
如何使用列标题阅读公司或国家/地区?
注意:我只关注与openpyxl相关的任何解决方案
解决方案
openpyxl库似乎有很多隐藏的小宝石。希望这是您所需要的。
from openpyxl import load_workbook
book = load_workbook('company_info.xlsx', data_only=True)
sheet = book.active
company_names = sheet['A']
company_id = sheet['B']
country = sheet['C']
for company in company_names:
if company.value != 'Company':
print(company.value)
# output
Amigo Foods
Atlantic Shrimpers Limited
Amawar Hiwam Co.
Austral Fishers Pyt Ltd
Alpha Group - Headquarters
for country in company_location:
if country.value != 'Country':
print(country.value)
# output
Nepal
Nigeria
Myanmar
Australia
Kenya
for id in company_id:
if id.value != 'ID':
print (id.value)
# output
ED5634
PN7809
QZ3871
TR1089
UY3090
max_column = sheet.max_column
max_row = sheet.max_row
for row in sheet.iter_rows(min_row=2, max_row=max_row, min_col=1,
max_col=max_column, values_only=True):
print (row)
# output
('Amigo Foods', 'ED5634', 'Nepal')
('Atlantic Shrimpers Limited', 'PN7809', 'Nigeria')
('Amawar Hiwam Co.', 'QZ3871', 'Myanmar')
('Austral Fishers Pyt Ltd', 'TR1089', 'Australia')
('Alpha Group - Headquarters', 'UY3090', 'Kenya')
for row in sheet.iter_rows(min_row=2, max_row=max_row, min_col=1,
max_col=max_column, values_only=True):
company_name = row[0]
company_id = row[1]
company_location = row[2]
if 'Amawar' in company_name:
print (row)
# output
('Amawar Hiwam Co.', 'QZ3871', 'Myanmar')
推荐阅读
- content-management-system - 如何在果园的 GraphQl 中关联 2 个内容项?
- python - 如何计算一个数字使用python打印了多少次?
- dataset - so_survey csv 在哪里或我如何找到它?
- firebase - 当我在 void main() 中初始化应用程序 firebase 时,它会为 web 引发一个错误,但它可以在 android 上正常工作
- google-kubernetes-engine - Fluentd 传递环境变量
- postgresql - 在函数内部,相同的查询需要 5 倍的时间 - 函数有什么问题?
- android - 我正在尝试使用 recyclerview 在屏幕上打印列表,但适配器部分中的代码不起作用
- http-status-code-404 - 发布我的 github 页面时如何修复错误 404?
- python - 如何使用 jira-python 将子任务从一个父问题移动到另一个问题
- html - 如何使具有插入边框的 div 和 div 子项完美地接触左侧和顶部垂直下降