Linux环境下Python操作word

来源:互联网 发布:pc手机微信三合一源码 编辑:程序博客网 时间:2024/05/01 18:01

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")

0 0