代码:

  1. #coding=utf-8
  2. __author__ = 'zhm'
  3. from win32com import client as wc
  4. import os
  5. import time
  6. import random
  7. import MySQLdb
  8. import re
  9. def wordsToHtml(dir):
  10. #批量把文件夹的word文档转换成html文件
  11. #金山WPS调用,抢先版的用KWPS,正式版WPS
  12. word = wc.Dispatch('KWPS.Application')
  13. for path, subdirs, files in os.walk(dir):
  14. for wordFile in files:
  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文件:' + htmlFullName
  29. doc.SaveAs(htmlFullName, 8)
  30. doc.Close()
  31. word.Quit()
  32. print ""
  33. print "Finished!"
  34. def html_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 in os.walk(dir):
  46. for htmlFile in files:
  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 not os.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 in m:
  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 not os.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')

python word的更多相关文章

  1. python word操作深入

    python 把word转html:上传页面<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" &q ...

  2. python word转pdf

    原理 使用python win32 库 调用word底层vba,将word转成pdf 安装pywin32 pip install pywin32 python代码 from win32com.clie ...

  3. Python初识(一)

    首先我有编程语言的基础,你也有就最好了,这样会很快认识Python. 当然由于本人见识和学识的局限性,请广大猿/媛们多多包涵与指正(希望多评论哦),共同进步嘛. ◆ 准备环境:到python官网下载p ...

  4. 3. Python 简介

    3. Python 简介 下面的例子中,输入和输出分别由大于号和句号提示符 ( >>> 和 ... ) 标注:如果想重现这些例子,就要在解释器的提示符后,输入 (提示符后面的) 那些 ...

  5. [Notes] Learn Python2.7 From Python Tutorial

    I have planed to learn Python for many times. I have started to learn Python for many times . Howeve ...

  6. Python入门一:基本数据类型

    作为一个刚入门编程的大一狗,第一次写博客,希望能对自己学的知识进行巩固和提升,也希望记录自己成长的过程. 学习Python,一是因为暑假学的c++头疼,听说Python简单,那我就试试吧,二是因为Py ...

  7. Python 基础之基本数据类型

    首先,Python中的变量不需要声明.每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建.在Python中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象 ...

  8. Python 面向对象(一) 基础

    Python 中一切皆对象 什么是面向对象? 面向对象就是将一些事物的共有特征抽象成类,从类来创建实例. 类class 可以理解为模版 比如人类,都具有身高.体重.年龄.性别.籍贯...等属性,但属性 ...

  9. python数据类型(一)

    1.数据类型 python中数有四种类型:整数.长整数.浮点数和复数. 整数, 如 1 长整数 是比较大的整数 浮点数 如 1.23.3E-2 复数 如 1 + 2j. 1.1 + 2.2j 2. 自 ...

随机推荐

  1. ViewStub源码分析

    ViewStub是一种特殊的View,Android官方给出的解释是:一种不可见的(GONE).size是0的占位view,多用于运行时 延迟加载的,也就是说真正需要某个view的时候.在实际项目中, ...

  2. django中html过滤器filter

    http://blog.csdn.net/iloveyin/article/details/49560559 safe让Html标签以及一些特殊符号(如<)生效,下面以例子说明: # value ...

  3. Linux(Centos6.5) Nginx 安装

    Nginx一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器,一个Apache服务器不错的替代品.             能够支持高达 50,000 个并发连接数的响应 ...

  4. Android上传文件至服务器(上)

    每一次都不能上首页,真悲催..管理员让我上一次首页? 很多时候我更愿意一个人写代码,与其在垃圾代码上改改改,我更愿意直接重构. 整洁的代码简单直接.整洁的代码如同优美的散文.整洁的代码从不隐藏设计者的 ...

  5. C++STL - 类模板

    类的成员变量,成员函数,成员类型,以及基类中如果包含参数化的类型,那么该类就是一个类模板   1.定义 template<typename 类型形参1, typename 类型形参2,...&g ...

  6. JS魔法堂:ES6新特性——GeneratorFunction介绍

    一.前言       第一次看koajs的示例时,发现该语句 function *(next){...............} ,这是啥啊?于是搜索一下,原来这是就是ES6的新特性Generator ...

  7. 【WPF系列】Textbox

    Style定义实例 给Textbox定义一个阴影效果. <Style x:Key="{x:Type TextBox}" TargetType="{x:Type Te ...

  8. markdown学习/mou

    markdown编辑器mou markdown编辑器的使用很简单,mac平台选择课 MOU 这款比较轻的客户端. 使用也很方便,打开软件,->helo->mou help 就有各种示例,照 ...

  9. Winform布局方式

    一.默认布局 ★可以加panel,也可以不加: ★通过鼠标拖动控件的方式,根据自己的想法布局.拖动控件的过程中,会有对齐的线,方便操作: ★也可选中要布局的控件,在工具栏中有对齐工具可供选择,也有调整 ...

  10. [No00006F]总结C#获取当前路径的各种方法

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...