openpyxl basic search

五迷三道 提交于 2019-12-11 18:06:33

问题


I am trying to search an excel document and if the name of the mp3 file is matched in the excel document, It prints out the row the instance of the name is found on.

this is what I have:

from mutagen.easyid3 import EasyID3
from openpyxl import load_workbook
import glob
import re
import os
for name in glob.glob('*.mp3'):
  audio = EasyID3(name)
  wb = load_workbook('xl.xlsx')
  sh = wb.get_sheet_by_name('Russian')
  for row in sh:
    if row.value == name:
      print row.number

回答1:


First of all you are loading the workbook and finding the sheet for every .mp3 file. Move that code outside of the loop.

Second problem is that you try to iterate over the worksheet sh, which is not iterable.

Third problem is that you test row.value to equal name, where you probably want sh.cell[0].value

Your code should probably look more like:

from mutagen.easyid3 import EasyID3
from openpyxl import load_workbook
import glob
import re
import os
wb = load_workbook('xl.xlsx')
sh = wb.get_sheet_by_name('Russian')
for name in glob.glob('*.mp3'):
    audio = EasyID3(name)
    for row_index in range(sh.get_highest_row()):
        if sh.cell(row=row_index, column=0).value == name:
            print(row_index)

As @Bill Kidd indicated, in openpyxl 2.4.2 you'll have to replace .get_highest_row() by .max_row (no braces!).



来源:https://stackoverflow.com/questions/10939450/openpyxl-basic-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!