Python xlrd数据提取

2024-05-15 17:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python xlrdhttp://scienceoss.com/read-excel-files-from-python/从excel工作表中读取数据

我的问题是,如果我在excel表中读取第一个单元格为“员工姓名”的行

还有一行名为“Employee name”的第一个单元格

如何读取从第一个单元格中最后一行开始的最后一列,该行在第一个单元格中有“Employee name”

  wb = xlrd.open_workbook(file,encoding_override="cp1252") 
  wb.sheet_names()
  sh =  wb.sheet_by_index(0)
  num_of_rows = sh.nrows
  num_of_cols = sh.ncols
  valid_xl_format = 0
  invalid_xl_format = 0

  if(num_of_rows != 0):
     for i in range(num_of_rows):
        questions_dict = {}
        for j in range(num_of_cols):
              xl_data=sh.cell(i,j).value
              if ((xl_data == "Employee name")):
                  # Regardless of how many "Employee name" found in rows first cell,Read only the last "Employee name"

Tags: ofnameinformatforifshemployee
2条回答

我正在使用python xlrdhttp://scienceoss.com/read-excel-files-from-python/从excel工作表中读取数据

你需要考虑你在做什么,而不是抓取一些博客代码,留下一些完全不相关的东西,比如wb.sheet_names(),省略一些与你的需求非常相关的部分,比如first_column = sh.col_values(0)

以下是如何查找A列(第一列)中最后一个“whatever”的行索引-未测试:

import xlrd
wb = xlrd.open_workbook(file_name)
# Why do you think that you need to use encoding_overide?
sheet0 = wb.sheet_by_index(0)
tag = u"Employee name" # or u"Emp name" or ...
column_0_values = sheet0.col_values(colx=0)
try:
    max_tag_row_index = column_0_values.rindex(tag)
    print "last tag %r found at row_index %d" % (
        tag, max_tag_row_index)
except IndexError:
    print "tag %r not found" % tag

现在我们需要解释“我们如何读取从第一个单元格中最后一行开始的最后一列

假设“最后一列”是指具有列_index==sheet0.ncols-1的列,则:

last_colx = sheet0.ncols - 1
required_values = sheet0.col_values(colx=last_colx, start_rowx=max_tag_row_index)
required_cells = sheet0.col_slice(colx=last_colx, start_rowx=max_tag_row_index)
# choose one of the above 2 lines, depending on what you need to do

如果这不是你的意思(这是很可能的,因为它忽略了一大堆数据(为什么你只想读最后一列?),请试着用例子来解释你的意思。

可能需要在剩余的单元格上迭代:

for rowx in xrange(max_tag_row_index, sheet0.nrows): # or max_tag_row_index + 1
    for colx in xrange(0, sheet0.ncols):
        do_something_with_cell_object(sheet0.cell(rowx, colx))

很难确切地理解您的要求。
发布示例数据可能有助于使您的意图更加明确。

你试过反向遍历数据集吗?,例如:

for i in reversed(range(num_of_rows)):
    ...
    if xl_data == "Employee name":
        # do something 
        # then break since you've found the final "Employee Name"
        break

相关问题 更多 >