在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)
相关推荐
查士丁尼·绵18 小时前
笔试-九宫格三阶积幻方
python·九宫格·三阶积幻方
l1t20 小时前
DeepSeek辅助利用搬移底层xml实现快速编辑xlsx文件的python程序
xml·开发语言·python·xlsx
大飞记Python20 小时前
部门管理|“编辑部门”功能实现(Django5零基础Web平台)
前端·数据库·python·django
查士丁尼·绵1 天前
笔试-羊狼过河
python
摸鱼的老谭1 天前
构建Agent该选Python还是Java ?
java·python·agent
鄃鳕1 天前
python 字典 列表 类比c++【python】
c++·python
可触的未来,发芽的智生1 天前
新奇特:黑猫警长的纳米世界,忆阻器与神经网络的智慧
javascript·人工智能·python·神经网络·架构
程序员三藏1 天前
Jmeter接口测试与压力测试
自动化测试·软件测试·python·测试工具·jmeter·接口测试·压力测试
烛阴1 天前
用 Python 揭秘 IP 地址背后的地理位置和信息
前端·python
大宝剑1701 天前
python环境安装
开发语言·python