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

标签 python excel xlrd

我只想打印特定列的行,假设是 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]

现在我只想打印那些具有黄色背景的单元格值。 我找到了这个link但未能使其适应我的代码。有人可以帮我吗?

最佳答案

如果您知道黄色背景单元格的具体颜色索引,可以检查单元格样式的background.pattern_colour_index值。请注意,将 formatting_info=True 传递给 open_workbook() 非常重要:

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

示例:

对于包含 2 个黄色背景单元格的文件:

enter image description here

上面的代码打印:

test2
test4

关于Python/Excel - 使用 xlrd 进行条件单元格打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24342850/

相关文章:

python - python 在将不可变变量传递给函数时是否使用写时复制?

不使用 Django 堆栈的 Python Web 开发?

vba - 如何在每个工作表中找到一个范围并将每个范围粘贴到一个工作表中

python - 尝试使用Python选择具有红色和绿色背景的Excel单元格

Python Excel 模板读取和重写,维护公式和格式

python - scikit learn 中特征缩放的使用

vba - 压缩大量(不切实际的)基于循环的 VBA 代码;嵌套 For...Next 循环

javascript - 从目录而不是您给定的地址读取 excel 文件

python - log4cplus:调用 tkinter 文件对话框时 python 中的错误

categorical-data - 指定 patsy/statsmodels 生成的类别的名称形式 'C'