使用 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