需求:python操作word文档并把doc或者docx文档中的内容插入到mysql的数据库中(段落跟图片位置保持一致)
解决方法:用python先把doc文件转换成docx文件(这一步也可以不要后续会说明),然后读取docx的文件并另存为htm格式的文件(上一步可以直接把doc文件另存为htm),python根据bs4获取p标签里的内容,如果段落中有图片则保存图片。(图片在word文档中的位置可以很好的还原到生成的数据库内容)
我见网上有把docx压缩后解压获取图片的,然后根据在根据xml来读取图片的位置,我觉得比较繁琐。用docx模块读取段落的时候还需要是不是判断段落中有分页等,然而转成htm之后就不用判断那么多直接判断段落里的样式或者图片等就可以了。
代码:
doc批量转换成docx文档
def findAllDoc(self):
files = 'D:\\修改的文章'
w = wc.gencache.EnsureDispatch('Word.Application')
for root,ds,fs in os.walk(files):
for f in fs:
if f.endswith('.doc'):
name = os.path.join(root+'\\',f)#必须是此形式的不然会有部分文档打开报错找不到文档
doc = w.Documents.Open("{}".format(name))#打开word文档
doc.SaveAs2("{}x".format(name), 12)#另存为
doc.Close()
sqlIn = 'INSERT post_temp_doc3 SET name = "%s"' % (name)
self.cursor.execute(sqlIn)
self.cursor.connection.commit()
#转换成功删除doc文档
if os.path.exists(name):
os.remove(name)
print('删除成功%s' % name)
else:
print('已经删除文件')
w.Quit()
docx转htm并读取内容插入到数据库
def findAllFile(self):
files = 'D:\\修改的文章\\'
uploads = 'uploads/images/post/'
htmlFile = "D:/1/1.htm"
folderFile = "D:/1/1.files"
w = wc.gencache.EnsureDispatch('Word.Application')
for root,ds,fs in os.walk(files):
for f in fs:
if f.endswith('.docx'):
docxFile = os.path.join(root,f)
doc = w.Documents.Open("{}".format(docxFile))
doc.SaveAs2(htmlFile, 8)#转成htm的参数是8参数详细请参考https://docs.microsoft.com/zh-cn/office/vba/api/word.wdsaveformat
doc.Close()
title = f.replace('.docx', '')
content = ''
#打开htm文件必须是二进制否则编码的问题会很让你头疼
with open(htmlFile, 'rb') as htmls:
htmlRead = htmls.read()
htmlData = BeautifulSoup(htmlRead, 'lxml')
htmlP = htmlData.find_all('p')
for pList in htmlP:
imgList = pList.find_all('img')
if imgList :
for img in imgList:
imgFile = img.get("src")
imgType = imgFile.replace('1.files/', '').partition('.')#获取图片后缀
fileWrite = files.replace('\\', '/')
with open(fileWrite+imgFile, 'rb') as imgr:
imgSrc = fileWrite+uploads+str(int(time.time()))+imgType[1]+imgType[2]
with open(imgSrc, 'wb')as imgw:
imgw.write(imgr.read())
content += '<p><img src="%s"></p>' % imgSrc.replace(fileWrite, '')
else:
content += '<p>%s</p>' % pList.text.replace("'", ''')#转义单引号不然有单引号的内容插入数据库时会报错
sqlIn = 'INSERT post_temp1 SET title = "%s" , content = \'%s\'' % (title,content)
print(sqlIn)
self.cursor.execute(sqlIn)
self.cursor.connection.commit()
if os.path.exists(docxFile):
os.remove(docxFile)#删除docx文档
if os.path.exists(htmlFile):
os.remove(htmlFile)#删除1.htm文档
shutil.rmtree(folderFile)#删除文件夹
w.Quit()
我做的这个比较简单就是段落和图片插入到数据库生成的文章的时候位置不变,至于其他的像span或者加粗没有做处理。如果样式需要还原更详细的话可以自己写一写,毕竟我这个只是个引子。
表达能力不强敬请见谅。附源码地址:https://download.csdn.net/download/daotianmi/16674288