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