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

问题描述 投票:0回答:1

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

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版本:带有docx库的3.5.2

感谢您的帮助。

python ms-word
1个回答
0
投票

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

更好的方法是使用Win32Com,它可以完全访问Com对象模型(例如办公应用程序)。使用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属性会产生问题的表。你如何处理非统一表我会留给你研究,如果你需要。

© www.soinside.com 2019 - 2024. All rights reserved.