2

私はpython xlrd http://scienceoss.com/read-excel-files-from-python/を使用してExcelシートからデータを読み取ります

私の質問は、Excelシートで最初のセルが「従業員名」の行を読んだかどうかです

そして、最初のセルが「従業員名」であるという名前の別の行があります

最初のセルに「従業員名」が含まれる最後の行から始まる最後の列をどのように読み取ることができますか.前を無視する

  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"
4

2 に答える 2

5

私はpython xlrd http://scienceoss.com/read-excel-files-from-python/を使用してExcelシートからデータを読み取ります

wb.sheet_names()いくつかのブログ コードを取得して、 のようなまったく関係のないものを残したり、要件に非常に関連する部分を省略したりするのではなく、自分が何をしているのかを考える必要がありますfirst_column = sh.col_values(0)

列A(最初の列)の最後の「何でも」のrow_indexを見つける方法は次のとおりです-未テスト:

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

ここで、「最初のセルに「従業員名」が含まれる最後の行から始まる最後の列をどのように読み取ることができるか」を解釈する必要があります。

「最後の列」が column_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))
于 2010-09-23T10:16:45.967 に答える
0

あなたが何を求めているのかを正確に理解するのは難しいです。
サンプルデータを投稿すると、意図がより明確になる場合があります。

データセットを逆に繰り返してみましたか?例:

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
于 2010-09-23T05:54:46.070 に答える