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

JavaScript传值到Python写入xls文件内容空白如何解决

问题描述

需要实现JavaScript端获取页面指定数值,传入Python后端函数后写入xls/xlsx文件,当前存在两个异常:

  • 代码运行后生成的xls文件内容为空白
  • 尝试直接传入值列表而非逐个传值时,Python端使用request.args.getlist()接收存在异常

原问题代码

Python端(基于Flask、xlwt)

import xlwt
from xlwt import Workbook

    @app.route('/Import_to_excel',
    methods=['GET', 'POST'])
    def Import_to_excel():
    
        x = request.args.get('id0')
        y = request.args.get('id1')
        z = request.args.get('id2')
    
        array = [ ip, app, ver]
        
        wb = Workbook()
        sheet1 = wb.add_sheet('Sheet 1')
    
        sheet1.write(0, 0, array[0])
        sheet1.write(0, 1, array[1])
        sheet1.write(0, 2, array[2])

        wb.save('xlwt example.xls')
        
        return "success"

JavaScript端

function Import_to_excel()
{
    id0 = document.getElementById("x").text
    id1 = document.getElementById("y").value
    id2 = document.getElementById("z").value

    const input_values = [ id0, id1, id2];

 fetch('http://127.0.0.1:5000/Import_to_excel?id0='+id0
 ).then(resp => resp.json())

 fetch('http://127.0.0.1:5000/Import_to_excel?id1='+id1
 ).then(resp => resp.json())

 fetch('http://127.0.0.1:5000/Import_to_excel?id2='+id2
 ).then(resp => resp.json())
}
问题根因
  • 前端请求逻辑错误:分3次独立发送fetch请求,每次仅携带1个参数。后端每收到一次请求就会重新生成、写入、保存一次Excel文件,前两次写入的文件会被后一次覆盖,最后一次请求仅携带1个有效参数,其余位置写入空值,最终生成的文件自然为空白状态。
  • Python端变量名不匹配:从请求参数中取出的变量为x/y/z,组装写入数组时误用了从未定义的ip/app/ver,代码运行时会直接抛出NameError异常中断执行。
  • 前端DOM取值错误:.text不是标准DOM属性,表单类元素(input/select/textarea)取值统一用.value,普通文本节点取值用.textContent。
  • 前后端响应格式不匹配:后端返回纯字符串"success",前端却调用resp.json()按JSON格式解析,会直接触发解析错误。
  • getlist用法错误:request.args.getlist()仅能识别同一次请求中同名的多值参数,之前要么分多次传参、要么参数名不一致,无法正确获取列表。
修复方案

Python端修复代码

import xlwt
from flask import Flask, request
app = Flask(__name__)

@app.route('/Import_to_excel', methods=['GET', 'POST'])
def Import_to_excel():
    # 单参数逐个接收写法
    x = request.args.get('id0')
    y = request.args.get('id1')
    z = request.args.get('id2')
    write_data = [x, y, z]

    # 列表接收写法(对应前端传同名ids参数)
    # write_data = request.args.getlist('ids')

    wb = xlwt.Workbook()
    sheet = wb.add_sheet('Sheet 1')
    for col, value in enumerate(write_data):
        sheet.write(0, col, value)
    wb.save('xlwt_example.xls')
    # 返回标准JSON格式,匹配前端解析逻辑
    return {"code": 200, "msg": "write success"}

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)

JavaScript端修复代码

function Import_to_excel() {
    // 统一取值:如果是表单元素全部用value,普通文本元素用textContent
    const id0 = document.getElementById("x").value;
    const id1 = document.getElementById("y").value;
    const id2 = document.getElementById("z").value;

    // 仅发送1次请求,携带所有参数,用encodeURIComponent转义特殊字符避免参数解析错误
    fetch(`http://127.0.0.1:5000/Import_to_excel?id0=${encodeURIComponent(id0)}&id1=${encodeURIComponent(id1)}&id2=${encodeURIComponent(id2)}`)
        .then(resp => resp.json())
        .then(res => console.log("Excel写入完成", res))
        .catch(err => console.error("请求异常", err));

    // 列表传参写法(对应后端getlist接收)
    // fetch(`http://127.0.0.1:5000/Import_to_excel?ids=${encodeURIComponent(id0)}&ids=${encodeURIComponent(id1)}&ids=${encodeURIComponent(id2)}`)
    //     .then(resp => resp.json())
    //     .then(res => console.log("Excel写入完成", res))
    //     .catch(err => console.error("请求异常", err));
}
补充说明
  • 所有需要写入Excel的参数必须在同一次请求中传给后端,禁止分多次请求重复写入覆盖文件。
  • 前后端参数名、变量名必须严格对应,避免出现变量未定义的低级错误。
  • 传参时统一用encodeURIComponent()处理参数值,避免参数中包含&、空格、中文等特殊字符时出现参数截断、解析错误。
  • 后端返回的数据格式要和前端解析方式匹配:返回JSON就用resp.json()解析,返回纯文本就用resp.text()解析。
  • xlwt库仅支持生成.xls格式文件,如果需要写入.xlsx格式,替换为openpyxl库即可,写入逻辑基本一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:18:20