Environmental preparation
Need to download the xlrd==1.2.0
version, because xlrd is currently updated to version 2.0.1 and only supports .xls
files.
So if you need to read the .xlsx
file, you need to install the old version.
#如果之前安装过,需要卸载原先版本
pip uninstall xlrd
#下载1.2.0版本
pip install xlrd==1.2.0
Read excel
import xlrd
# 打开文件
data = xlrd.open_workbook('./36.xlsx')
View worksheet
data.sheet_names()
The return value is in list form
data.sheet_names()
print(type(data.sheet_names()))
print("sheets:" + str(data.sheet_names()))
Get the number of rows and columns
- Number of lines:
table.nrows
- Number of columns:
table.ncols
print("总行数:" + str(table.nrows))
print("总列数:" + str(table.ncols))
Get the value of the entire row and the value of the entire column
- Whole row value:
table.row_values(start,end)
- Entire column value:
table.col_values(start,end)
- Parameter
start
to start printing from the first of several for digital - Parameter
end
to print to the end position, by defaultnone
- The returned result is in list form
# 参数 start 为从第几个开始打印,
# end为打印到那个位置结束,默认为none
print("整行值:" + str(table.row_values(0)))
print("整列值:" + str(table.col_values(1)))
Get the value of a cell
For example, get the value of cell B3:
cel_B3 = table.cell(3,2).value
Routine code
# coding=utf-8
import xlrd
# 打开文件
data = xlrd.open_workbook('./36.xlsx')
# 查看工作表
data.sheet_names()
print(type(data.sheet_names()))
print("sheets:" + str(data.sheet_names()))
# 通过文件名获得工作表,获取工作表1
# table = data.sheet_by_name('工作表1')
# 打印data.sheet_names()可发现,返回的值为一个列表,通过对列表索引操作获得工作表1
# table = data.sheet_by_index(0)
# 获取行数和列数
# 行数:table.nrows
# 列数:table.ncols
print("总行数:" + str(table.nrows))
print("总列数:" + str(table.ncols))
# 获取整行的值 和整列的值,返回的结果为数组
# 整行值:table.row_values(start,end)
# 整列值:table.col_values(start,end)
# 参数 start 为从第几个开始打印,
# end为打印到那个位置结束,默认为none
print("整行值:" + str(table.row_values(0)))
print("整列值:" + str(table.col_values(1)))
# 获取某个单元格的值,例如获取B3单元格值
cel_B3 = table.cell(3,2).value
print("第三行第二列的值:" + cel_B3)
Reference article: