Python / Excel - 用xlrd进行条件单元格打印

2 投票
1 回答
2103 浏览
提问于 2025-04-18 10:37

我想只打印特定列的行,比如说B列,到目前为止都还不错:

import xlrd
file_location = "/home/myuser/excel.xls"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]

for r in data:
    print r[1]

现在我想只打印那些背景是黄色的单元格的值。我找到这个链接,但没能把它适应到我的代码里。有人能帮我一下吗?

1 个回答

2

如果你知道那些背景是黄色的单元格的具体颜色索引,你可以查看单元格样式的 background.pattern_colour_index 值。需要注意的是,在使用 open_workbook() 时,一定要传入 formatting_info=True 这个参数:

import xlrd

file_location = "/home/myuser/excel.xls"
workbook = xlrd.open_workbook(file_location, formatting_info=True)
sheet = workbook.sheet_by_index(0)

for row in range(sheet.nrows):
    cell = sheet.cell(row, 1)
    style = workbook.xf_list[cell.xf_index]
    color = style.background.pattern_colour_index
    if color == 43:  # on of yellows
        print cell.value

举个例子:

假设有一个文件里面有两个背景是黄色的单元格:

在这里输入图片描述

上面的代码会输出:

test2
test4

撰写回答