当前位置:   article > 正文

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

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

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

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/439921?site
推荐阅读
相关标签
  

闽ICP备14008679号