[英]How to read the Font and Background color in excel using xlrd version 1.1.0
实际上,我使用的是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
对象本身获取信息。 导致大多数实际样式信息(如颜色)存储在书中。 所有其他元素仅具有指向书籍数据列表或字典的索引:
像colour_map
一样: http : colour_map
或者, font_list
: http : 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)
)
警告:虽然我不确定锁定标志。 由于我使用的是Libre Office,因此我无法完全测试它,并且文档中提到了Open Office衍生产品的一些问题: http : //xlrd.readthedocs.io/en/latest/api.html#xlrd.formatting.XFProtection
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.