使用带有docx库的Python从Word表中保存列值

时间:2019-03-04 04:41:44

标签: python ms-word

如何只打印MS字表第二列中的值。 我的代码在下面打印第一列值,第二列值 一个低于另一个。 示例:单词表格式:

colm 1       column2
SR#          32213
Part#        K9843
PartDesc     SteamBolt

---我的代码---

import docx
from docx import Document
wordDoc = Document('c:\python-programs\ssis-test.docx')
for table in wordDoc.tables:
    for row in table.rows:
        for cell in row.cells:
            print (cell.text)

---结束我的代码--- 上面的代码打印如下。

SR#
32213
Part# 
K9843
PartDesc
SteamBolt

我只想打印值32213, K9843SteamBolt(仅在第二栏中)。

Python版本:3.5.2,带有docx库。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

Docx可能不是最好的方法,因为它仅提供Word api的一小部分,并且尽管出现在GitHub上,但多年来却没有得到显着发展。

更好的方法是使用Win32Com,它可以完全访问Com对象模型(例如Office应用程序)。使用Win32com,您还希望使用makepy为想要使用的对象模型生成智能感知。

在这里快速浏览会有所帮助

http://timgolden.me.uk/pywin32-docs/html/com/win32com/HTML/QuickStartClientCom.html

VBA解决您的问题的方法是

Option Explicit

Sub test()

    Dim my_table                    As Word.Table
    Dim my_row                      As Word.Row
    Dim my_text                     As String

    For Each my_table In ActiveDocument.Tables

        For Each my_row In my_table.Range.Rows

            my_text = my_row.Range.Cells(2)

        Next

    Next

End Sub

但这不能保证,因为如果您的表格包含已合并的单元格,则Word会处理表格问题。您可以使用.Uniform属性测试将产生问题的表。如果需要,我将让您研究如何处理不统一的表格。