You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Ajax请求发送OfficeJS二维数组至Flask后端?

Fixing Large 2D Array Transfer from OfficeJS Excel to Flask via jQuery Ajax

It sounds like your issue is likely related to payload size limits or incorrect request configuration—since small arrays work but large ones fail with readyState:0, that usually means the request isn't making it to the server (or gets rejected early). Let's walk through the fixes step by step.

1. Fix Flask Server to Accept Large Payloads

Flask has a default maximum request size limit (usually around 1MB). Your 3673×11 array is probably exceeding this. Here's how to increase it and properly handle JSON data:

from flask import Flask, request, jsonify
import pandas as pd

app = Flask(__name__)
# Set max content length to 16MB (adjust based on your data size)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB

@app.route('/upload-excel-data', methods=['POST'])
def upload_excel_data():
    try:
        # Parse JSON directly from the request body
        data = request.get_json()
        # Convert the 2D array to a pandas DataFrame
        df = pd.DataFrame(data)
        # Add your processing logic here...
        return jsonify({"status": "success", "row_count": len(df)})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 400

Make sure you're using request.get_json() instead of form data parsers—this tells Flask to expect JSON in the request body.

2. Correct jQuery Ajax Configuration

Your client-side code needs to properly format the JSON and set the right headers. Here's the fixed OfficeJS + jQuery code:

// Retrieve data from Excel and send to Flask
Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getItem("SheetName");
    const range = sheet.getRange("A1:K3673");
    range.load("values");
    await context.sync();
    
    const excelData = range.values;
    
    // Send data via jQuery Ajax
    $.ajax({
        url: "/upload-excel-data",  // Replace with your actual Flask endpoint
        type: "POST",
        contentType: "application/json",  // Critical: tells server to parse as JSON
        data: JSON.stringify(excelData),  // Convert 2D array to valid JSON string
        timeout: 30000,  // Increase timeout to 30s for large payloads
        success: (response) => {
            console.log("Upload successful:", response);
        },
        error: (xhr, status, error) => {
            console.error("Upload failed:", status, error);
        }
    });
}).catch(error => {
    console.error("Excel data retrieval error:", error);
});

Key Fixes in the Client Code:

  • contentType: "application/json": Ensures Flask recognizes the request body as JSON (without this, it'll try to parse it as form data, which fails for large arrays).
  • JSON.stringify(excelData): Converts the raw 2D array to a valid JSON string—don't pass the array directly, as jQuery will incorrectly encode it as form data.
  • Increased timeout: Large payloads take longer to transmit; 30 seconds should be sufficient for your dataset.

3. Validate JSON Before Sending (Optional)

If you're still hitting issues, check for invalid JSON characters in your Excel data (like unescaped quotes) with this quick validation step:

try {
    const jsonString = JSON.stringify(excelData);
    console.log("JSON is valid. Size:", jsonString.length, "characters");
    // Proceed with Ajax request
} catch (e) {
    console.error("Invalid JSON detected in Excel data:", e);
}

4. Alternative: Use Fetch API Instead of jQuery

If jQuery is still causing problems, try the native Fetch API—it's often more reliable for large payloads:

// After retrieving excelData from Excel
fetch("/upload-excel-data", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify(excelData),
    signal: AbortSignal.timeout(30000),  // 30s timeout
})
.then(response => response.json())
.then(data => console.log("Success:", data))
.catch(error => console.error("Error:", error));

Why Your Original Request Failed

  • Payload too large: Flask rejected the request before processing it due to its default size limit.
  • Incorrect content type: Without explicitly setting contentType: "application/json", Flask couldn't parse the JSON string.
  • Timeout: The request took longer than jQuery's default timeout to send, so it was aborted early.

These fixes should resolve your issue and let you transfer the full 2D array successfully. Let me know if you run into any other roadblocks!

内容的提问来源于stack exchange,提问作者Tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:23:46