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