Python Word 转html
工作中偶尔用到word转html,实际需求更多是要转表单形式进行交互,找了下网上也没找到合适。
除了在线转,一般就PyDocx和Mammoth,这两个库。用来转换静态html,只做展示也还行。两个库对图片都是通过base64进行编码。
首先pip两个库。
pip install pydocx -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install mammoth -i https://pypi.tuna.tsinghua.edu.cn/simple
from pydocx import PyDocX
import mammoth
#PyDocx转换
html = PyDocX.to_html("test.docx")
f = open("test3.html", "w", encoding='utf-8')
f.write(html)
f.close()
#Mammoth
style_map = """
p[style-name='Section Title'] => h1:fresh
p[style-name='Subsection Title'] => h2:fresh
"""
with open("test.docx", "rb") as f:
res = mammoth.convert_to_html(f, style_map=style_map)
html2 = res.value
h = open("test4.html", "w", encoding='utf-8')
h.write(html2)
h.close()
Mammoth 可以自定义样式映射。参考github
PyDocx更多是对word文档的操作,具体的一些细节可以参考这篇文章:参考文章
原文中word的样式如图:
PyDocx转换:
Mammoth转换