2017-09-24 166 views
1

我對使用打開的docx-file有個小問題。 這是我的代碼部分:在python-docx中使用表格

doc = Document(self.fileName[0]) 

for paragraph in doc.paragraphs: 
    self.cursor.insertText(paragraph.text + '\n') 

for table_index, table in enumerate(doc.tables): 
    self.cursor.insertText('Таблица {0}\n'.format(table_index+1)) 
    for row_index in range(len(table.rows)): 
     for column_index in range(len(table.columns)): 
     self.cursor.insertText(table.cell(row_index, column_index).text + '\t') 
     self.cursor.insertText('\n') 
    self.cursor.insertText('\n') 

問題是我可以找出表被放置physicaly在 原來的文檔? 我需要像doc中一樣按照相同的順序顯示段落和表格。

回答

0

此操作尚未直接受python-docx API支持。不過,您可以在此處找到解決方法功能: https://github.com/python-openxml/python-docx/issues/40 並且可以通過在'python-docx iter塊項目'上搜索找到更多信息。

基本問題是,Microsoft的Word for Word不包含以文檔順序迭代塊級項目的方法。 Word中的塊級項目是段落和表格對象。 python-docx將MS API建模爲起點,因此Document.paragraphsDocument.tables屬性是第一個要實現的屬性。 Document.iter_block_items()或者也許只是Document.block_items尚未實現,但它比其他許多功能更接近增強列表的頂部,因爲它經常被要求提供。

與此同時,您需要在自己的代碼中實施解決方法功能。

+0

謝謝。來自鏈接的代碼完美無缺。 –