weixin_48513740 2023-08-11 02:39 采纳率: 0%
浏览 21
已结题

为什么这个代码实现不了选中单元格后在word中生成文字(相关搜索:用python)

程序功能:
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)


  • 写回答

7条回答 默认 最新

  • threenewbee 2023-08-11 06:59
    关注

    你的代码一眼看就是GPT生成的,这种代码看着一顿操作气势如虹,其实错误百出。

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 8月14日
  • 赞助了问题酬金50元 8月11日
  • 修改了问题 8月11日
  • 创建了问题 8月11日

悬赏问题

  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗