代码实现了在本机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
2051

被折叠的 条评论
为什么被折叠?



