原文:http://www.mtools.club/content/408/
使用到了pypandoc库,请先进行安装。
pip install pypandoc
在线使用:http://www.mtools.club/tools/word/?contentid=402
案例代码:
import os
import pypandoc
def get_save_path(file_path, file_type=None):
'''
获取保存路径,若file_type为空时获取文件夹路径
:param file_path:
:param file_type:
:return:
'''
_path = os.path.splitext(file_path)[0]
if file_type:
while os.path.exists(_path + '.' + file_type):
_path = _path + '(1)'
return _path + '.' + file_type
else:
while os.path.isdir(_path):
_path = _path + '(1)'
os.makedirs(_path)
return _path
def word_to_html(file_path):
try:
outputfile = get_save_path(file_path, 'html')
pypandoc.convert_file(file_path, "html5", format="docx", extra_args=['--self-contained'], outputfile=outputfile)
return True
except Exception as e:
print("转换失败!" + str(e))
return False
if __name__ == '__main__':
word_to_html('test.docx')
效果图