2012-11-22 38 views
2

最近,我正在尝试用于MS Word文件管理的不同API(现在编写)。在这一点上,我只需要一个简单的编写python API。我尝试了win32com模块,这个模块在缺乏python在线实例的情况下被证明是非常强大的(很少有关于VB和C的知识能够翻译MSDN中的示例)。MS Word r/w在python,Python-docx问题和win32com引用?

我试图使用python-docx,但安装后我得到这个任何docx函数的追踪。

Traceback (most recent call last): 
    File "C:\filepath.py", line 9, in <module> 
    ispit = newdocument() 
NameError: name 'newdocument' is not defined 

我有一些问题,通过源代码和easy_install安装lxml。它正在检查libxlm2和libxslt二进制文件。我下载了它们并添加了环境路径,但每次都停止安装槽源或easy_install。

最后我用这个网站的非官方python扩展包Link。 安装速度很快,最终没有发生错误。

有什么我可以做的,使docx工作,是否有一些python win32com相关的参考线上?我找不到任何东西。 (除了MSDN(VB不是python)和O'Reily's Python programming on win32

回答

8

当使用win32com时,请记住您正在与Word对象模型交谈。您不需要知道很多VBA或其他语言来将样本应用于Python;你只需要弄清楚对象模型的哪些部分正在被使用。

让我们以下面的示例(在VBA),这将创建Application的新实例,并加载一个新的文档转化为一个新的实例:

Public Sub NewWordApp() 

    'Create variables to reference objects 
    '(This line is not needed in Python; you don't need to declare variables 
    'or their types before using them) 
    Dim wordApp As Word.Application, wordDoc As Word.Document 

    'Create a new instance of a Word Application object 
    '(Another difference - in VBA you use Set for objects and simple assignment for 
    'primitive values. In Python, you use simple assignment for objects as well.) 
    Set wordApp = New Word.Application 

    'Show the application 
    wordApp.Visible = True 

    'Create a new document in the application 
    Set wordDoc = wordApp.Documents.Add() 

    'Set the text of the first paragraph 
    '(A Paragraph object doesn't have a Text property. Instead, it has a Range property 
    'which refers to a Range object, which does have a Text property.) 
    wordDoc.Paragraphs(1).Range.Text = "Hello, World!" 

End Sub 

的代码Python中的类似的片段可能看起来像这样的:

import win32com.client 

#Create an instance of Word.Application 
wordApp = win32com.client.Dispatch('Word.Application') 

#Show the application 
wordApp.Visible = True 

#Create a new document in the application 
wordDoc = wordApp.Documents.Add() 

#Set the text of the first paragraph 
wordDoc.Paragraphs(1).Range.Text = "Hello, World!" 

一些链接到Word对象模型:

一些Python示例:

+0

最佳来源呢!谢谢! – Domagoj