簡體   English   中英

Python pywin32(win32com.client)在打開()后准備好Microsoft Word文檔之前響應錯誤表

[英]Python pywin32 (win32com.client) responses wrong table before Microsoft Word document ready after open()

我發現從 MS Word 文檔中讀取的表 python 是錯誤的,但如果等待一段時間可能是正確的,所以我做了這個實驗來調查問題:

1. open a Word .docx document, it has total 26 tables.
2. Repeatedly print and see how many tables in this document? 
   Surprisingly this number is changing!
3. So the question is: how to know if the document is ready after .Open() ?

這是實驗的代碼:

import time 
import win32com.client
word_app = win32com.client.Dispatch("Word.Application")

doc = word_app.Documents.Open(FileName = pathname, ConfirmConversions = False,NoEncodingDialog = True,Revert = True)
for i in range(40):
    print("%d:%d " % (i, doc.tables.count), end="")
    time.sleep(0.1)
doc.Close()

結果:

 0:24 1:24 2:24... there were 24 tables at first, wrong! should be 26 
12:25 13:25    ... then it became 25
26:26 27:26 28:26 ... then become 26 which is finally correct

Open 方法一完成,文檔就准備好了。 Word 對象模型不提供任何屬性或方法來檢查文檔是否已加載和初始化,就像在 HTML 網頁(Web 瀏覽器)的情況下一樣。

這是我的解決方法

import time, docx, win32com.client
word_app = win32com.client.Dispatch("Word.Application")

doc_lib = docx.Document(pathname)
doc_com = word_app.Documents.Open(FileName = pathname)
while len(doc_lib.tables) != doc_com.tables.count:
    # need to wait probably a minute for doc_com to be really ready
    time.sleep(1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM