有没有办法使用Python编辑嵌入Word文档中的Excel电子表格?

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

我想使用 Python (3.10.13) 编辑嵌入 Word 文档中的 Excel 表格。

我可以使用

from docx import Document
编辑 Word 文档的所有表格/文本,但无法访问嵌入的 Excel 表格。

我对这个主题很陌生,所以除了以下方法之外,我还没有想出太多(到目前为止):

from docx import Document
doc = Document(complete_file_path)
#....
for table in doc.tables:
  print(table)

#or
#....
for shape in doc.inline_shapes:
  print(shape)

我的主要问题是我根本找不到表(

doc.tables
doc.inline_shapes
没有元素=>循环被跳过)。

这个问题既存在于我真正的“模板”Word 文件中,也存在于一个简单快速地创建集成了 Excel 表格的虚拟 Word 文档中(插入 => 表格 => Excel 电子表格)

python excel ms-word
1个回答
0
投票

似乎没有直接的方法可以在 Word 文档中编辑 Excel 表格。

因此我的解决方案如下:

我没有编辑包含的 Excel 表格,而是单独编辑和保存 Excel 表格,然后使用

win32com
将其插入到占位符的位置:

import win32com.client

def insert_Excel_table_into_Word_document(full_doc_path, full_excel_path):
    # Open Word application
    word_app = win32com.client.Dispatch("Word.Application")

    # Open Word document
    word_doc = word_app.Documents.Open(full_doc_path)

    # Search for the placeholder in the document
    find_str = "[excel_table]"
    search_range = word_doc.content
    such_range.Find.Execute(find_str)

    if such_range.Find.Found:
        such_range.Text = ""
        # Placeholder found, insert Excel table
        search_range.Collapse(0) 
        
        excel_range = search_range.InlineShapes.AddOLEObject(
            ClassType="Excel.Sheet",
            FileName=full_excel_path,
            LinkToFile=False,
            DisplayAsIcon=False
        )

        # Adjust the Excel table width so that the page margins 
        # (if exceeded) are no longer exceeded
        page_width = word_doc.PageSetup.PageWidth - (word_doc.PageSetup.LeftMargin
                                                     + word_doc.PageSetup.RightMargin)
        if excel_range.Width > page_width:
            excel_range.Width = page_width - 10

    else:
        print("No placeholder found.")

    # Save Word document
    # new_doc_path = r"some\different_path\if\you_want\different_save_file"
    # word_doc.SaveAs(new_doc_path)
    # otherwise:
    word_doc.Save()

    word_doc.Close()
    word_app.Quit()

full_doc_path
full_excel_path
对应相应 Word 或 Excel 文件的完整文件路径。

备注:
即使“理论上”

win32com
应该能够在Word文档中找到Excel表格:
在我的例子中,找到了一个对象(
docx
没有找到),但它没有被识别为 Excel 表格,并且无法打开,即使这个 Excel 表格之前是由
win32com
插入的。
在插入之前,我继续使用
docx
openpyxl
编辑 Word 和 Excel 文件。
win32com
似乎慢得多,我已经使用
docx
openpyxl
进行了编辑编码。

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