You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:编写Python代码实现Excel表格数据转Word表格指定列

Got it, let's tackle this problem step by step. Here's a practical, easy-to-follow solution using Python libraries that handle Excel and Word files seamlessly:

Prerequisites

First, install the required libraries to work with Excel and Word documents:

pip install openpyxl python-docx
Step-by-Step Code Implementation

This script will read rows from an Excel sheet and write the data to a specified column in a Word table. I've added comments to explain each part clearly:

from openpyxl import load_workbook
from docx import Document
from docx.enum.table import WD_ALIGN_VERTICAL

def copy_excel_to_word(excel_path, word_path, excel_sheet, word_table_idx, target_col_idx):
    # Load Excel workbook and target sheet
    excel_workbook = load_workbook(excel_path, data_only=True)
    excel_sheet = excel_workbook[excel_sheet]

    # Load Word document
    word_doc = Document(word_path)

    # Check if the target table exists in Word
    if word_table_idx >= len(word_doc.tables):
        raise ValueError(f"Word doc only has {len(word_doc.tables)} tables — can't find table at index {word_table_idx}")
    
    target_table = word_doc.tables[word_table_idx]

    # Iterate through Excel rows (skip header row if your Excel has one; adjust min_row as needed)
    for row_num, excel_row in enumerate(excel_sheet.iter_rows(min_row=2, values_only=True), start=1):
        # Add new rows to Word table if it doesn't have enough rows
        if row_num >= len(target_table.rows):
            new_row = target_table.add_row()
            # Optional: Set vertical alignment for better formatting
            for cell in new_row.cells:
                cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
        
        # Write Excel data to the target column (here we take the first cell of each Excel row; adjust as needed)
        target_cell = target_table.rows[row_num].cells[target_col_idx]
        target_cell.text = str(excel_row[0]) if excel_row[0] is not None else ""

    # Save the updated Word document
    updated_word_path = f"updated_{word_path}"
    word_doc.save(updated_word_path)
    print(f"Success! Data copied. Check {updated_word_path}")

# Example usage — replace these values with your actual file details
if __name__ == "__main__":
    try:
        copy_excel_to_word(
            excel_path="your_data.xlsx",
            word_path="your_template.docx",
            excel_sheet="Sheet1",
            word_table_idx=0,  # Index of the table in Word (starts at 0)
            target_col_idx=2   # Target column in Word table (starts at 0)
        )
    except Exception as e:
        print(f"Oops, something went wrong: {str(e)}")
Key Notes & Customizations
  • Excel Header Handling: If your Excel doesn't have a header row, change min_row=2 to min_row=1 in the iter_rows call.
  • Target Column Adjustment: The target_col_idx uses 0-based indexing — so the 3rd column in your Word table would be index 2.
  • Copying Entire Rows: If you want to copy multiple cells from an Excel row to multiple Word columns, modify the code to loop through excel_row elements and map them to corresponding Word table cells.
  • Empty Values: The script converts None values (empty Excel cells) to empty strings to avoid writing "None" in your Word document.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:58:06