1打开pyCharm
新建一个叫excel的python类
点击回车
2在terminal中安装xlrd
xlrd 新版本只支持 xls 格式,我这里安装的是xlrd的1.2.0,可以支持xlsx格式
pip install xlrd==1.2.0
3新建一个excel
注意:然后将文件的格式换为xls,并且版本换为97-03,然后另存到对应的安装目录下,否则会报版本不兼容的错误(xlrd.biffh.XLRDError: Excel xlsx file; not supported)
4 在excel.py中写脚本
注意:路径之中需要用\代替,否则有可能请求不到路径
import xlrd
book = xlrd.open_workbook("F:\\work\\python\\python_project\\py_project\\pythonProject4\\study\\test.xls")
# 获取表单数量
print(f"包含表单数量 {book.nsheets}")
# 获取表单名称
print(f"表单的名分别为: {book.sheet_names()}")
# 表单索引从0开始,获取第一个表单对象
book.sheet_by_index(0)
# 获取名为Sheet3的表单对象
book.sheet_by_name('Sheet3')
# 获取所有的表单对象,放入一个列表返回
book.sheets()
sheet = book.sheet_by_index(2)
print(f"表单名为:{sheet.name} ")
print(f"{sheet.name}表单索引:{sheet.number}")
print(f"{sheet.name}表单行数:{sheet.nrows}")
print(f"{sheet.name}表单列数:{sheet.ncols}")
# 行号、列号都是从0开始计算,表单A1单元格中的内容
print(f"{sheet.name}单元格A1内容是: {sheet.cell_value(rowx=0, colx=0)}")
# 表单第一行的内容
print(f"{sheet.name}第一行内容是: {sheet.row_values(rowx=0)}")
# 表单第一列的内容
print(f"{sheet.name}第一列内容是: {sheet.col_values(colx=0)}")
# 表单第四列的内容
print(f"{sheet.name}第三列内容是: {sheet.col_values(colx=3)}")
# 收入在第2行,第4列
excel = sheet.col_values(colx=3, start_rowx=1)
# 表单的总收入为
print(f"{sheet.name}收入为: {sum(excel)}")
5 学习目录
https://blog.csdn.net/baidu_28767649/article/details/124835467