python模块之xlrd详解(更新中)
xlrd是什么
python的读取Excel的扩展工具,并可对Excel进行操作。
xlrd安装
pip install xlrd
xlrd获取Excel对象
通过调open_workbook方法获取Excel对象,返回Book对象,之后的操作通过该对象实现。括号中的 r 是防止引号中的字符转义的。若在同一路径下执行,可只写myexcel.xlsx(相对路径)。
# 打开xlsx文件
book = xlrd.open_workbook(r"C:\opt\myexcel.xlsx")
print(f"sheet数量{book.nsheets}")
print(f"sheet名:{book.sheet_names()}")
# 获取第一个表单对象
sheet = book.sheet_by_index(0)
# 获取sheet名为技能的表单对象
sheet = book.sheet_by_name('2018')
# 获取所有的表单对象,放入一个列表返回
sheet = book.sheets()
print(f"表单名:{sheet.name} ")
print(f"表单索引:{sheet.number}")
print(f"表单行数:{sheet.nrows}")
print(f"表单列数:{sheet.ncols}")
# 获取第3行,第2列的值,注:行号、列号都是从0开始
print(f"单元格A1内容是: {sheet.cell_value(rowx=3, colx=2)}")
# 获取第1行的所有内容,返回列表
print(f"第一行内容是: {sheet.row_values(rowx=0)}")
# 获取第1列的所有内容,返回列表
print(f"第一列内容是: {sheet.col_values(colx=0)}")
# 获取第1列的除标题外的所有内容
sheet.col_values(colx=1,start_rowx=1)