2012-11-22 37 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