簡體   English   中英

其他Excel文件中的xlrd查找Excel值

[英]xlrd lookup Excel values in other Excel file

我在玩xlrd,遇到了一些困難。 我要執行的操作的主要思想是打開一個Excel文件,將第一列的內容讀入一個數組,然后使用該數組在另一個Excel文件中進行搜索。 找到該值后,它應從第二個Excel文件返回三個單元格的內容。 我的代碼:

import xlrd
import os.path
from docx import Document

document = Document()

registry = xlrd.open_workbook('/root/Desktop/registry.xlsx')
findings = xlrd.open_workbook('/root/Desktop/findings.xlsx')

findings_sheet = findings.sheet_by_index(0)
registry_sheet = registry.sheet_by_index(0)

num_rows = findings.nrows - 1
curr_row = 0

findings_array = []

while curr_row < num_rows:
   row = findings.row(curr_row)
   findings_array += row
   curr_row += 1


for finding in findings_array:
   for r in range(first_sheet.nrows):
       cell_col1=first_sheet.cell(rowx=r,colx=0).value
       if cell_col1 == finding:

           print first_sheet.cell(r,3)
           print first_sheet.cell(r,4)
           print first_sheet.cell(r,5)
else:
    print "Finding not found"

目前不起作用。 如果我替換了if cell_col1 == finding:進入到if cell_col1 == "ABC":那么條件起作用了,但它打印出了5次細胞,這是我數組中發現的數目。

我知道我的代碼中有問題,但我不是程序員,有點卡住。

我無法運行您的代碼並以更多的pythonic風格重寫它:

import xlrd
import os.path

registry_doc = xlrd.open_workbook('/tmp/s.xlsx')
findings_doc = xlrd.open_workbook('/tmp/f.xlsx')

findings_sheet = findings_doc.sheet_by_index(0)
registry_sheet = registry_doc.sheet_by_index(0)

findings = {findings_sheet.cell_value(i, 0) for i in range(0, findings_sheet.nrows)}

for r in range(0, registry_sheet.nrows):
   cell_col1=registry_sheet.cell_value(rowx=r,colx=0)
   if cell_col1 in findings:
       print registry_sheet.cell_value(r,2)
       print registry_sheet.cell_value(r,3)
       print registry_sheet.cell_value(r,4)

它必須工作

if cell_col1 == finding:錯誤if cell_col1 == finding: 您正在比較strlist of cell

如果要將第一列的內容讀入array ,請執行以下行:

findings_array += row

應該:

findings_array += row[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM