Linux環境下Python操作word
阿新 • • 發佈:2019-02-06
1、建立word模板(使用${ }
標識key)
2、將word模板另存為*.xml
3、python程式碼
from string import Template
#res中是需要在word中顯示的內容
res={}
res['test01']=u"測試1"
res['test02']=u"測試2"
#word模板讀入
input_file = file("/home/ubuntu/workspace/test.xml", 'r')
#生成word位置
output_file = file("/home/ubuntu/workspace/result.doc", 'w')
#將res中的內容替換word中的標籤並輸出
#實際上就是將xml以字串讀入,然後替換掉指定識別符號
s = Template(input_file.read().decode("utf-8"))
#使用安全替換,即模板中的key不存在時不報錯
output = s.safe_substitute(res)
output_file.write(output.encode("utf-8"))
output_file.close()
4、結果
注意
使用${ }
時,需要將識別符號及內容一次性輸入,否則生成xml中${test01}
會斷成幾節,如下
解決辦法:使用word開啟生成的xml檔案,選中片段,ctrl+x ctrl+v
ctrl+s
即可 Error
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
解決方法:
在程式碼中加入sys.setdefaultencoding('utf8')
或在中文字元後加.encode("utf8")