有没有办法用Python编辑嵌入在Word文档中的Excel电子表格?
我想用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电子表格)。
1 个回答
0
在Word文档中似乎没有直接编辑Excel表格的方法。
所以我找到了解决办法:
与其在Word文档里编辑嵌入的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
search_range.Find.Execute(find_str)
if search_range.Find.Found:
search_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
# of the Word document (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文件的完整路径。
[excel_table]
是占位符,必须放在Word文档的正文中(不能嵌套在其他地方)
备注:
即使“理论上”win32com
应该能找到Word文档中的Excel表格:
在我的情况下,找到了一个对象(docx
没有找到任何),但它并没有被识别为Excel表格,无法以Excel表格的形式打开,即使这个Excel表格之前是通过win32com
插入的。
我继续使用docx
和openpyxl
来编辑Word和Excel文件,然后再插入。win32com
似乎要慢很多,而我已经用docx
和openpyxl
写好了编辑的代码。