使用 Python 读取 Excel 文件,如何获取具有指示列名的特定列的值?

2025-03-20 08:47:00
admin
原创
35
摘要:问题描述:我有一个 Excel 文件:Arm_id DSPName DSPCode HubCode PinCode PPTL 1 JaVAS 01 AGR ...

问题描述:

我有一个 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)
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2482  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1533  
  PLM(产品生命周期管理)项目对于企业优化产品研发流程、提升产品质量以及增强市场竞争力具有至关重要的意义。然而,在项目推进过程中,范围蔓延是一个常见且棘手的问题,它可能导致项目进度延迟、成本超支以及质量下降等一系列不良后果。因此,有效避免PLM项目范围蔓延成为项目成功的关键因素之一。以下将详细阐述三大管控策略,助力企业...
plm系统   0  
  PLM(产品生命周期管理)项目管理在企业产品研发与管理过程中扮演着至关重要的角色。随着市场竞争的加剧和产品复杂度的提升,PLM项目面临着诸多风险。准确量化风险优先级并采取有效措施应对,是确保项目成功的关键。五维评估矩阵作为一种有效的风险评估工具,能帮助项目管理者全面、系统地评估风险,为决策提供有力支持。五维评估矩阵概述...
免费plm软件   0  
  引言PLM(产品生命周期管理)开发流程对于企业产品的全生命周期管控至关重要。它涵盖了从产品概念设计到退役的各个阶段,直接影响着产品质量、开发周期以及企业的市场竞争力。在当今快速发展的科技环境下,客户对产品质量的要求日益提高,市场竞争也愈发激烈,这就使得优化PLM开发流程成为企业的必然选择。缺陷管理工具和六西格玛方法作为...
plm产品全生命周期管理   0  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用