如何在 Python 中获取 Excel 单元格属性 [英] How to get Excel cell properties in Python

查看:50
本文介绍了如何在 Python 中获取 Excel 单元格属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其实我用的是xlrd module 0.8版本,但是我不知道如何读取单元格属性,比如背景颜色、字体以及单元格是否被锁定.

Actually I am using xlrd module 0.8 version, but I don't know how to read cell properties like background color, font, and whether cell is locked.

我尝试使用

import xlrd
wb = xlrd.open_workbook(...)
sh = wb.sheet_by_index(...)
sh.sh._cell_xf_indexes(2, 2)

在读取wb 时,它引发了一个错误,说需要设置格式信息,但是如果我有那个参数,那么它表明它仍然没有实现.

It raises an error saying formatting information needs to be set while reading wb, but if I had that parameter then it shows it is still not implemented.

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

Is there another module or how can this module itself be made to read cell properties?

推荐答案

以下对我有用,使用 xlrd 0.7.6 版:

The following works for me, using xlrd version 0.7.6:

from xlrd import open_workbook

wb = open_workbook('tmp.xls', formatting_info=True)
sheet = wb.sheet_by_name("1")
cell = sheet.cell(6, 0)
print "cell.xf_index is", cell.xf_index
fmt = wb.xf_list[cell.xf_index]
print "type(fmt) is", type(fmt)
print
print "fmt.dump():"
fmt.dump()

fmt 是 XF 类的一个实例;见 https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html#formatting.XF-class

fmt is an instance of the XF class; see https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html#formatting.XF-class

dump() 方法打印有关格式的所有信息.下面是上面代码的输出:

The dump() method prints all the information about the format. Here's the output of the above code:

cell.xf_index is 497
type(fmt) is <class 'xlrd.formatting.XF'>

fmt.dump():
_alignment_flag: 1
_background_flag: 1
_border_flag: 1
_font_flag: 1
_format_flag: 0
_protection_flag: 0
alignment (XFAlignment object):
    hor_align: 1
    indent_level: 0
    rotation: 0
    shrink_to_fit: 0
    text_direction: 0
    text_wrapped: 0
    vert_align: 2
background (XFBackground object):
    background_colour_index: 64
    fill_pattern: 1
    pattern_colour_index: 17
border (XFBorder object):
    bottom_colour_index: 0
    bottom_line_style: 0
    diag_colour_index: 0
    diag_down: 0
    diag_line_style: 0
    diag_up: 0
    left_colour_index: 0
    left_line_style: 0
    right_colour_index: 0
    right_line_style: 0
    top_colour_index: 56
    top_line_style: 1
font_index: 72
format_key: 0
is_style: 0
lotus_123_prefix: 0
parent_style_index: 0
protection (XFProtection object):
    cell_locked: 1
    formula_hidden: 0
xf_index: 497

其中一些值是工作簿 wb 上列表的索引.例如,fmt.font_index 是 72,而 wb.font_list[72]Font 类(https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html#formatting.Font-class).

Some of those values are indices into lists on the workbook wb. For example, fmt.font_index is 72, and wb.font_list[72] is an instance of the Font class (https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html#formatting.Font-class).

这篇关于如何在 Python 中获取 Excel 单元格属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆