xlrd 專注於讀取 Excel (.xls/.xlsx),提供豐富的單元格型別、合併儲存格、日期解析等資訊。本文涵蓋開啟工作簿、工作表存取、行/列/單元格讀取、型別判斷與常見坑點。
import xlrd
# 1. 開啟工作簿
wb = xlrd.open_workbook('workbook_name.xls')
# 或從記憶體 bytes
wb = xlrd.open_workbook(file_contents=data)
# 2. 取得工作表
print(wb.sheet_names()) # 列出所有表名
sh = wb.sheet_by_index(0) # 索引存取
sh = wb.sheet_by_name('Sheet1') # 名稱存取
# 3. 尺寸資訊
nrows = sh.nrows
ncols = sh.ncols
| 需求 | 方法 | 回傳 |
|---|---|---|
| 整行 | sh.row_values(rowx) | 列表 [cell0, cell1, ...] |
| 整列 | sh.col_values(colx) | 列表 |
| 單一儲存格 | sh.cell_value(rowx, colx) | Python 原生型別 (str, float, int, datetime, bool) |
| 單一儲存格 (含型別) | sh.cell(rowx, colx) | Cell 物件,.value、.ctype (0=empty,1=text,2=number,3=date,4=bool,5=error) |
# ctype == 3 (XL_CELL_DATE)
date_tuple = xlrd.xldate_as_tuple(cell.value, wb.datemode)
# datemode: 0=1900 基準, 1=1904 基準 (Mac)
dt = datetime(*date_tuple)
def import_excel(path):
wb = xlrd.open_workbook(path)
sh = wb.sheet_by_index(0)
data = []
for row_idx in range(1, sh.nrows): # 跳過標題
row = sh.row(row_idx)
record = {
'id': int(row[0].value),
'name': row[1].value.strip(),
'price': float(row[2].value),
'date': datetime(*xlrd.xldate_as_tuple(row[3].value, wb.datemode)) if row[3].ctype == 3 else None,
}
data.append(record)
return data
openpyxl。openpyxl.read_only 模式或 pandas.read_excel (chunked)。sh.merged_cells 回傳 [(rlow, rhigh, clow, chigh), ...]。