我只想打印特定列的行,假设是 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
关于Python/Excel - 使用 xlrd 进行条件单元格打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24342850/