Python xlrd读取单元格背景色

注意:

  • 必须是xls格式

  • 读取时必须加 formatting_info=True 参数

代码

import xlrd

"""
必须是xls格式
读取时必须加 formatting_info=True 参数
"""
x1 = xlrd.open_workbook("颜色.xls", formatting_info=True)

sheet1=x1.sheet_by_index(0) # 读取第一个sheet

print("总行数:",sheet1.nrows)
print("总列数:",sheet1.ncols)

# print(dir(sheet1))

# print(x1.xf_list)
# print(len(x1.xf_list))




for row_index in range(sheet1.nrows): # 循环每一行
    for col_index in range(sheet1.ncols): # 循环每一列
        thecell = sheet1.cell(row_index,col_index)
        # 获取单元格中的数据
        print("数据:",thecell.value,end=',')
        cell_xf_index = sheet1.cell_xf_index(row_index,col_index)
        cell_xf = x1.xf_list[cell_xf_index]
        # 获取背景颜色索引
        background = cell_xf.background.pattern_colour_index 
        print("颜色索引:",background,end='\t')

    print()

原文出处:/show_1IX1U2L95KeA.html