首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python xlrd 庫實現 Excel 指定列關鍵字檢索並導出

     編輯:更多程式設計知識

安裝


pip install xlrd
# 注意:xlrd 2.0+ 僅支持 .xls,.xlsx 請用 openpyxl

完整檢索腳本


import os
import xlrd
import sys

# 1. 獲取文件路徑
filename = input('輸入 Excel 文件路徑: ').strip()
if not os.path.isfile(filename):
    raise FileNotFoundError(f'{filename} 不存在')

# 2. 打開工作簿
book = xlrd.open_workbook(filename)

# 3. 選擇工作表
print('可用工作表:')
for i, name in enumerate(book.sheet_names()):
    print(f'  {i}: {name}')
sheet_idx = int(input('選擇工作表編號: '))
sheet = book.sheet_by_index(sheet_idx)
print(f'行數: {sheet.nrows}, 列數: {sheet.ncols}')

# 4. 選擇檢索列
col_idx = int(input(f'輸入檢索列號 (0-{sheet.ncols-1}): '))
while col_idx >= sheet.ncols:
    col_idx = int(input('超出範圍,重新輸入: '))

# 5. 輸入關鍵字
keyword = input('輸入檢索關鍵字: ')

# 6. 執行檢索並導出
out_file = f'{keyword}.txt'
with open(out_file, 'w', encoding='utf-8') as fout:
    for row_idx in range(sheet.nrows):
        cell_val = str(sheet.cell_value(row_idx, col_idx))
        if keyword in cell_val:
            row_data = sheet.row_values(row_idx)
            fout.write(' '.join(str(v) for v in row_data) + '\n')

print(f'完成,結果已保存至 {out_file}')

關鍵 API 說明

方法/屬性說明
book.sheet_names()所有工作表名稱列表
book.sheet_by_index(i)按索引獲取工作表
sheet.nrows / sheet.ncols行數/列數
sheet.cell_value(row, col)獲取單元格值(數值/字符串/日期浮點數)
sheet.row_values(row)獲取整行值列表

遷移提示:.xlsx 文件請用 openpyxl


import openpyxl
wb = openpyxl.load_workbook('file.xlsx')
ws = wb.active
for row in ws.iter_rows(values_only=True):
    if keyword in str(row[col_idx]):
        print(row)

總結

xlrd 處理舊版 .xls 文件簡單高效,核心流程:打開 → 選表 → 遍歷行 → 判斷列值 → 導出。新項目處理 .xlsx 請直接使用 openpyxl。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved