程序功能:
1、根据excel表格中的内容产生一个word文档
2、第一次当选中excel中某一单元格时,在word中生成:本端:单元格内相同的内容
第二次选中单元格的内容时,在word中生成:应用:单元格中相同的内容
第三次选中单元格时,在word中生成:对端:单元格中相同的内容
3、当两次或多次选中同一excel中的单元格,则替换word中的内容
4、自动打开输入的excel文件方便用户对单元格进行选中
5、自动打开输出的word方便用户观察输出情况
6、选择一个excel中的单元格,word中输出一条文字
7、当选中多个单元格时合并相同的文字,不同的文字根据单元格的前后顺序在中间加入顿号
8、打开excel后检测用户的操作,在用户选中单元格后,再在word中生成文字
import openpyxl
from docx import Document
import os
def generate_word_from_excel(excel_file, word_file):
# 打开Excel文件
workbook = openpyxl.load_workbook(excel_file)
sheet = workbook.active
# 创建Word文档
document = Document()
# 用于存储选中单元格的内容和上一次选中的内容
selected_contents = []
prev_selected_content = None
def add_content_to_word(content):
paragraph = document.add_paragraph(content)
# 监听用户在Excel中选中单元格并生成文字到Word文档
def on_cell_select(event):
nonlocal selected_contents, prev_selected_content
current_content = str(sheet[event.coordinate].value)
if not current_content:
return
selected_contents.append(current_content)
if len(selected_contents) == 1:
add_content_to_word("本端:" + current_content)
else:
if current_content != prev_selected_content:
if selected_contents.count(current_content) > 1:
index = 0
for i, content in enumerate(selected_contents):
if content == current_content:
index += 1
document.paragraphs[-1].text = f"对端 {index}:{content}"
else:
document.paragraphs[-1].text = "应用:" + current_content
else:
document.paragraphs[-1].text = "对端:" + current_content
prev_selected_content = current_content
# 注册Excel的选中单元格事件监听器
sheet.cell_events = True
sheet.cell_selected = on_cell_select
# 自动打开输入的Excel文件
os.startfile(excel_file)
# 保存生成的Word文档
document.save(word_file)
# 打开输出的Word文件
os.startfile(word_file)
# 询问用户输入Excel文件的路径
excel_file_path = input("请输入Excel文件的路径:")
# 生成Word文档的路径
word_file_path = 'output.docx'
# 调用函数生成Word文档
generate_word_from_excel(excel_file_path, word_file_path)