如何使用 xlrd 版本 1.1.0 读取 Excel 中的字体和背景颜色

ana*_*nth 4 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_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
Run Code Online (Sandbox Code Playgroud)

t 引发错误,指出在读取 wb ​​时需要设置格式信息,但如果我有该参数,则表明它仍未实现。

是否还有另一个模块或者如何使该模块本身读取单元格属性?

python xlrd 提前谢谢你

pet*_*szd 5

文档

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

colour_maphttp ://xlrd.readthedocs.io/en/latest/api.html#xlrd.book.Book.colour_map

或者font_listhttp ://xlrd.readthedocs.io/en/latest/api.html#xlrd.book.Book.font_list

代码

我想你正在寻找类似的东西:

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)
            )
Run Code Online (Sandbox Code Playgroud)

警告:不过我不确定锁定标志。我无法完全测试它,因为我使用的是 Libre Office 并且文档提到了 Open Office 衍生品的一些问题: http://xlrd.readthedocs.io/en/latest/api.html#xlrd.formatting.XFProtection