使用 Python 读取 Excel 文件,如何获取具有指示列名的特定列的值?
- 2025-03-20 08:47:00
- admin 原创
- 36
问题描述:
我有一个 Excel 文件:
Arm_id DSPName DSPCode HubCode PinCode PPTL
1 JaVAS 01 AGR 282001 1,2
2 JaVAS 01 AGR 282002 3,4
3 JaVAS 01 AGR 282003 5,6
我想以 的形式保存一个字符串Arm_id,DSPCode,Pincode
。此格式是可配置的,即它可能会更改为DSPCode,Arm_id,Pincode
。我将其保存在列表中,如下所示:
FORMAT = ['Arm_id', 'DSPName', 'Pincode']
鉴于可配置,我如何读取具有所提供名称的特定列的内容FORMAT
?
这是我尝试过的。目前我可以读取文件中的所有内容
from xlrd import open_workbook
wb = open_workbook('sample.xls')
for s in wb.sheets():
#print 'Sheet:',s.name
values = []
for row in range(s.nrows):
col_value = []
for col in range(s.ncols):
value = (s.cell(row,col).value)
try : value = str(int(value))
except : pass
col_value.append(value)
values.append(col_value)
print values
我的输出是:
[
[u'Arm_id', u'DSPName', u'DSPCode', u'HubCode', u'PinCode', u'PPTL'],
['1', u'JaVAS', '1', u'AGR', '282001', u'1,2'],
['2', u'JaVAS', '1', u'AGR', '282002', u'3,4'],
['3', u'JaVAS', '1', u'AGR', '282003', u'5,6']
]
然后我循环values[0]
尝试找出FORMAT
中的内容,然后获取中values[0]
的索引,然后从下一个循环中我知道所有因素的索引,从而知道我需要获取哪个值。Arm_id, DSPname and Pincode
`values[0]`FORMAT
但这是一个非常糟糕的解决方案。
如何获取 Excel 文件中具有名称的特定列的值?
解决方案 1:
答案有点晚了,但是使用 pandas,可以直接获取 excel 文件中的一列:
import pandas
df = pandas.read_excel('sample.xls')
#print the column names
print df.columns
#get the values for a given column
values = df['Arm_id'].values
#get a data frame with selected columns
FORMAT = ['Arm_id', 'DSPName', 'Pincode']
df_selected = df[FORMAT]
确保已经安装了 xlrd 和 pandas:
pip install pandas xlrd
解决方案 2:
这是一种方法:
from xlrd import open_workbook
class Arm(object):
def __init__(self, id, dsp_name, dsp_code, hub_code, pin_code, pptl):
self.id = id
self.dsp_name = dsp_name
self.dsp_code = dsp_code
self.hub_code = hub_code
self.pin_code = pin_code
self.pptl = pptl
def __str__(self):
return("Arm object:
"
" Arm_id = {0}
"
" DSPName = {1}
"
" DSPCode = {2}
"
" HubCode = {3}
"
" PinCode = {4}
"
" PPTL = {5}"
.format(self.id, self.dsp_name, self.dsp_code,
self.hub_code, self.pin_code, self.pptl))
wb = open_workbook('sample.xls')
for sheet in wb.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
items = []
rows = []
for row in range(1, number_of_rows):
values = []
for col in range(number_of_columns):
value = (sheet.cell(row,col).value)
try:
value = str(int(value))
except ValueError:
pass
finally:
values.append(value)
item = Arm(*values)
items.append(item)
for item in items:
print item
print("Accessing one single value (eg. DSPName): {0}".format(item.dsp_name))
print
您不必使用自定义类,只需采用 即可dict()
。但是,如果您使用类,则可以通过点符号访问所有值,如上所示。
以下是上述脚本的输出:
Arm object:
Arm_id = 1
DSPName = JaVAS
DSPCode = 1
HubCode = AGR
PinCode = 282001
PPTL = 1
Accessing one single value (eg. DSPName): JaVAS
Arm object:
Arm_id = 2
DSPName = JaVAS
DSPCode = 1
HubCode = AGR
PinCode = 282002
PPTL = 3
Accessing one single value (eg. DSPName): JaVAS
Arm object:
Arm_id = 3
DSPName = JaVAS
DSPCode = 1
HubCode = AGR
PinCode = 282003
PPTL = 5
Accessing one single value (eg. DSPName): JaVAS
解决方案 3:
因此,关键部分是获取标题 ( col_names = s.row(0)
),并在遍历行时跳过不需要的第一行for row in range(1, s.nrows)
- 通过使用从 1 开始的范围(而不是隐式的 0)来完成。然后,使用 zip 遍历将“name”作为列标题的行。
from xlrd import open_workbook
wb = open_workbook('Book2.xls')
values = []
for s in wb.sheets():
#print 'Sheet:',s.name
for row in range(1, s.nrows):
col_names = s.row(0)
col_value = []
for name, col in zip(col_names, range(s.ncols)):
value = (s.cell(row,col).value)
try : value = str(int(value))
except : pass
col_value.append((name.value, value))
values.append(col_value)
print values
解决方案 4:
通过使用pandas我们可以轻松读取excel。
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
DataF=pd.read_excel("Test.xlsx",sheet_name='Sheet1')
print("Column headings:")
print(DataF.columns)
测试地址:https://repl.it
参考:https://pythonspot.com/read-excel-with-pandas/
解决方案 5:
下面是读取 Excel 文件并打印第 1 列中的所有单元格(第一个单元格即标题除外)的代码:
import xlrd
file_location="C:pythonprogxxx.xlsv"
workbook=xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)
print(sheet.cell_value(0,0))
for row in range(1,sheet.nrows):
print(sheet.cell_value(row,0))
解决方案 6:
我采用的方法是从第一行读取标题信息来确定感兴趣的列的索引。
您在问题中提到您还希望将值输出到字符串。我从 FORMAT 列表动态构建输出的格式字符串。行附加到值字符串,并用换行符分隔。
输出列的顺序由 FORMAT 列表中列名的顺序决定。
在下面的代码中,FORMAT 列表中列名的大小写很重要。在上面的问题中,您的 FORMAT 列表中有“Pincode”,但 Excel 中却有“PinCode”。这在下面不起作用,它必须是“PinCode”。
from xlrd import open_workbook
wb = open_workbook('sample.xls')
FORMAT = ['Arm_id', 'DSPName', 'PinCode']
values = ""
for s in wb.sheets():
headerRow = s.row(0)
columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == firstRow[x].value]
formatString = ("%s,"*len(columnIndex))[0:-1] + "
"
for row in range(1,s.nrows):
currentRow = s.row(row)
currentRowValues = [currentRow[x].value for x in columnIndex]
values += formatString % tuple(currentRowValues)
print values
对于上面给出的示例输入,此代码输出:
>>> 1.0,JaVAS,282001.0
2.0,JaVAS,282002.0
3.0,JaVAS,282003.0
因为我是 Python 新手,所以支持:
这个答案,
这个答案,
这个问题,
这个问题
和这个答案。
解决方案 7:
我已经阅读过使用openpyxl库,
import openpyxl
from pathlib import Path
xlsx_file = Path('C:\\Users\\Amit\\Desktop\\ReadExcel', 'ReadData.xlsx')
wb_obj = openpyxl.load_workbook(xlsx_file)
# Read the active sheet:
sheet = wb_obj.active
for i in range(sheet.max_column):
print(f'i = {i}')
for row in sheet.iter_rows():
print(row[i].value)
解决方案 8:
虽然我几乎总是使用 pandas 来实现这一点,但我当前的小工具正在打包成可执行文件,而包含 pandas 则有些过头了。因此,我创建了一个poida解决方案的版本,该版本生成了一个命名元组列表。经过此更改后,他的代码将如下所示:
from xlrd import open_workbook
from collections import namedtuple
from pprint import pprint
wb = open_workbook('sample.xls')
FORMAT = ['Arm_id', 'DSPName', 'PinCode']
OneRow = namedtuple('OneRow', ' '.join(FORMAT))
all_rows = []
for s in wb.sheets():
headerRow = s.row(0)
columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == headerRow[x].value]
for row in range(1,s.nrows):
currentRow = s.row(row)
currentRowValues = [currentRow[x].value for x in columnIndex]
all_rows.append(OneRow(*currentRowValues))
pprint(all_rows)
扫码咨询,免费领取项目管理大礼包!