You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用Python-Docx将Excel文件数据插入Word文档?

Hey there! I’ve tackled similar tasks before, so let’s break down how to make this work with Python-Docx plus a couple of helper libraries—depending on whether you want to paste Excel data as a native Word table or embed the actual Excel file as an editable object in your Word document.


Option 1: Insert Excel Data as a Static Word Table

This is perfect if you just need to display Excel content as a formatted Word table (no direct edit access to the original Excel file required).

First, install the required libraries:

pip install python-docx openpyxl

Here’s a complete, ready-to-use code snippet:

from docx import Document
from openpyxl import load_workbook

def excel_to_word_table(excel_path, word_output_path, sheet_name="Sheet1"):
    # Load the Excel workbook and target sheet
    excel_workbook = load_workbook(excel_path)
    target_sheet = excel_workbook[sheet_name]
    
    # Initialize a new Word document
    word_doc = Document()
    
    # Add a heading (customize as needed)
    word_doc.add_heading("Imported Excel Data", level=1)
    
    # Create a Word table matching Excel's row/column count
    table = word_doc.add_table(rows=target_sheet.max_row, cols=target_sheet.max_col)
    table.style = "Table Grid"  # Apply a clean, grid-based style
    
    # Fill the table with Excel data, handling empty cells
    for row_idx, excel_row in enumerate(target_sheet.iter_rows(values_only=True)):
        for col_idx, cell_value in enumerate(excel_row):
            # Convert None values (empty cells) to empty strings
            table.cell(row_idx, col_idx).text = str(cell_value) if cell_value is not None else ""
    
    # Save the final Word document
    word_doc.save(word_output_path)
    print(f"Success! Word document saved to: {word_output_path}")

# Example usage
if __name__ == "__main__":
    EXCEL_FILE_PATH = "path/to/your/target_excel.xlsx"
    WORD_OUTPUT_PATH = "path/to/your/output_word.docx"
    excel_to_word_table(EXCEL_FILE_PATH, WORD_OUTPUT_PATH)

Option 2: Embed Excel as an Editable OLE Object

If you want recipients to double-click the object and open the original Excel file (to edit data directly), you’ll need pywin32 (Windows-only, since it interacts with Microsoft Office’s COM API).

First install the library:

pip install pywin32

Here’s the code to embed the Excel file:

import win32com.client as win32
import os

def embed_excel_object(excel_path, word_output_path):
    # Initialize Word in background mode
    word_app = win32.Dispatch("Word.Application")
    word_app.Visible = False  # Set to True if you want to see the process in action
    
    try:
        # Create a new Word document
        word_doc = word_app.Documents.Add()
        
        # Add a label before the embedded object
        word_doc.Content.InsertAfter("Embedded Excel File (double-click to edit):\n")
        word_doc.Content.MoveEnd()
        
        # Insert the Excel OLE object
        word_doc.Shapes.AddOLEObject(
            ClassType="Excel.Sheet.12",
            FileName=excel_path,
            LinkToFile=False,  # Set to True if you want to link (not embed) the file
            DisplayAsIcon=True,  # Show Excel icon instead of a data preview
            IconLabel=os.path.basename(excel_path)
        )
        
        # Save and close the document
        word_doc.SaveAs(word_output_path)
        word_doc.Close()
        print(f"Success! Excel embedded in: {word_output_path}")
    finally:
        # Ensure Word closes completely to avoid lingering processes
        word_app.Quit()

# Example usage
if __name__ == "__main__":
    EXCEL_FILE_PATH = "path/to/your/target_excel.xlsx"
    WORD_OUTPUT_PATH = "path/to/your/embedded_word.docx"
    embed_excel_object(EXCEL_FILE_PATH, WORD_OUTPUT_PATH)

Quick Notes:

  • Option 1: Data is static—changes to the original Excel won’t update the Word table. Use this for reports where you just need to display fixed data.
  • Option 2: Windows-only, and requires Microsoft Office to be installed. The embedded object is fully editable.
  • Always use absolute file paths if your script isn’t in the same directory as your Excel/Word files to avoid errors.

内容的提问来源于stack exchange,提问作者Poorva M

火山引擎 最新活动