代码:

 #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的更多相关文章

  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. SwipeRefreshLayout + RecyclerView 实现 上拉刷新 和 下拉刷新

    下拉刷新和上拉刷新都用SwipeRefreshLayout 自带的进度条 布局 <?xml version="1.0" encoding="utf-8"? ...

  2. android 四大组件之---Service

    服务 服务的生命周期 --- 1 开启服务的生命周期 完整的生命周期:onCreate()-->onStartCommand()-->onDestroy() * 开启服务:onCreate ...

  3. iOS 摇一摇的功能

    效果如下 相关素材 相关代码如下 #import "ShakeViewController.h" #import <AudioToolbox/AudioToolbox.h&g ...

  4. 数据仓库之SSIS开发

    1.从cdc捕获到数据以后, 连接ssis进行执行数据的抽取以及转换工作,把需要的数据导入到数据仓库, 并且做好对应的日志记录表.现在先说一下比较重要的. 选择参数化设置数据连接, 以方便后面的配置. ...

  5. linux c++编译问题和虚拟机网络通信

    1.gcc main.cpp -lstdc++ -o test5 2. service network stop service NetworkManager restart

  6. 解决开启SQL Server sql Always on Group 事务日志增大的问题

    配置了Alwayson之后,因为没有只能使用完全恢复模式,不能使用简单或大容量日志模式,所以日志不断增长,不能使用改变恢复模式的方式清空日志 手动操作收缩或截断日志也无效 读了一些文章后发现,有人使用 ...

  7. 【Windows编程】系列第九篇:剪贴板使用

    上一篇我们学习了常见的通用对话框,本篇来了解剪贴板的使用,它常用于复制粘贴功能. 剪贴板是Windows最早就加入的功能,由于该功能非常实用,我们几乎每天都会使用到.通过剪贴板,我们就可以将数据从一个 ...

  8. 报表开发导出各种格式文件的API

    文件输出的多样性,准确性和稳定性对于我们常用的报表软件来说很重要.报表的输入是指从报表的模板文件(XML格式的)创建WorkBook对象,输出则指将报表保存为各种格式文件,比如Pdf.Excel.Wo ...

  9. 关于css的一些事情(1)

    什么情况下hidden不起作用? position设置成fixed,overflow的hidden不起作用. visibility和display 1.visibility: 规定了元素是否可见,即使 ...

  10. 线程同步之 yield() wait()

    yield()没有参数. sleep 方法使当前运行中的线程睡眼一段时间,进入不可运行状态,这段时间的长短是由程序设定的,yield 方法使当前线程让出CPU占有权,但让出的时间是不可设定的.yiel ...