如何在python-docx中获取单元格背景颜色?

时间:2019-10-10 14:03:40

标签: python xml ms-word python-docx

我正在尝试使用python-docx从MS Word表读取数据。 有一种方法可以设置表格单元格的背景颜色:

tcPr = cell._tc.get_or_add_tcPr()
shd = OxmlElement("w:shd")
shd.set(qn("w:fill"), rgb2hex(*color))
tcPr.append(shd)

我的任务是相反的,我需要获取现有的颜色。我对xml不熟练,因此尝试了这一点:

cell = table.cell(row, col)
tcPr = cell._tc.get_or_add_tcPr().get(qn('w:shd'))

它如何为每个读取的单元格返回 None (无论其颜色如何)。

2 个答案:

答案 0 :(得分:1)

按照scanny的建议,我使用了解析cell._tc.xml:

- name: Hello k8s
  hosts: all
  tasks:
    - name: Create a cluster
      register: cluster
      gcp_container_cluster:
        name: thecluster
        initial_node_count: 1
        master_auth:
          username: admin
          password: TheRandomPassword
        node_config:
          machine_type: g1-small
          disk_size_gb: 10
          oauth_scopes:
            - "https://www.googleapis.com/auth/compute"
            - "https://www.googleapis.com/auth/devstorage.read_only"
            - "https://www.googleapis.com/auth/logging.write"
            - "https://www.googleapis.com/auth/monitoring"
        zone: europe-west3-c
        project:  second-network-255214 
        auth_kind: serviceaccount
        service_account_file: "{{ lookup('env', 'GOOGLE_CREDENTIALS') }}"
        state: present 
    - name: Show results
      debug: var=cluster
    - name: Create temporary file for CA
      tempfile:
        state: file
        suffix: build
      register: ca_crt
    - name: Save content to file
      copy: 
        content: "{{ cluster.masterAuth.clusterCaCertificate |b64decode }}"
        dest: "{{ ca_crt.path }}"
    - name: Create a k8s namespace
      k8s:
        host: "https://{{ cluster.endpoint }}"
        ca_cert: "{{ ca_crt.path }}"
        api_key: "{{ cluster.HOW_I_GET_THE_API_KEY}}" <<<-- Here is what I want!!!
        name: testing
        api_version: v1
        kind: Namespace
        state: present 

如果有颜色数据,则返回“自动”或背景色的十六进制代码,可以将其转换为RGB。

答案 1 :(得分:1)

正如 scanny 所说,您应该首先确定您要查找的元素/属性。

但是要读取此元素的值,您应该使用 find 方法。

例如:

cell._tc.get_or_add_tcPr().get(qn('w:shd')) #Returns None
cell._tc.get_or_add_tcPr().find(qn('w:shd')) #Returns <Element {http://schemas.openxmlformats.org/wordprocessingml/2006/main}shd at ...>