python base64转doc,doc转docx(windows和linux)
前言
由于base64无法直接转成docx格式,所以需要先转为doc。再由doc转为docx。
注意:使用python将doc转为docx在Windows中和linux中方法不同
所需包
import base64
import re
import subprocess
import pythoncom
1、base转doc
代码如下(示例):
def base64_to_word(base64_data, word_save_path):
"""
将 base64流 转为 Word
:param base64_data: base64流
:param word_save_path: Word保存路径
:return:
"""
with open(word_save_path, 'wb') as f:
f.write(base64.b64decode(base64_data))
base64_data:接收的base64流;
word_save_path:保存为doc格式word的地址
2、将doc转化为docx
2.1 linux环境
代码如下(示例):
def save_to_docx(base64str, word_save_path):
base64_to_word(base64str, word_save_path)
output = subprocess.check_output(["soffice",
"--headless",
"--invisible",
"--convert-to",
"docx",
word_save_path,
"--outdir","../data"])
base64_to_word(base64str, word_save_path):上述base转doc的方法
base64str:接收的base64流;
word_save_path:保存为doc格式word的地址
2.2 windows环境
代码如下(示例):
def win_save_to_docx(base64str,word_save_path):
base64_to_word(base64str, word_save_path)
pythoncom.CoInitialize()
from win32com import client
# 转换doc为docx
word = client.Dispatch("Word.Application") # 打开word应用程序
# for file in files:
doc = word.Documents.Open('D:\BF_GitLib\\bf_contract\{}'.format(word_save_path)) # 打开word文件
doc.SaveAs('D:\BF_GitLib\\bf_contract\{}x'.format(word_save_path), 12) # 另存为后缀为".docx"的文件,其中参数12或16指docx文件
doc.Close() # 关闭原来word文件
**注意: **
doc = word.Documents.Open(‘D:\BF_GitLib\bf_contract{}’.format(word_save_path)) doc.SaveAs(‘D:\BF_GitLib\bf_contract{}x’.format(word_save_path), 12)
这里的路径尽可能使用绝对路径,否则可能报错!
base64_to_word(base64str, word_save_path):上述base转doc的方法
base64str:接收的base64流;
word_save_path:保存为doc格式word的地址