xlrd Python Guide: Read Excel Files
xlrd is a Python library used for reading Excel files. It can parse the data within Excel files and provides methods for accessing, manipulating, and checking the content of the Excel files.
Here are some common usage examples of the xlrd library:
- Open the Excel file:
import xlrd
# 打开Excel文件
workbook = xlrd.open_workbook('filename.xls')
- Obtain the Sheet object:
# 获取第一个Sheet
sheet = workbook.sheet_by_index(0)
# 或者通过Sheet名字获取
sheet = workbook.sheet_by_name('Sheet1')
- Fetch cell data.
# 获取第一个Sheet的A1单元格数据
cell_value = sheet.cell_value(0, 0)
# 获取第二行的所有单元格数据
row_values = sheet.row_values(1)
- Obtain the number of rows, number of columns, and the name of the sheet:
# 获取Sheet中的行数和列数
num_rows = sheet.nrows
num_cols = sheet.ncols
# 获取所有Sheet名字
sheet_names = workbook.sheet_names()
- Iterating through all rows or columns:
# 遍历所有行
for row_index in range(sheet.nrows):
row_values = sheet.row_values(row_index)
print(row_values)
# 遍历所有列
for col_index in range(sheet.ncols):
col_values = sheet.col_values(col_index)
print(col_values)
These are just some basic usage examples of the xlrd library, there are also more advanced features available for use. You can refer to the official xlrd documentation for more detailed information: https://xlrd.readthedocs.io/