这两天研究python操作word文档,因为相关的文档比较少,磕磕绊绊的各种搜索终于把我要实现的功能大体实现了,代码不多,时间主要耗费在中文乱码上。
实现的内容
打开word文档
读取表格
表格插入行
向表格中填写内容
文档另存为
环境
python 2.7
文件保存的编码格式是utf-8
代码
#模块引用
import win32com
form win32com.client import Dispatch,DispatchEx
#打开word文档
word= Dispatch("Word.Application")
word.Visiable=1
path="c:/model.docx"
doc = word.Documents.Open(FileName=path,Encoding="gbk")
#中文路径乱码问题处理
path="c:/文档.docx"
FileName=path.decode("utf8")
#读取表格
table = doc.Tables[0]
#表格插入行
table.Cell(0,0).Select()
word.Selection.InsertRowsBelow(1) #当前行的下面插入一行
#向表格中填写内容
table.Cell(0,0).Range.Text="abc"
str = "你好"
#中文写入乱码处理
table.Cell(0,1).Range.Text=str.