Skip to main content
 首页 » 编程设计

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

2024年10月25日9unruledboy

我只想打印特定列的行,比方说 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 个黄色背景单元格的文件:

上面的代码打印:

test2 
test4