本文目录一览:
- 1、我想用Python操作word,网上看了些代码,但自己的老是报错,求高手看看!!!
- 2、python word文件处理
- 3、python怎么在word表中插图片?
- 4、python操作word,关于win32com
- 5、python处理word文档
我想用Python操作word,网上看了些代码,但自己的老是报错,求高手看看!!!
看了一下应该是没有自动创建constants变量,constants是空的
先运行语句:
win32com.client.gencache.EnsureDispatch('Word.Application')
应该就可以了
或者运行pythonwin菜单栏选择Tools——Com MakePy Utility然后在弹出的窗口中选择Microsoft Word x.y Object Library 点击OK就可以了
或者直接运行client文件夹下的makepy.py文件同样选择Microsoft Word 也可以
python word文件处理
#-*- encoding: utf8 -*-
import win32com
from win32com.client import Dispatch, constants
import win32com.client
import __main__
import os
import new
import sys
import re
import string
reload(sys)
sys.setdefaultencoding('utf8')
#from fileinput import filename
class Word(object):
#初始化word对象
def __init__(self, uri):
self.objectword(uri)
#创建word对象
def objectword(self,url):
self.word = win32com.client.Dispatch('Word.Application')
self.word.Visible = 0
self.word.DisplayAlerts = 0
self.docx = self.word.Documents.Open(url)
self.wrange = self.docx.Range(0, 0)
#关闭word
def close(self):
self.word.Documents.Close()
self.word.Quit()
#创建word
def create(self):
pass
#在word中进行查找
def findword(self, key):
question = []
uri = r'E:/XE/ctb.docx'
self.objectword(uri)
#读取所有的word文档内容
range = self.docx.Range(self.docx.Content.Start,self.docx.Content.End)
question = str(range).split("")
#查找内容
#question = re.split(r"(/r[1][0-9][0-9]+.)",str(range))
#l = question[0].split("/d+.")
for questionLine in question:
questionLine = questionLine.strip('/n')
l = re.split(r"([1][0-9][0-9]+.)",questionLine)
del l[0]
for t in l:
s = str(key[0:3])
if str(t).find(s) -1:
#插入
g = string.join(l)
print g.encode('gb2312')
#print g.decode("")
self.insertword(g)
print "sss"
else:
print "ttt"
#插入word
def insertword(self,w):
url = r'E:/XE/ctb.doc'
self.objectword(url)
self.wrange.InsertAfter(w)
pass
#读取数据源
def source(self, src):
f = open(src)
d = f.readlines()
for l in d:
name, question01, question02, question03, question04, question05 = tuple(l.decode('utf8').split('/t'))
if question01 != u'全对':
#self.wrange.InsertAfter(name)
self.findword(question01)
return self
Word(r'E:/XE/xx.docx').source(r'E:/XE/xe.txt').close()
python怎么在word表中插图片?
# -*- coding: UTF8 -*-from docx import Documentfrom docx.shared import Pt doc = Document() # 文件存储路径path = "C://Users//Administrator//Desktop//word文档//" # 读取文档# doc = Document(path + "hello.docx") # 添加图片,后面的参数设置图片尺寸,可以选填doc.add_picture(path + 'cat.jpg', width=Pt(300))
python操作word,关于win32com
word中doc这个格式的文件是微软特有格式,微软没有向外公开任何的api接口文档, 只能通过微软提供的OLE组件来提其COM接口,只要你的机器上安装了Offices完整的办公软件,在安装目录下面有个MSWORD.OLB组件,导入这个即可。
python处理word文档
有个库叫『Python-docx』
安装之后 python 可以读写 word 文档,就可以拼接了。