通过关键字查询excel表中匹配的内容

通过关键字查询excel表中匹配的内容,可指定表单名和查询列序号,输出结果为匹配行全部内容或对指定单元格进行拼接。

import re
import xlrd3 as xlrd

# 查询关键字
keywords = '我是关键字'
# 表文件名称
filename = '我是文件名.xls'
# 表单索引号
shtindex = 0
# 查询列序号
colindex = 2

# 模糊查询excel中的匹配行
def fuzzy_search_excel(file_name, sheet_index, column_index, query_word):
    workbook = xlrd.open_workbook(file_name)
    sheet = workbook.sheet_by_index(sheet_index)
    results = []
    for row_idx in range(sheet.nrows):
        cell_self = sheet.cell_value(row_idx, column_index)
        # 输出匹配行全部内容
        #row_data = sheet.row_values(row_idx)
        #if isinstance(cell_self, str) and re.search(query_word, cell_self, re.IGNORECASE):
        #    results.append((row_idx, row_data))
        # 输出匹配行指定列的内容并进行拼接
        cell_data1 = sheet.cell_value(row_idx, column_index + 1)
        cell_data2 = sheet.cell_value(row_idx, column_index - 2)
        if isinstance(cell_self, str) and re.search(query_word, cell_self, re.IGNORECASE):
            results.append((row_idx, cell_data1[0:cell_data1.rfind('/', 0)] + '/' + cell_data2))
    return results

results = fuzzy_search_excel(filename, shtindex, colindex, keywords)
for result in results:
    print(result)

原创文章禁止转载:技术学堂 » 通过关键字查询excel表中匹配的内容

精彩评论

9+7=

感谢您的支持与鼓励

支付宝扫一扫打赏

微信扫一扫打赏