How can the xlrd module be used in Python?
To use the xlrd module, you first need to install it. You can install the xlrd module using the following command:
pip install xlrd
Once the installation is complete, you can import and use the xlrd module in your Python script. Here is a simple example:
import xlrd
# 打开Excel文件
workbook = xlrd.open_workbook('example.xlsx')
# 获取所有的工作表名字
sheet_names = workbook.sheet_names()
print(sheet_names)
# 获取第一个工作表
sheet = workbook.sheet_by_index(0)
# 获取工作表的行数和列数
num_rows = sheet.nrows
num_cols = sheet.ncols
print(f"行数:{num_rows},列数:{num_cols}")
# 获取第一行的数据
first_row = sheet.row_values(0)
print(first_row)
# 遍历每一行的数据
for row in range(num_rows):
row_data = sheet.row_values(row)
print(row_data)
In the example above, first open an Excel file using the open_workbook() function, then use the sheet_names() method to get the names of all the sheets. Next, use the sheet_by_index() method to retrieve the first sheet object, and use the nrows and ncols properties to get the number of rows and columns in the sheet. Then, use the row_values() method to get the data from the first row, and iterate through each row’s data using a loop.
This is just a basic example using the xlrd module, you can further utilize the xlrd module to read data from Excel files based on your own needs.