1. 程式人生 > 實用技巧 >使用 Python 匯出 Tableau 自定義形狀 (Extracting Tableau Custom Shapes Using Python)

使用 Python 匯出 Tableau 自定義形狀 (Extracting Tableau Custom Shapes Using Python)

Why

有些時候,我們收到其他人發來的 Tableau 檔案,工作簿裡面嵌入了一些自定義的形狀,但是當我們需要在新的工作簿裡面應用這些形狀圖片時,發現沒有匯出的埠,不過方法還是有的,用下面的 Python 程式碼就可以提取自定義形狀圖片了,注意請先設定好 twb 的路徑變數。希望對有需要的朋友有幫助。

方案思路: twb 檔案本身為 utf-8 編碼的 xml 檔案,而自定義形狀圖片以 base64 編碼儲存在 shapes 節點。

Code

# -*- coding: utf-8 -*-

"""Extracting Tableau Custom Shapes

NOTE: This code is only support for Tableau "*.twb" files.
      "*.twbx" file is compressed, you need save it as "*.twb" file first.
      Please input your filepath below then launch it, all my best wishes.

功能:匯出 Tableau 自定義形狀,執行前需要儲存為 twb 檔案並修改下面變數。

Contributor: MoonYear530, Stanley Hwang, 2020/9/11.
"""

from xml.etree import ElementTree as ET
from os import path
from os import makedirs
from base64 import b64decode

# Please input your filepath HERE:
twb = ET.parse("tableau_workbook.twb")

root = twb.getroot()
folder = "Extractive/"  # for Extractive Custom Shapes

for shape in root.findall("./external/shapes/shape"):
    filename = shape.attrib["name"]
    subfolder = folder + filename.split(r"/", 1)[0]

    try:
        if not path.exists(subfolder):
            makedirs(subfolder)

        img_bytes = b64decode(
            shape.text.replace(" ", "").replace(r"\n", ""))
        with open(folder + filename, "wb") as icon:
            icon.write(img_bytes)
    except Exception:
        continue

tag: Python, Tableau, How To, Image, Custom Shapes