在flask服务中远程读取该Excel的内容

在flask服务中远程读取该Excel的内容:

python 复制代码
from flask import Flask, jsonify  
import requests  
import pandas as pd  
import os  
import tempfile  
  
app = Flask(__name__)  
  
@app.route('/read_excel', methods=['GET'])  
def read_excel():  
    # Excel 文件的 URL  
    excel_url = 'https://xxx.xxx.xlsx'  
      
    # 发送请求并下载文件  
    response = requests.get(excel_url)  
      
    # 确保请求成功  
    if response.status_code != 200:  
        return jsonify({'error': 'Failed to retrieve Excel file'}), 400  
      
    # 创建一个临时文件来保存 Excel 文件  
    with tempfile.NamedTemporaryFile(delete=False) as tmp:  
        tmp.write(response.content)  
        tmp_file_path = tmp.name  
      
    try:  
        # 读取 Excel 文件  
        df = pd.read_excel(tmp_file_path)  
          
        # 这里可以处理数据,比如转换成 JSON 格式  
        data = df.to_json(orient='records')  
          
        # 返回数据  
        return jsonify(data)  
      
    except Exception as e:  
        # 如果发生错误,返回错误信息  
        return jsonify({'error': str(e)}), 500  
      
    finally:  
        # 删除临时文件  
        os.remove(tmp_file_path)  
  
if __name__ == '__main__':  
    app.run(debug=True)
相关推荐
千寻girling几秒前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
stark张宇23 分钟前
构建第一个AI聊天机器人:Flask+DeepSeek+Postgres实战
人工智能·postgresql·flask
databook4 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风5 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风5 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei21 小时前
python 抽象基类
python
用户83562907805121 小时前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm