python word 1_Python word | 学步园
这里测试的环境是:windows xp,office 2007,python 2.5.2,pywin32 build
213,原理是利用win32com接口直接调用office
API,好处是简单、兼容性好,只要office能处理的,python都可以处理,处理出来的结果和office word里面“另存为”一致。
#!/usr/bin/env python
#coding=utf-8
from
win32com import
client as
wc
word = wc.Dispatch
(
'Word.Application'
)
doc = word.Documents
.Open
(
'd:/labs/math.doc'
)
doc.SaveAs
(
'd:/labs/math.html'
, 8
)
doc.Close
(
)
word.Quit
(
)
关键的就是doc.SaveAs(‘d:/labs/math.html’,
8)这一行,网上很多文章写成:doc.SaveAs(‘d:/labs/math.html’,
win32com.client.constants.wdFormatHTML),直接报错:
AttributeError: class Constants has no attribute ‘wdFormatHTML’
当然你也可以用上面的代码将word文件转换成任意格式文件(只要office 2007支持,比如将word文件转换成PDF文件,把8改成17即可),下面是office 2007支持的全部文件格式对应表:
wdFormatDocument = 0
wdFormatDocument97 = 0
wdFormatDocumentDefault = 16
wdFormatDOSText = 4
wdFormatDOSTextLineBreaks = 5
wdFormatEncodedText = 7
wdFormatFilteredHTML = 10
wdFormatFlatXML = 19
wdFormatFlatXMLMacroEnabled = 20
wdFormatFlatXMLTemplate = 21
wdFormatFlatXMLTemplateMacroEnabled = 22
wdFormatHTML = 8
wdFormatPDF = 17
wdFormatRTF = 6
wdFormatTemplate = 1
wdFormatTemplate97 = 1
wdFormatText = 2
wdFormatTextLineBreaks = 3
wdFormatUnicodeText = 7
wdFormatWebArchive = 9
wdFormatXML = 11
wdFormatXMLDocument = 12
wdFormatXMLDocumentMacroEnabled = 13
wdFormatXMLTemplate = 14
wdFormatXMLTemplateMacroEnabled = 15
wdFormatXPS = 18
照着字面意思应该能对应到相应的文件格式,如果你是office
2003可能支持不了这么多格式。word文件转html有两种格式可选wdFormatHTML、wdFormatFilteredHTML(对应数字
8、10),区别是如果是wdFormatHTML格式的话,word文件里面的公式等ole对象将会存储成wmf格式,而选用
wdFormatFilteredHTML的话公式图片将存储为gif格式,而且目测可以看出用wdFormatFilteredHTML生成的HTML
明显比wdFormatHTML要干净许多。
当然你也可以用任意一种语言通过com来调用office API,比如PHP.
=========================================
使用 python 写 COM
2009年09月03日 星期四 下午 07:01
Python 支持Com调用(client com) 以及撰写COM 组件(server com).
1. com 调用示例(使用Windows Media Player 播放音乐)
from
win32com.client
import
Dispatch
mp
=
Dispatch(
"
WMPlayer.OCX
"
)
tune
=
mp.newMedia(
"
C:/WINDOWS/system32/oobe/images/title.wma
"
)
mp.currentPlaylist.appendItem(tune)
mp.controls.play()
class
PythonUtilities:
_public_methods_
=
[
'
SplitString
'
]
_reg_progid_
=
"
PythonDemos.Utilities
"
#
NEVER copy the following ID
#
Use "print pythoncom.CreateGuid()" to make a new one.
_reg_clsid_
=
"
{41E24E95-D45A-11D2-852C-204C4F4F5020}
"
def
SplitString(self, val, item
=
None):
import
string
if
item
!=
None: item
=
str(item)
return
string.split(str(val), item)
#
Add code so that when this script is run by
#
Python.exe, it self-registers.
if
__name__
==
'
__main__
'
:
"
Registering COM server
"
import
win32com.server.register
win32com.server.register.UseCommandLine(PythonUtilities)
- 注册/注销Com
Command-Line Option
Description
The default is to register the COM objects.
--unregister
Unregisters the objects. This removes all references to the objects from the Windows registry.
--debug
Registers the COM servers in debug mode. We discuss debugging COM servers later in this chapter.
--quiet
Register (or unregister) the object quietly (i.e., don't report success).
- 使用COM
可以在python 命令行下运行
>>>
import
win32com.client
>>>
s
=
win32com.client.Dispatch(
"
PythonDemos.Utilities
"
)
>>>
s.SplitString(
"
a,b,c
"
,
"
,
"
)
((u
'
a
'
, u
'
a,b,c
'
),)
>>>
3. python server com 原理
其实在注册表中查找到python com 的实现内幕
Windows Registry Editor Version
5.00
[
HKEY_CLASSES_ROOT/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}
]
@
=
"
PythonDemos.Utilities
"
[
HKEY_CLASSES_ROOT/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}/Debugging
]
@
=
"
0
"
[
HKEY_CLASSES_ROOT/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}/Implemented Categories
]
[
HKEY_CLASSES_ROOT/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}/Implemented Categories/{B3EF80D0-68E2-11D0-A689-00C04FD658FF}
]
[
HKEY_CLASSES_ROOT/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}/InprocServer32
]
@
=
"
pythoncom25.dll
"
"
ThreadingModel
"
=
"
both
"
[
HKEY_CLASSES_ROOT/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}/LocalServer32
]
@
=
"
D://usr//Python//pythonw.exe /
"
D://usr//Python//lib//site-packages//win32com//server//localserver.py/
"
{41E24E95-D45A-11D2-852C-204C4F4F5020}
"
[
HKEY_CLASSES_ROOT/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}/ProgID
]
@
=
"
PythonDemos.Utilities
"
[
HKEY_CLASSES_ROOT/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}/PythonCOM
]
@
=
"
PythonDemos.PythonUtilities
"
[
HKEY_CLASSES_ROOT/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}/PythonCOMPath
]
@
=
"
D://
"
inproc server 是通过pythoncom25.dll 实现
local server 通过localserver.py 实现
com 对应的python 源文件信息在 PythonCOMPath & PythonCOM
4. 使用问题
用PHP 或者 c 调用com 的时候
php
$com
=
new
COM(
"
PythonDemos.Utilities
"
);
$rs
=
$com
->
SplitString(
"
a b c
"
);
foreach
(
$rs
as
$r
)
echo
$r
.
"
/n
"
;
?>
会碰到下面的一些错误.
pythoncom error: PythonCOM Server - The 'win32com.server.policy' module could not be loaded.
: No module named server.policy
pythoncom error: CPyFactory::CreateInstance failed to create instance.
(80004005)
可以通过2种方式解决:
a. 设置环境 PYTHONHOME = D:/usr/Python
另外在c ++ 使用python 的时候, 如果import module 出现错误'import site' failed; use -v for traceback
的话, 也可以通过设置这个变量解决.
b. 为com 生产exe, dll 可执行文件, setup.py 代码如下 :
from
distutils.core
import
setup
import
py2exe
import
sys
import
shutil
#
Remove the build tree
ALWAYS do that!
shutil.rmtree(
"
build
"
, ignore_errors
=
True)
#
List of modules to exclude from the executable
excludes
=
[
"
pywin
"
,
"
pywin.debugger
"
,
"
pywin.debugger.dbgcon
"
,
"
pywin.dialogs
"
,
"
pywin.dialogs.list
"
]
#
List of modules to include in the executable
includes
=
[
"
win32com.server
"
]
#
ModuleFinder can't handle runtime changes to __path__, but win32com uses them
try
:
#
if this doesn't work, try import modulefinder
import
py2exe.mf as modulefinder
import
win32com
for
p
in
win32com.
__path__
[
1
:]:
modulefinder.AddPackagePath(
"
win32com
"
, p)
for
extra
in
[
"
win32com.shell
"
,
"
win32com.server
"
]:
#
,"win32com.mapi"
__import__
(extra)
m
=
sys.modules[extra]
for
p
in
m.
__path__
[
1
:]:
modulefinder.AddPackagePath(extra, p)
except
ImportError:
#
no build path setup, no worries.
pass
#
Set up py2exe with all the options
setup(
options
=
{
"
py2exe
"
: {
"
compressed
"
:
2
,
"
optimize
"
:
2
,
#
"bundle_files": 1,
"
dist_dir
"
:
"
COMDist
"
,
"
excludes
"
: excludes,
"
includes
"
: includes}},
#
The lib directory contains everything except the executables and the python dll.
#
Can include a subdirectory name.
zipfile
=
None,
com_server
=
[
'PythonDemos
'
], # 文件名!!
)
python word 1_Python word | 学步园相关推荐
- python isinstance_Python之isinstance | 学步园
isinstance isinstance(object, classinfo) 判断实例是否是这个类或者object是变量 classinfo 是类型(tuple,dict,int,float) 判 ...
- python随机生成英文字符串_如何用Python语言生成随机字符串 | 学步园
这是在Stackoverflow的关于 "用Python语言简洁地生成随机字符串" 的经典问答. 将此文翻译并分享下. 我想生成一个长度为N的字符串. 这个字符串应由数字和大写英文 ...
- python转c工具shedskin_shedskin— 一种python性能优化工具 | 学步园
虽说python的性能在脚本语言中还算杰出,但是当程序中出现for,while循环或者函数递归调用的情况,其性能就下降的非常快. 比如,用递归方法计算fibonacci(33) ,C语言只要几毫秒,但 ...
- python如何计算个人gpa_【Python】计算GPA | 学步园
最近开始我的研究生生涯了,周围都在谈论GPA这种高深的东西,像我这种工科学校背景的孩子一向是个喜欢在键盘上耕耘的人,对考高分没有多大兴趣(其实是没有那个本事).不过我也想知道我自己本科的GPA是多少来 ...
- python矩阵的螺旋排列_飘逸的python – 打印螺旋矩阵 | 学步园
经过上面的分析,思路很清晰了,千言不如一码. import itertools def spiral(n,m): _status = itertools.cycle(['right','down',' ...
- python导入word转换的html,python如何转换word格式、读取word内容、转成html
# python如何转换word格式.读取word内容.转成html? import docx from win32com import client as wc # 首先将doc转换成docx wo ...
- python批量pdf转word,python批量实现Word文件转换为PDF文件
本文为大家分享了python批量转换Word文件为PDF文件的具体方法,供大家参考,具体内容如下 1.目的 通过万能的Python把一个目录下的所有Word文件转换为PDF文件. 2.遍历目录 作者总 ...
- python批量提取word指定内容_使用python批量读取word文档并整理关键信息到excel表格的实例...
目标 最近实验室里成立了一个计算机兴趣小组 倡议大家多把自己解决问题的经验记录并分享 就像在CSDN写博客一样 虽然刚刚起步 但考虑到后面此类经验记录的资料会越来越多 所以一开始就要做好模板设计(如下 ...
- python怎么读取word文件_使用python编辑和读取word文档
python调用word接口主要用到的模板为python-docx,基本操作官方文档有说明. 使用python新建一个word文档,操作就像文档里介绍的那样: 1 from docx importDo ...
最新文章
- 腾讯开放TAPD、持续集成平台等核心研发工具,加速AI落地
- GDCM:gdcm::ExplicitDataElement的测试程序
- 对lIKE语句的优化
- 阿里工程师是如何系统化地总结缓存相关知识的
- oj题 根据化学方程式计算摩尔质量
- java heap space 解决方法_内存溢出错误:java堆空间
- WMware Workstation——时间和时区问题
- slack 聊天机器人_无法筹集资金的Slack机器人
- 河南中睿保险中介系统环境升级配置纪录
- VM虚拟机安装win7系统(亲测可用!!!)
- 经典面试题 Ipv4 和 Ipv6 是什么
- 注册FaceBook和购买FaceBook小白号的区别
- php不使用第三变量互换,总结PHP不用第三个变量交换两个变量的值的几种方法
- springSecurity之PasswordEncoder
- hdu 4416 后缀数组
- 关于xampp集成环境的官网下载
- 读取太阳紫外辐照谱数据
- 服装行业拼的是实力——智能制造
- lvds 共模电感_一文了解共模电感/共模信号/差分信号
- mysql 姓刘或姓李_MYSQL数据库查询
热门文章
- 程序出错后,程序员给测试人员的20条高频回复
- 5个常见的SD-WAN挑战以及如何应对
- 一些对制作网站有帮助的站点
- 《程序是怎样跑起来的》第四章
- [Swift]LeetCode513. 找树左下角的值 | Find Bottom Left Tree Value
- 【HDU 1501】Zipper(记忆化搜索)
- 【NOIP2015】【Luogu2661】信息传递(有向图最小环)
- BZOJ 1093 [ZJOI2007]最大半连通子图
- http://www.jb51.net/list/list_233_2.htm(导航: 首页 软件编程 Android)
- 自定义时间格式 返回年月日