python中通过http地址打开office文件

部署运行你感兴趣的模型镜像

代码实现了在本机6000端口提供web服务,访问地址,打开word或excel进行编辑。后面准备改进为编辑保存后自动上传到服务器:

from flask import Flask, request, jsonify, send_from_directory
import os
import pythoncom
import threading
import win32com.client as win32
#pip install pywin32 flask

app = Flask(__name__)

@app.route('/edit-word', methods=['GET'])
def edit_word():
    # 创建并启动线程
    thread = threading.Thread(target=editWord)
    thread.start()
    thread.join()
    return jsonify({"message": "Word document opened for editing"}), 200

def editWord():
    file_path  = "F:/bzyy/python/officeWeb/v1/txl.docx"
    if not os.path.exists(file_path):
       print(f"文件不存在{file_path}")
       return
    pythoncom.CoInitialize()
    try:
      word = win32.gencache.EnsureDispatch('Word.Application')  #微软office打开
      #word = win32.gencache.EnsureDispatch('Kwps.Application') #WPS打开
      word.Visible = True  # 使界面可见
      word.WindowState = 1  #窗口最大化
      word.Visible = True  # 使界面可见
      wb = word.Documents.Open(file_path)
      wb.Activate()  # 激活 
      wb.WindowState = 1  #窗口最大化
      wb.Activate()  # 激活      
    except Exception as e:
      print(f"操作失败: {e}")
    finally:
      pythoncom.CoUninitialize()
    

@app.route('/edit-excel', methods=['GET'])
def edit_excel():
    # 创建并启动线程
    thread = threading.Thread(target=editXls)
    thread.start()
    thread.join()
    return jsonify({"message": "Excel workbook opened for editing"}), 200

def editXls():
    file_path  = "F:/bzyy/python/officeWeb/v1/txl.xlsx"
    if not os.path.exists(file_path):
       print(f"文件不存在{file_path}")
       return
    pythoncom.CoInitialize()
    try:
      excel = win32.gencache.EnsureDispatch('Excel.Application')
      excel.WindowState = -4137  #窗口最大化
      excel.Visible = True  # 使Excel界面可见
      wb = excel.Workbooks.Open(file_path)
      wb.Activate()  # 激活工作簿以便用户编辑
    except Exception as e:
      print(f"操作失败: {e}")
    finally:
      pythoncom.CoUninitialize()
    

if __name__ == '__main__':
    app.run(debug=True,port=6000)
    
#测试地址:
#http://127.0.0.1:6000/edit-excel
#http://127.0.0.1:6000/edit-word

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值