Python 读取excel指定的列

一、摘要

在这篇文章中:

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

 

posted @ 2019-07-22 18:34  肖祥  阅读(41791)  评论(0编辑  收藏  举报