要将 Excel 中的表格数据插入到 Word 文档中,可以使用pandas
和python-docx
库来实现。以下是一个示例代码:
首先,请确保已经安装了pandas
和python-docx
库。如果尚未安装,可以使用以下命令通过pip
进行安装:
plaintext
pip install pandas python-docx
示例代码如下:
python
import pandas as pd
from docx import Document
def insert_excel_table_to_word(excel_file, sheet_name, word_file):
# 读取 Excel 文件中的指定工作表
df = pd.read_excel(excel_file, sheet_name=sheet_name)
# 创建 Word 文档对象
doc = Document()
# 添加表格到 Word 文档
table = doc.add_table(rows=df.shape[0], cols=df.shape[1])
# 填写表格内容
for i, row in df.iterrows():
for j, value in enumerate(row):
table.cell(i, j).text = str(value)
# 保存 Word 文档
doc.save(word_file)
# 指定 Excel 文件路径、工作表名称和要保存的 Word 文件路径
excel_file_path = "your_excel_file.xlsx"
sheet_name = "your_sheet_name"
word_file_path = "output_word_file.docx"
insert_excel_table_to_word(excel_file_path, sheet_name, word_file_path)
在上述代码中,定义了一个名为insert_excel_table_to_word
的函数,它接受 Excel 文件路径、要读取的工作表名称以及要保存的 Word 文件路径作为参数。
首先,使用pandas
的read_excel
函数读取 Excel 文件中的指定工作表数据,并将其存储在df
变量中。
然后,使用Document
类创建一个新的 Word 文档对象。通过add_table
方法添加一个与 Excel 表格大小相同的表格到 Word 文档中。
接下来,使用循环遍历 Excel 表格中的每一行和每一列,将数据转换为字符串并填入到 Word 表格的相应单元格中。
最后,使用save
方法保存 Word 文档。
请将代码中的"your_excel_file.xlsx"
替换为实际的 Excel 文件路径,"your_sheet_name"
替换为要读取的工作表名称,"output_word_file.docx"
替换为输出的 Word 文件路径。运行代码后,将会把指定 Excel 工作表中的表格数据插入到指定的 Word 文档中。
注意,这里假设 Excel 表格中的数据都是简单的文本或数字类型。如果表格中包含其他复杂的数据类型或格式,可能需要进行进一步的处理或转换。此外,还需确保 Excel 文件和代码在同一目录下,或者在文件路径中使用正确的绝对路径或相对路径。