Python 如何使用xlrd 1.1.0版在excel中读取字体和背景色

Python 如何使用xlrd 1.1.0版在excel中读取字体和背景色,python,xlrd,Python,Xlrd,实际上我使用的是xlrd模块1.1.0版本,但我不知道如何读取单元格属性,如背景颜色、字体以及单元格是否锁定 我试着用 import xlrd book = xlrd.open_workbook("sample.xls", formatting_info=True) sheets = book.sheet_names() print "sheets are:", sheets for index, sh in enumerate(sheets): sheet = book.sheet_b

实际上我使用的是xlrd模块1.1.0版本,但我不知道如何读取单元格属性,如背景颜色、字体以及单元格是否锁定

我试着用

import xlrd
book = xlrd.open_workbook("sample.xls", formatting_info=True)
sheets = book.sheet_names()
print "sheets are:", sheets
for index, sh in enumerate(sheets):
    sheet = book.sheet_by_index(index)
    print "Sheet:", sheet.name
    rows, cols = sheet.nrows, sheet.ncols
    print "Number of rows: %s   Number of cols: %s" % (rows, cols)
    for row in range(rows):
        for col in range(cols):
            print "row, col is:", row+1, col+1,
            thecell = sheet.cell(row, col)      
            # could get 'dump', 'value', 'xf_index'
            print thecell.value,
            xfx = sheet.cell_`enter code here`xf_index(row, col)
            xf = book.xf_list[xfx]
            bgx = xf.background.pattern_colour_index
            print bgx
t引发一个错误,表示在读取wb时需要设置格式信息,但如果我有该参数,则表明它仍然没有实现

是否有其他模块,或者如何使该模块本身读取单元格属性


python xlrd提前感谢您

文档

您需要使用
xf_index
来获取
xlrd.formatting.xf
对象。然后使用各种索引从
book
对象本身获取信息。原因大多数实际样式信息(如颜色)都存储在书中。所有其他元素只有指向图书数据列表或字典的索引:

例如,
彩色地图

或者,
font\u列表

代码

我想你正在寻找这样的东西:

import xlrd


book = xlrd.open_workbook("sample.xls", formatting_info=True)

def get_front_color(xf):
    font = book.font_list[xf.font_index]
    if not font:
        return None

    return get_color(font.colour_index)


def get_back_color(xf):
    if not xf.background:
        return None

    return get_color(xf.background.background_colour_index)


def get_color(color_index):
    return book.colour_map.get(color_index)


def get_if_protected(xf):
    if not xf.protection:
        return False

    return xf.protection.cell_locked


sheets = book.sheet_names()
for index, sh in enumerate(sheets):
    sheet = book.sheet_by_index(index)
    print "Sheet:", sheet.name
    rows, cols = sheet.nrows, sheet.ncols
    for row in range(rows):
        for col in range(cols):
            c = sheet.cell(row, col)
            xf = book.xf_list[c.xf_index]

            print u'{},{}:{:>6}: FRONT: {:>20} | BACK: {:>20} | LOCKED: {}'.format(
                row, col, c.value, get_front_color(xf), get_back_color(xf), get_if_protected(xf)
            )
警告:但我不确定锁定标志。我无法完全测试它,因为我使用的是Libre Office,文档中提到了开放式Office衍生品的一些问题:

对于背景色,
xf.background.pattern\u color\u index
给了我比
xf.background.background\u color\u index
更精确的颜色(我不知道为什么,没有文档记录)