python word
代码:
- #coding=utf-8
- __author__ = 'zhm'
- from win32com import client as wc
- import os
- import time
- import random
- import MySQLdb
- import re
- def wordsToHtml(dir):
- #批量把文件夹的word文档转换成html文件
- #金山WPS调用,抢先版的用KWPS,正式版WPS
- word = wc.Dispatch('KWPS.Application')
- for path, subdirs, files in os.walk(dir):
- for wordFile in files:
- wordFullName = os.path.join(path, wordFile)
- #print "word:" + wordFullName
- doc = word.Documents.Open(wordFullName)
- wordFile2 = unicode(wordFile, "gbk")
- dotIndex = wordFile2.rfind(".")
- if(dotIndex == -1):
- print '********************ERROR: 未取得后缀名!'
- fileSuffix = wordFile2[(dotIndex + 1) : ]
- if(fileSuffix == "doc" or fileSuffix == "docx"):
- fileName = wordFile2[ : dotIndex]
- htmlName = fileName + ".html"
- htmlFullName = os.path.join(unicode(path, "gbk"), htmlName)
- # htmlFullName = unicode(path, "gbk") + "\\" + htmlName
- print u'生成了html文件:' + htmlFullName
- doc.SaveAs(htmlFullName, 8)
- doc.Close()
- word.Quit()
- print ""
- print "Finished!"
- def html_add_to_db(dir):
- #将转换成功的html文件批量插入数据库中。
- conn = MySQLdb.connect(
- host='localhost',
- port=3306,
- user='root',
- passwd='root',
- db='test',
- charset='utf8'
- )
- cur = conn.cursor()
- for path, subdirs, files in os.walk(dir):
- for htmlFile in files:
- htmlFullName = os.path.join(path, htmlFile)
- title = os.path.splitext(htmlFile)[0]
- targetDir = 'D:/files/htmls/'
- #D:/files为web服务器配置的静态目录
- sconds = time.time()
- msconds = sconds * 1000
- targetFile = os.path.join(targetDir, str(int(msconds))+str(random.randint(100, 10000)) +'.html')
- htmlFile2 = unicode(htmlFile, "gbk")
- dotIndex = htmlFile2.rfind(".")
- if(dotIndex == -1):
- print '********************ERROR: 未取得后缀名!'
- fileSuffix = htmlFile2[(dotIndex + 1) : ]
- if(fileSuffix == "htm" or fileSuffix == "html"):
- if not os.path.exists(targetDir):
- os.makedirs(targetDir)
- htmlFullName = os.path.join(unicode(path, "gbk"), htmlFullName)
- htFile = open(htmlFullName,'rb')
- #获取网页内容
- htmStrCotent = htFile.read()
- #找出里面的图片
- img=re.compile(r"""<img\s.*?\s?src\s*=\s*['|"]?([^\s'"]+).*?>""",re.I)
- m = img.findall(htmStrCotent)
- for tagContent in m:
- imgSrc = unicode(tagContent, "gbk")
- imgSrcFullName = os.path.join(path, imgSrc)
- #上传图片
- imgTarget = 'D:/files/images/whzx/'
- img_sconds = time.time()
- img_msconds = sconds * 1000
- targetImgFile = os.path.join(imgTarget, str(int(img_msconds))+str(random.randint(100, 10000)) +'.png')
- if not os.path.exists(imgTarget):
- os.makedirs(imgTarget)
- if not os.path.exists(targetImgFile) or(os.path.exists(targetImgFile) and (os.path.getsize(targetImgFile) != os.path.getsize(imgSrcFullName))):
- tmpImgFile = open(imgSrcFullName,'rb')
- tmpWriteImgFile = open(targetImgFile, "wb")
- tmpWriteImgFile.write(tmpImgFile.read())
- tmpImgFile.close()
- tmpWriteImgFile.close()
- htmStrCotent=htmStrCotent.replace(tagContent,targetImgFile.split(":")[1])
- if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(htmlFullName))):
- #用iframe包装转换好的html文件。
- iframeHtml='''
- <script type="text/javascript" language="javascript">
- function iFrameHeight() {
- var ifm= document.getElementById("iframepage");
- var subWeb = document.frames ? document.frames["iframepage"].document:ifm.contentDocument;
- if(ifm != null && subWeb != null) {
- ifm.height = subWeb.body.scrollHeight;
- }
- }
- </script>
- <iframe src='''+targetFile.split(':')[1]+'''
- marginheight="0" marginwidth="0" frameborder="0" scrolling="no" width="765" height=100% id="iframepage" name="iframepage" onLoad="iFrameHeight()" ></iframe>
- '''
- tmpTargetFile = open(targetFile, "wb")
- tmpTargetFile.write(htmStrCotent)
- tmpTargetFile.close()
- htFile.close()
- try:
- # 执行
- sql = "insert into common_article(title,content) values(%s,%s)"
- param = (unicode(title, "gbk"),iframeHtml)
- cur.execute(sql,param)
- except:
- print "Error: unable to insert data"
- cur.close()
- conn.commit()
- # 关闭数据库连接
- conn.close()
- if __name__ == '__main__':
- wordsToHtml('d:/word')
- html_add_to_db('d:/word')
python word的更多相关文章
- python word操作深入
python 把word转html:上传页面<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" &q ...
- python word转pdf
原理 使用python win32 库 调用word底层vba,将word转成pdf 安装pywin32 pip install pywin32 python代码 from win32com.clie ...
- Python初识(一)
首先我有编程语言的基础,你也有就最好了,这样会很快认识Python. 当然由于本人见识和学识的局限性,请广大猿/媛们多多包涵与指正(希望多评论哦),共同进步嘛. ◆ 准备环境:到python官网下载p ...
- 3. Python 简介
3. Python 简介 下面的例子中,输入和输出分别由大于号和句号提示符 ( >>> 和 ... ) 标注:如果想重现这些例子,就要在解释器的提示符后,输入 (提示符后面的) 那些 ...
- [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 ...
- Python入门一:基本数据类型
作为一个刚入门编程的大一狗,第一次写博客,希望能对自己学的知识进行巩固和提升,也希望记录自己成长的过程. 学习Python,一是因为暑假学的c++头疼,听说Python简单,那我就试试吧,二是因为Py ...
- Python 基础之基本数据类型
首先,Python中的变量不需要声明.每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建.在Python中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象 ...
- Python 面向对象(一) 基础
Python 中一切皆对象 什么是面向对象? 面向对象就是将一些事物的共有特征抽象成类,从类来创建实例. 类class 可以理解为模版 比如人类,都具有身高.体重.年龄.性别.籍贯...等属性,但属性 ...
- python数据类型(一)
1.数据类型 python中数有四种类型:整数.长整数.浮点数和复数. 整数, 如 1 长整数 是比较大的整数 浮点数 如 1.23.3E-2 复数 如 1 + 2j. 1.1 + 2.2j 2. 自 ...
随机推荐
- ViewStub源码分析
ViewStub是一种特殊的View,Android官方给出的解释是:一种不可见的(GONE).size是0的占位view,多用于运行时 延迟加载的,也就是说真正需要某个view的时候.在实际项目中, ...
- django中html过滤器filter
http://blog.csdn.net/iloveyin/article/details/49560559 safe让Html标签以及一些特殊符号(如<)生效,下面以例子说明: # value ...
- Linux(Centos6.5) Nginx 安装
Nginx一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器,一个Apache服务器不错的替代品. 能够支持高达 50,000 个并发连接数的响应 ...
- Android上传文件至服务器(上)
每一次都不能上首页,真悲催..管理员让我上一次首页? 很多时候我更愿意一个人写代码,与其在垃圾代码上改改改,我更愿意直接重构. 整洁的代码简单直接.整洁的代码如同优美的散文.整洁的代码从不隐藏设计者的 ...
- C++STL - 类模板
类的成员变量,成员函数,成员类型,以及基类中如果包含参数化的类型,那么该类就是一个类模板 1.定义 template<typename 类型形参1, typename 类型形参2,...&g ...
- JS魔法堂:ES6新特性——GeneratorFunction介绍
一.前言 第一次看koajs的示例时,发现该语句 function *(next){...............} ,这是啥啊?于是搜索一下,原来这是就是ES6的新特性Generator ...
- 【WPF系列】Textbox
Style定义实例 给Textbox定义一个阴影效果. <Style x:Key="{x:Type TextBox}" TargetType="{x:Type Te ...
- markdown学习/mou
markdown编辑器mou markdown编辑器的使用很简单,mac平台选择课 MOU 这款比较轻的客户端. 使用也很方便,打开软件,->helo->mou help 就有各种示例,照 ...
- Winform布局方式
一.默认布局 ★可以加panel,也可以不加: ★通过鼠标拖动控件的方式,根据自己的想法布局.拖动控件的过程中,会有对齐的线,方便操作: ★也可选中要布局的控件,在工具栏中有对齐工具可供选择,也有调整 ...
- [No00006F]总结C#获取当前路径的各种方法
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...