发布时间:2020-02-28 10:04:58编辑:admin阅读(3163)
在这篇文章中:
https://www.cnblogs.com/xiao987334176/p/9330368.html#autoid-4-5-2
介绍了使用 xlrd 模块,读取指定坐标的单元格,以及循环整个表格。
还没有介绍如何读取指定的列。
目前有一张水果报价表,内容如下:

需要提取品名和成本价,完整代码如下:
#!/usr/bin/env python3
# coding: utf-8
import xlrd
# 打开excel文件,创建一个workbook对象,book对象也就是fruits.xlsx文件,表含有sheet名
rbook = xlrd.open_workbook('test.xlsx')
# sheets方法返回对象列表,[<xlrd.sheet.Sheet object at 0x103f147f0>]
rbook.sheets()
# xls默认有3个工作簿,Sheet1,Sheet2,Sheet3
rsheet = rbook.sheet_by_index(0)  # 取第一个工作簿
# 循环工作簿的所有行
for row in rsheet.get_rows():
    product_column = row[1]  # 品名所在的列
    product_value = product_column.value  # 项目名
    if product_value != '品名':  # 排除第一行
        price_column = row[4]  # 价格所在的列
        price_value = price_column.value
        # 打印
        print("品名", product_value, "价格", price_value)
执行输出:
品名 陕西水晶富士 价格 4.1 品名 雪梨 价格 1.6 品名 无籽西瓜 价格 1.7
上一篇: Python 判断字符串是否包含中文
 51193
 50605
 41231
 38049
 32512
 29419
 28279
 23134
 23093
 21428
 1485°
 2199°
 1823°
 1750°
 2063°
 1812°
 2495°
 4191°
 4050°
 2892°