簡體   English   中英

使用 Ajax 和 Flask 下載 excel

[英]download excel by using Ajax andFlask

我正在嘗試使用 Ajax 調用從 flask 下載 excel。 它顯示響應代碼為 200 但 excel 未下載,錯誤消息如下。

Ajax 請求:

$("#genExcel").on("點擊", function() { var xhttp = new XMLHttpRequest();

                // Data to post
                var dataarray = {};

                // Use XMLHttpRequest instead of Jquery $ajax

                xhttp.onreadystatechange = function() {
                    var a;
                    if (xhttp.readyState === 4 && xhttp.status === 200) {
                        // Trick for making downloadable link
                        a = document.createElement('a');
                        const objectURL = window.URL.createObjectURL(xhttp.response);
                        a.href = objectURL

                        //const objectURL = URL.createObjectURL(object)

                        // Give filename you wish to download
                        a.download = "test-file.xlsx";
                        a.style.display = 'none';
                        document.body.appendChild(a);
                        a.click();
                    }
                };
                // Post data to URL which handles post request
                xhttp.open("POST", '/genexcel');
                xhttp.setRequestHeader("Content-Type", "application/json");
                // You should set responseType as blob for binary responses
                //xhttp.responseType = 'blob';
                xhttp.send(JSON.stringify(dataarray));
            });

Flask function:

@app.route('/genexcel', methods=["GET", "POST"])
def createExcel():
    if request.method == 'POST':
        data = request.json  
        # process json data        
        return send_file(strIO, attachment_filename='test.xlsx',  as_attachment=True)

錯誤:

1 [僅報告] 拒絕將字符串評估為 JavaScript,因為“unsafe-eval”不是以下內容安全策略指令中允許的腳本源:“script-src * blob:”。

2 未捕獲的類型錯誤:無法在“URL”上執行“createObjectURL”:未找到與提供的簽名匹配的 function。

at XMLHttpRequest.xhttp.onreadystatechange

錯誤和響應

希望我對您的理解正確。 這是一個使用您提供的數據數組的非常簡單的示例。 您可以修改以滿足您的需求:

Flask 功能

from flask import Flask, render_template, request, url_for, send_file
import xlsxwriter

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/genexcel', methods=["GET", "POST"])
def createExcel():
    if request.method == 'POST':
        data = request.get_json(force=True)
        # process json data
        createExcel(data['data'])

    file_path = 'static/files/test.xlsx'
    return send_file(file_path, attachment_filename='test.xlsx', as_attachment=True)

def createExcel(data):
    workbook = xlsxwriter.Workbook('static/files/test.xlsx')
    worksheet = workbook.add_worksheet()

    row_no = 0
    col_no = 0
    for row in data:
        col_no = 0
        for entry in row:
            worksheet.write(row_no, col_no, entry)
            col_no += 1
        row_no += 1

    workbook.close()

app.run(debug=True, port=5010)

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Test</title>
  </head>
  <body>
    Testing
    <button id="genExcel">Direct Download</button>
    <button id="genExcelFlask">Flask Download</button>
  </body>

  <script>
    var btn = document.getElementById("genExcel");
    var btnFlask = document.getElementById("genExcelFlask");
    var dataArray = {
      data: [
        [1, "A", 100],
        [2, "B", 200],
      ],
    };

    btn.addEventListener("click", (e) => {
      fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then((resp) => resp.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          // the filename you want
          a.download = "todo-1.json";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          alert("your file has downloaded!"); // or you know, something with better UX...
        })
        .catch(() => alert("oh no!"));
    });

    btnFlask.addEventListener("click", (e) => {
      console.log(JSON.stringify(dataArray));

      fetch("{{ url_for('createExcel') }}", {
        method: "post",
        body: JSON.stringify(dataArray),
      })
        .then((resp) => resp.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          // the filename you want
          a.download = "test.xlsx";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          alert("your file has downloaded!"); // or you know, something with better UX...
        })
        .catch(() => alert("oh no!"));
    });
  </script>
</html>

這是一個使用提取 API 的示例。 第一個按鈕只是直接下載 JS。 第二個按鈕使用 Flask 路由進行下載。 希望能幫助到你。

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Test</title>
  </head>
  <body>
    Testing
    <button id="genExcel">Direct Download</button>
    <button id="genExcelFlask">Flask Download</button>
  </body>

  <script>
    var btn = document.getElementById("genExcel");
    var btnFlask = document.getElementById("genExcelFlask");

    btn.addEventListener("click", (e) => {
      fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then((resp) => resp.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          // the filename you want
          a.download = "todo-1.json";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          alert("your file has downloaded!"); // or you know, something with better UX...
        })
        .catch(() => alert("oh no!"));
    });

    btnFlask.addEventListener("click", (e) => {
      fetch("{{ url_for('createExcel') }}")
        .then((resp) => resp.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          // the filename you want
          a.download = "test.xlsx";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          alert("your file has downloaded!"); // or you know, something with better UX...
        })
        .catch(() => alert("oh no!"));
    });
  </script>
</html>

Flask Function

from flask import Flask, render_template, request, url_for, send_file

@app.route('/genexcel', methods=["GET", "POST"])
def createExcel():
    if request.method == 'POST':
        data = request.json
        print(data)
        # process json data

    file_path = 'static/files/test.xlsx'
    return send_file(file_path, attachment_filename='test.xlsx', as_attachment=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM