目录

  • 预览效果:
  • API说明:
  • 基本例程
  • 总结


预览效果:

首先我们的excel是我们在前一节

【Python】生成Excel 写入内容-操作Excel、Word、CSV(1)(保姆级图文注释+测试代码+api例程) 文章中用代码生成的

python Word表格渲染 python word excel_python


python Word表格渲染 python word excel_python Word表格渲染_02


python Word表格渲染 python word excel_数据分析_03


现在我们读取excel

python Word表格渲染 python word excel_python Word表格渲染_04

API说明:

打开我们 python写入的excel.xls 文件

my_xls = xlrd.open_workbook(“python写入excel.xls”)
参数1 = xlrd.open_workbook(参数2)

  • 参数1 excel文件对象名字
  • 参数2 excel文件名字

获取sheet 数量

my_xls.nsheets
参数1.nsheets

  • 参数1 excel文件对象名字

获取 sheet 名称

my_xls.sheet_names()
参数1 .sheet_names()

  • 参数1 excel文件对象名字

根据 sheet 索引获取内容

sheet_1 = my_xls.sheet_by_index(0)
参数1 = 参数2.sheet_by_index(参数3)

  • 参数1 获取得到的sheet对象名字
  • 参数2 excel文件对象名字
  • 参数3 sheet 索引,从0开始

根据 sheet 名称获取内容

sheet = my_xls.sheet_by_name(‘成绩’)
参数1 = 参数2.sheet_by_name(参数3)

  • 参数1 获取得到的sheet对象名字
  • 参数2 excel文件对象名字
  • 参数3 sheet 名字

sheet_1.name, sheet_1.nrows, sheet_1.ncols
参数1.name 参数1.nrows 参数1.ncols

  • 参数1 获取得到的sheet对象名字
  • 分别得到这个sheet对象的名字,行数,列数

获取某个单元格的值

sheet_1.cell_value(0, 1)
参数1 .cell_value(参数2, 参数3)

  • 参数1 获取得到的sheet对象名字
  • 参数2 行(从0开始计算)
  • 参数3 列(从0开始计算)
    如下图,写入的姓名单元格A1坐标在Python中是0,0
    sheet_1.cell_value(0, 1) 这样得到了“专业”
  • python Word表格渲染 python word excel_python


获取整行或整列的值

rows = sheet_1.row_values(0) # 获取第0行内容
cols = sheet_1.col_values(1) # 获取第1列内容

  • “第0行的值为:”, rows
  • “第1列的值为:”, cols

输出第x行的内容

sheet_1.row(x)
参数1.row(参数2)

  • 参数1 获取得到的sheet对象名字
  • 参数2 指定行的索引

基本例程

# @Time    : 2022/1/11 15:44
# @Author  : 南黎
# @FileName: 1.2读取 Excel.py
# 导入 xlrd 库
import xlrd

# 打开我们 python写入的excel.xls 文件
my_xls = xlrd.open_workbook("python写入excel.xls")

# 获取并打印 sheet 数量
print( "sheet 数量:", my_xls.nsheets)

# 获取并打印 sheet 名称
print( "sheet 名称:", my_xls.sheet_names())

# 根据 sheet 索引获取内容
sheet_1 = my_xls.sheet_by_index(0)

# 根据 sheet 名称获取内容
# sheet = my_xls.sheet_by_name('成绩')

# 获取并打印该 sheet 行数和列数
print( "sheet %s 共 %d 行 %d 列" % (sheet_1.name, sheet_1.nrows, sheet_1.ncols))

# 获取并打印某个单元格的值
print( "第0行第1列的值为:", sheet_1.cell_value(0, 1))

# 获取整行或整列的值
rows = sheet_1.row_values(0) # 获取第0行内容
cols = sheet_1.col_values(1) # 获取第1列内容

# 打印获取的行列值
print( "第0行的值为:", rows)
print( "第1列的值为:", cols)

# 遍历所有表单内容
for sheet in my_xls.sheets():
    for r in range(sheet.nrows):
        # 输出指定行
        print(sheet.row(r))

总结

大家喜欢的话,给个👍,点个关注!继续跟大家分享敲代码过程中遇到的问题!


所有文件已经上传至码云

https://gitee.com/miao-zehao/python_to_-excel-and-word-and-csv/tree/master/

python Word表格渲染 python word excel_后端_06


python Word表格渲染 python word excel_开发语言_07