日期:2014-05-17  浏览次数:20768 次

使用python遍历文件夹将word转为html

有一个小需求,将word文档在页面上显示。因为需要word里面的格式(还有图片),所以不能抽出文本显示。考虑将word转为html后在页面显示html代码,可以保留格式和图片链接(图片链接需要做处理)。

?

不知道使用java是否可以完成这个功能,不过网上找到使用python调用windows接口的文章,所以照着做了一下,还挺方便的。第一次用python,只是照葫芦画瓢,在此记录一下。

?

#coding=utf-8

#文件名:
#BatchConverWords2Html.py
#说明:
#批量将一个文件夹下的所有.doc/.docx文件转为.html文件,需要安装对应的win32模块
#调用方式:进入源程序目录,命令:python BatchConverWords2Html.py RootDir

from win32com import client as wc
import os
word = wc.Dispatch('Word.Application')

def wordsToHtml(dir):

	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 "generate html:" + htmlFullName
				doc.SaveAs(htmlFullName, 10)
				doc.Close()
	
	word.Quit()
	print ""
	print "Finished!"
	
if __name__ == '__main__':
	import sys
	if len(sys.argv) != 2:
		print "Usage: python funcName.py rootdir"
		sys.exit(100)
	wordsToHtml(sys.argv[1])

?

运行结果就是在rootdir目录下的所有word文档转为简洁版的html网页文件,生成的文件存在原word同目录下,有可能生成 xxx.files 文件夹。

?

这里只是综合了一个遍历文件夹目录的例子和一个调用win32com接口的例子,对python还是不太明白,需要好好系统学习下。

?

参考了《Python Cookbook》书 2.17 的一段遍历文件夹的代码:

#《Python Cookbook》2.17 在目录树中改变文件扩展名
import os
def swapextensions(dir, before, after):
	if before[:1] != '.':
		before = '.' + before
	thelen = -len(before)
	if after[:1] != '.':
		after = '.' + after
	for path, subdirs, files in os.walk(dir):
		for oldfile in files:
			if oldfile[thelen:] == before:
				oldfile = os.path.join(path, oldfile)
				newfile = oldfile[:thelen] + after
				os.rename(oldfile, newfile)
if __name__ == '__main__':
	import sys
	if len(sys.argv) != 4:
		print "Usage: swapext rootdir before after"
		sys.exit(100)
	swapextensions(sys.argv[1], sys.argv[2], sys.argv[3])
?

?

注:

1. 要想调用win32com接口,除了安装Python,还需要下载安装与python版本对应的pywin32 模块,我下的是pywin32-216.win32-py2.7.exe;

?

参考:

一、Python转换office word文件为HTML

二、Python中使用中文

三、Python Cookbook

?

============================================

2011年8月23日

今天突然发现一个问题,使用python转出来的html和使用word软件手工转出来的html代码不一样,我之前一直认为调用的是同样的API结果应该一样!

?

ps:javaeye的SEO真好,现在百度搜索“python word html”第二篇就是这个,哎,不过我想看看其他人有没有遇到这种问题啊。

?

?

?

?

?

?

?

1 楼 mistress 2012-01-03  
有个问题,OLE的图片例如visio图片,SaveAs以后存出来失真很厉害。。
2 楼 RonQi 2012-01-04  
mistress 写道
有个问题,OLE的图片例如visio图片,SaveAs以后存出来失真很厉害。。

我没遇到过,今天有空试试