随笔 - 493  文章 - 0  评论 - 97  阅读 - 239万

axios请求导出数据到excel文件

客户端利用axios自己封装了一个request,文件名为http.js

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import axios from 'axios';
import history from './history';
 
export const baseUrl = '/api';
 
const request = axios; // or axios.create({})
request.defaults.baseURL = baseUrl;
request.interceptors.request.use(config => {
    // const { url, data } = config;
    // console.log(`send request[${url}]: ${JSON.stringify(data)}`);
    return config;
});
request.interceptors.response.use(
    response => {
        const {
            // config: { url },
            data,
        } = response;
        // console.log(`receive response[${url.replace(baseUrl, '')}]: ${JSON.stringify(data)}`);
        return data;
    },
    error => {
        console.log(`receive response[${'url'}]: ${JSON.stringify(error)}`);
        return Promise.reject(
            error && error.response && error.response.data && error.response.data.message ? error.response.data.message : error,
        );
    },
);
 
const method = {
    get: (url, data = {}) => {
        return request.get(url, { params: data });
    },
 
    post: (url, data = {}) => {
        return request.post(url, data);
    },
 
    export: (url, fileName = 'download.xlsx', data = {}) => {
        if (typeof fileName === 'object') {
            data = fileName;
            fileName = 'download.xlsx';
        }
 
        request({
            method: 'post',
            url,
            data,
            responseType: 'blob',
        })
            .then(res => {
                if (res.type === 'application/json') {
                    console.log('文件导出失败: ', res);
                    return;
                }
 
                const href = window.URL.createObjectURL(new Blob([res]));
 
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = href;
                link.setAttribute('download', fileName);
 
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(href);
            })
            .catch(error => {
                console.log('文件导出失败: ', error);
            });
    },
 
    form: (url, data = {}) => {
        const form = document.createElement('form');
        form.style = 'display:none;';
        form.method = 'post';
        form.action = baseUrl + (url[0] === '/' ? '' : '/') + url;
 
        const values = JSON.stringify(data);
        if (values !== '{}') {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'values';
            input.value = values;
            form.appendChild(input);
        }
 
        document.body.append(form);
 
        form.submit();
        form.remove();
    },
 
    all: (...https) => {
        return new Promise((resolve, reject) => {
            request
                .all(https)
                .then(
                    axios.spread((...resList) => {
                        // 多个请求都发送完毕,拿到返回的数据
                        resolve(resList);
                    }),
                )
                .catch(err => {
                    reject(err);
                });
        });
    },
};
 
export const http = (url, data, success, fail) => {
    return new Promise((resolve, reject) => {
        method
            .post(url, data)
            .then(res => {
                const { code } = res;
                if (code === 101) {
                    history.replace('/');
 
                    history.fail && fail();
                    reject();
                }
                if (code === 100 || code === 102) {
                    history.replace('/login');
 
                    fail && fail();
                    reject();
                } else {
                    success && success(res);
                    resolve(res);
                }
            })
            .catch(error => {
                fail && fail(error);
                reject(error);
            });
    });
};
 
export default method;

 另一个jsx中使用:

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
import React from 'react';
import * as antd from 'antd';
import request from '@/common/http';
 
const { Button } = antd;
 
class Wrapper extends React.Component {
    exportPaidUsers = () => {
        request.export('user/exportPaidUsers', '付费用户列表.xlsx');
    };
 
    // 渲染
    render() {
        return (
            <div>
                <div style={{ marginBottom: 30 }}>
                    <span>
                        <Button type='primary' onClick={this.exportPaidUsers.bind(this)}>
                            导出所有付费用户
                        </Button>
                    </span>
                </div>
            </div>
        );
    }
}
 
export default Wrapper;

 服务端php:

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
public static function download(PHPExcel $excel, String $fileName = 'download')
    {
        $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(preg_match('/msie/i', $ua)
            || preg_match('/edge/i', $ua)
            || preg_match('/trident/i', $ua)
        )
        {
            $fileName = urlencode($fileName);
        }
 
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header(sprintf('Content-Disposition: attachment;filename="%s.xlsx"', $fileName));
        header('Cache-Control: max-age=0');
 
        $ta[] = microtime(true);
 
        $writer = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $writer->save('php://output');
 
//      $ta[] = microtime(true);
 
        log_message2('download: ', $ta);
 
        exit;
    }

 

完成了!

 

posted on   清清飞扬  阅读(2010)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示