excel 导出

发布于:2025-08-09 ⋅ 阅读:(39) ⋅ 点赞:(0)

接口

@export_data_bp.route('/downloadPointsData', methods=['GET'])
def downloadPointsData():
    # 获取必要参数
    date_ = request.args.get('date_')
    ta_num = request.args.get('ta_num', type=int)

    # 查询点位数据
    data = iotdb_utils.IotdbData()
    if ta_num > 10:
        data.points = Points_Stable.points_str[ta_num - 10]
    else:
        data.points = Points_All.points_str[ta_num]
    data.start_time = date_
    data.end_time = date_utils.days_add(date_, 1)
    df = iotdb_utils.get_df(data)

    df.index = df.index.strftime('%Y-%m-%d %H:%M:%S')
    
    # 将 DataFrame 写入内存中的 Excel 文件
    output = io.BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df.to_excel(writer, index=True, sheet_name='PointsData')
    output.seek(0)  # 重置指针到文件开头
    
    # 返回文件下载
    return send_file(
        output,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        as_attachment=True,
        download_name=f'{ta_num}ta_points_data_{date_}.xlsx'
    )

前端使用fetch

response.blob() 

response可以直接获取blob对象

        _handleDownload_fetch(item) {            
            // 使用 fetch API
            fetch(`/downloadPointsData?date_=${item.date_}&ta_num=${this.ta_num}`, {
                method: 'GET',
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('下载失败');
                }
                return response.blob(); // 获取 Blob 数据
            })
            .then(blob => {
                // 创建下载链接
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `${this.ta_num}ta_points_data_${item.date_}.xlsx`;; // 设置文件名
                document.body.appendChild(a);
                a.click();
                
                // 清理
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                // alert('下载成功');
                this.showDownloadModal = false;
            })
            .catch(error => {
                console.error('下载错误:', error);
                alert('下载失败: ' + error.message);
                this.showDownloadModal = false;
            });
        },

前端使用axios

new Blob([response.data]

blob 对象要自己使用 response.data 和 response.headers['content-type'] 封装

        _handleDownload_axios(item) {            
            // 使用 axios API
            axios.get(`/downloadPointsData?date_=${item.date_}&ta_num=${this.ta_num}`, {
                responseType: 'blob', // 关键:告诉 Axios 返回 Blob 数据
            })
            .then(response => {
                if (response.status != 200) {
                    throw new Error('下载失败');
                }
                // 直接从 response.data 获取 Blob 对象(无需手动转换)
                const blob = new Blob([response.data], {
                    type: response.headers['content-type'] // 可选:设置 MIME 类型
                });
                return blob;
            })
            .then(blob => {
                // 创建下载链接
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `${this.ta_num}ta_points_data_${item.date_}.xlsx`; // 设置文件名
                document.body.appendChild(a);
                a.click();
                
                // 清理
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                // alert('下载成功');
                this.showDownloadModal = false;
            })
            .catch(error => {
                console.error('下载错误:', error);
                alert('下载失败: ' + error.message);
                this.showDownloadModal = false;
            });
        },

前端使用接口直接下载

window.location.href

无法获取接口什么时候调用完成

window.location.href = `/downloadPointsData?date_=${item.date_}&ta_num=${this.ta_num}`;


网站公告

今日签到

点亮在社区的每一天
去签到