要使用 Python 将 Excel 生成 Word 报告,您需要使用 Python 中的以下两个模块:

  1. openpyxl - 用于读取和写入 Excel 文件。
  2. python-docx - 用于创建和编辑 Word 文档。

下面是一个示例代码,它读取 Excel 文件中的数据,并将其写入 Word 文档。

import openpyxl
from docx import Document
from docx.shared import Inches

# 打开 Excel 文件
workbook = openpyxl.load_workbook('example.xlsx')
sheet = workbook.active

# 创建 Word 文档
document = Document()

# 添加标题
document.add_heading('Excel to Word Report', 0)

# 添加表格
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Name'
hdr_cells[1].text = 'Age'
hdr_cells[2].text = 'Gender'

# 从 Excel 中读取数据,并将其写入 Word 文档中的表格中
for row in sheet.iter_rows(min_row=2, values_only=True):
    row_cells = table.add_row().cells
    row_cells[0].text = row[0]
    row_cells[1].text = str(row[1])
    row_cells[2].text = row[2]

# 添加图片
document.add_picture('example.png', width=Inches(2.0))

# 保存 Word 文档
document.save('example.docx')

这将生成一个名为“example.docx”的 Word 文档,其中包含从 Excel 文件读取的数据和一张图片。当然,您可以根据需要修改代码以满足您的具体需求。

Python Excel 转 Word 报告:完整代码示例

原文地址: https://www.cveoy.top/t/topic/ok6V 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录