python word
代码:
1 #coding=utf-8 2 __author__ = 'zhm' 3 from win32com importclient as wc4 importos5 importtime6 importrandom7 importMySQLdb8 importre9 defwordsToHtml(dir):10 #批量把文件夹的word文档转换成html文件 11 #金山WPS调用,抢先版的用KWPS,正式版WPS 12 word = wc.Dispatch('KWPS.Application')13 for path, subdirs, files inos.walk(dir):14 for wordFile infiles:15 wordFullName =os.path.join(path, wordFile)16 #print "word:" + wordFullName 17 doc =word.Documents.Open(wordFullName)18 wordFile2 = unicode(wordFile, "gbk")19 dotIndex = wordFile2.rfind(".")20 if(dotIndex == -1):21 print '********************ERROR: 未取得后缀名!' 22 fileSuffix = wordFile2[(dotIndex + 1) : ]23 if(fileSuffix == "doc" or fileSuffix == "docx"):24 fileName =wordFile2[ : dotIndex]25 htmlName = fileName + ".html" 26 htmlFullName = os.path.join(unicode(path, "gbk"), htmlName)27 #htmlFullName = unicode(path, "gbk") + "\\" + htmlName 28 print u'生成了html文件:' +htmlFullName29 doc.SaveAs(htmlFullName, 8)30 doc.Close()31 word.Quit()32 print "" 33 print "Finished!" 34 defhtml_add_to_db(dir):35 #将转换成功的html文件批量插入数据库中。 36 conn =MySQLdb.connect(37 host='localhost',38 port=3306,39 user='root',40 passwd='root',41 db='test',42 charset='utf8' 43 )44 cur =conn.cursor()45 for path, subdirs, files inos.walk(dir):46 for htmlFile infiles:47 htmlFullName =os.path.join(path, htmlFile)48 title =os.path.splitext(htmlFile)[0]49 targetDir = 'D:/files/htmls/' 50 #D:/files为web服务器配置的静态目录 51 sconds =time.time()52 msconds = sconds * 1000 53 targetFile = os.path.join(targetDir, str(int(msconds))+str(random.randint(100, 10000)) +'.html')54 htmlFile2 = unicode(htmlFile, "gbk")55 dotIndex = htmlFile2.rfind(".")56 if(dotIndex == -1):57 print '********************ERROR: 未取得后缀名!' 58 fileSuffix = htmlFile2[(dotIndex + 1) : ]59 if(fileSuffix == "htm" or fileSuffix == "html"):60 if notos.path.exists(targetDir):61 os.makedirs(targetDir)62 htmlFullName = os.path.join(unicode(path, "gbk"), htmlFullName)63 htFile = open(htmlFullName,'rb')64 #获取网页内容 65 htmStrCotent =htFile.read()66 #找出里面的图片 67 img=re.compile(r"""<img\s.*?\s?src\s*=\s*['|"]?([^\s'"]+).*?>""",re.I)68 m =img.findall(htmStrCotent)69 for tagContent inm:70 imgSrc = unicode(tagContent, "gbk")71 imgSrcFullName =os.path.join(path, imgSrc)72 #上传图片 73 imgTarget = 'D:/files/images/whzx/' 74 img_sconds =time.time()75 img_msconds = sconds * 1000 76 targetImgFile = os.path.join(imgTarget, str(int(img_msconds))+str(random.randint(100, 10000)) +'.png')77 if notos.path.exists(imgTarget):78 os.makedirs(imgTarget)79 if not os.path.exists(targetImgFile) or(os.path.exists(targetImgFile) and (os.path.getsize(targetImgFile) !=os.path.getsize(imgSrcFullName))):80 tmpImgFile = open(imgSrcFullName,'rb')81 tmpWriteImgFile = open(targetImgFile, "wb")82 tmpWriteImgFile.write(tmpImgFile.read())83 tmpImgFile.close()84 tmpWriteImgFile.close()85 htmStrCotent=htmStrCotent.replace(tagContent,targetImgFile.split(":")[1])86 if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) !=os.path.getsize(htmlFullName))):87 #用iframe包装转换好的html文件。 88 iframeHtml=''' 89 <script type="text/javascript" language="javascript">90 function iFrameHeight() {91 var ifm= document.getElementById("iframepage");92 var subWeb = document.frames ? document.frames["iframepage"].document:ifm.contentDocument;93 if(ifm != null && subWeb != null) {94 ifm.height = subWeb.body.scrollHeight;95 }96 }97 </script>98 <iframe src='''+targetFile.split(':')[1]+''' 99 marginheight="0" marginwidth="0" frameborder="0" scrolling="no" width="765" height=100% id="iframepage" name="iframepage" onLoad="iFrameHeight()" ></iframe>100 ''' 101 tmpTargetFile = open(targetFile, "wb")102 tmpTargetFile.write(htmStrCotent)103 tmpTargetFile.close()104 htFile.close()105 try:106 #执行 107 sql = "insert into common_article(title,content) values(%s,%s)" 108 param = (unicode(title, "gbk"),iframeHtml)109 cur.execute(sql,param)110 except:111 print "Error: unable to insert data" 112 cur.close()113 conn.commit()114 #关闭数据库连接 115 conn.close()116 if __name__ == '__main__':117 wordsToHtml('d:/word')118 html_add_to_db('d:/word')
转载于:https://www.cnblogs.com/kamil/p/5772903.html
python word相关推荐
- python word排版_使用Python通过win32 COM实现Word文档的写入与保存方法
通过win32 COM接口实现软件的操作本质上来看跟直接操作软件一致,这跟我之前经常用的通过各种扩展的组件或者库实现各种文件的处理有较大的差异.如果有过Windows下使用Word的经历,那么使用wi ...
- Python/word.so: undefined symbol: _ZNK4Word7reverseEv
python运行时出现如上报错: Python/word.so: undefined symbol: _ZNK4Word7reverseEv 在终端输入: echo _ZNK4Word7reverse ...
- python word 插入转下页及接上页(win32com)
python word 插入转下页及接上页(win32com) 今天整理报告格式,有客户在多页word版报告中,要求增加转下页及接上页分隔,通过python对已生成的word报告进行格式调整,效果如下 ...
- python word 质检报告签字位置动态调整及word转PDF
python word 质检报告签字位置动态调整及word转PDF 生成后,可以在线预览pdf格式的报告
- python word 操作 doc 文件格式转docx 格式 学习笔记
python word 操作 doc 文件格式转docx 格式 学习笔记 from win32com import client as wc import time # TODO file_0 = & ...
- python word转pdf
原理 使用python win32 库 调用word底层vba,将word转成pdf 安装pywin32 pip install pywin32 python代码 from win32com.clie ...
- python word 1_Python word | 学步园
这里测试的环境是:windows xp,office 2007,python 2.5.2,pywin32 build 213,原理是利用win32com接口直接调用office API,好处是简单.兼 ...
- python word转txt_Python办公自动化| word 表格转excel
之前写过一篇 Python办公自动化 | 批量word报告生成工具 ,有小伙伴提出了逆向需求,即:从批量word中获取内容并写入excel,需求背景是汇总一些材料,举例:实习鉴定表.个人简历.档案等. ...
- python读取只读word只读_人生苦短我学Python——Word处理之快速Word转PDF
上回书说到Python对于Excel的操作,本回书咱们来说一说Python对于Word的操作.这次的需求是这样的:把若干个Word文档转换为PDF格式.起因呢,是因为公司经常会披露公告.法律文件等,这 ...
- python word模板 图_科学网—Python绘制可插入Word的高清矢量图(SVG转EMF) - 任晓东的博文...
Python具有强大的绘图功能.在科学论文中通常需要矢量图,而且如果能方便的插入到word中更好.Python中自带的绘图库matplotlib可以将图保存成svg格式,但是我通常喜欢使用emf的矢量 ...
最新文章
- Docker(六):Docker 仓库管理与镜像加速
- linux和unix文件没有创建时间,Linux中没有文件创建时间的概念
- PyTorch环境下对BERT进行Fine-tuning
- visual c++出错:link问题
- python画端午节_我想带你去旅行,我用Python提前做了一份端午旅游攻略,请收下!...
- k8s强制删除pod
- js 简单弹框toast
- 在将hibernate的session托管给spring过程中的问题
- 剑桥offer(41~50)
- python2.7卸载出问题原因分析_怎么卸载python2.7
- sql查询时取日期部分内容(年月日时分秒)、增加时间
- ORM的个人简单理解以及持久化和持久层的简单理解、Hibernate的简单理解,mybatis 的好处通俗易懂
- Linux Ubuntu16挂载新硬盘并格式化硬盘方法教程笔记
- Please, configure Web Facet first!的解决办法
- 使用存储过程返回结果集
- cadence中测输出功率方法
- JSP | 简易购物车的实现
- java的开发工具是什么_java都用什么开发工具
- python虚拟仿真_中国美术学院
- GPRS联网过程简介
热门文章
- linux带宽最小的远程桌面,【图片】linux下哪种远程桌面服务最快?_linux吧_百度贴吧...
- spark抽取mysql数据到hive_使用spark将内存中的数据写入到hive表中
- 正方体最快最简单画_素描新手入门第一幅画可不只是“正方体”
- python 32bit数据结构_python实现bitmap数据结构详解
- 实验5 matlab程序设计2,实验5 Matlab程序设计2
- linux中hadoop命令大全,hadoop常用命令
- r语言ggplot2 多线图绘制图例_plotnine: Python版的ggplot2作图库
- 大学新生学计算机推荐电脑,大学新生用什么电脑好呢?
- Java BufferedReader reset()方法及示例
- 28335接两个spi设备_IIC和SPI如此流行,谁才是嵌入式工程师的必备工具?