python - 从单元格中检索完整的富文本数据(单元格内有多种字体颜色/样式)

标签 python excel google-sheets-api xlsx xls

openpyxl只能读写一个 每个单元格的字体颜色xlwriter支持多种字体颜色,但仅用于书写而非阅读。xlwt也只是为了写作。xlwings根据他们的文档不支持富文本。xlrd显然支持根据此 thread 从单元格中读取“富文本”数据,但我无法在他们的 API 规范中找到合适的方法,并且他们的 documentation 中没有文章处理这个 AFAIK。
最重要的是,该项目是unmaintained并建议使用 openpyxl .
看来我走投无路了。
你知道是否有可能在 python 中检索 已满 来自这样一个单元格的数据:
rich-text formatted cell
特别是完整的样式数据,即沿单元格字符串使用的不同颜色和格式(粗体等)。
非常感谢您的帮助。
PS:如果您知道如何通过 Google Sheet API 使用 google sheet 来代替,那也可以为我工作。 (甚至是 .odt 格式)

最佳答案

我遇到了同样的问题。我需要在一些富文本单元格中找到红色的文本跨度。钻研openpyxl(v3.0.9)的源码后发现do parse the rich-text tags但格式为 stripped by the reader作为 content Text 的属性(property)对象用于 read_string_table 功能。
所以,我写了一个简单的补丁脚本来覆盖 read_string_table函数使得原始 Text存在格式化文本时返回对象。修改后的read_string_table功能如下。

def read_string_table(xml_source):
    """Read in all shared strings in the table.
    If a shared string has formatted snippets, the raw Text object is appended to the returned list.
    Otherwise, only the plain text content of the shared string is appended to the list.
    """
    strings = []
    STRING_TAG = '{%s}si' % SHEET_MAIN_NS
    for _, node in iterparse(xml_source):
        if node.tag == STRING_TAG:
            text_obj = Text.from_tree(node)
            if text_obj.formatted:
                text = text_obj  # return raw Text object
            else:  # original processing
                text = text_obj.content
                text = text.replace('x005F_', '')
            node.clear()
            strings.append(text)
    return strings
完整的补丁脚本可用here .您需要导入它并调用patch_read_string_table直接导入任何 openpyxl 模块之前的函数。应用此补丁后,value多信息文本单元格将是 Text包含您想要的所有样式信息的对象。
根据您的用例,这可能不是最佳解决方案,但它会向您展示格式被剥离的位置以及如何将它们取回。希望以后能提出更优雅的方案并最终合并到官方代码中。

关于python - 从单元格中检索完整的富文本数据(单元格内有多种字体颜色/样式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64594390/

相关文章:

python - Tornado 不会在主管中干净地重新启动

excel - 错误消息没有出现,尽管没有错误,并且在vba中的错误hadeler语句之前放置了退出子

excel - Xpath解释

google-api-php-client - 如何通过 Google Sheets API 更新多个单元格?

python - 如何将掩码从一个数组应用到另一个数组?

python - 消除末端未连接的线

python - 我的 python 程序运行得非常慢

Excel 排序 "mixed data"

oauth - 服务器端 Google API 服务请求产生 googleapiclient.errors.HttpError : <HttpError 404

Python 和 Google Sheets - 检查数据在哪一行