ajax 下载文件(excel导出)

<button class="btn btn-danger m-r-5" id="exportClick"
style="width: 100px;margin-left:10px;">日报表</button>

ajax 请求后端

    $("#exportClick").click(function () {
        var url = '${basePath}/rest/cart/export'
        console.log('url ' + url);
        var a = document.createElement('a')
        a.href = encodeURI(url)
        a.setAttribute('target', '_blank')
        a.download = "日报表.xlsx";
        a.click();
    });

后端代码

    @RequestMapping(value = "/export")
    public void export(HttpServletResponse response, HttpServletRequest request) {
        service.export(response, request);
    }

导出实现逻辑

java 复制代码
    @Override
    public void export(HttpServletResponse response, HttpServletRequest request) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            XSSFWorkbook workbook = new XSSFWorkbook();
            //创建工作表sheeet
            XSSFSheet sheet = workbook.createSheet("数据处理结果");
            //创建第一行
            sheet.setColumnWidth(0, 3766);
            sheet.setColumnWidth(1, 3766);
            sheet.setColumnWidth(2, 5766);
            XSSFRow row = sheet.createRow(0);
            String[] title = {"日期", "营业额", "消费量"};
            XSSFCell cell_title;
            for (int i = 0; i < title.length; i++) {
                cell_title = row.createCell(i);
                cell_title.setCellValue(title[i]);
            }
            for (int i = 0; i < dayList.size(); i++) {
                XSSFRow createRow = sheet.createRow(i + 1);
                XSSFCell name = createRow.createCell(0);
                name.setCellValue(dayList.get(i));
                XSSFCell username = createRow.createCell(1);
                username.setCellValue(String.valueOf(amountList.get(i)));
                XSSFCell gender = createRow.createCell(2);
                gender.setCellValue(String.valueOf(countList.get(i)));
            }
            response.setHeader("content-disposition", "attachment;filename=day.xlsx");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOCloseUtils.close(inputStream);
            IOCloseUtils.close(outputStream);
        }
    }
相关推荐
PieroPc5 小时前
Python 写的 智慧记 进销存 辅助 程序 导入导出 excel 可打印
开发语言·python·excel
羊小猪~~16 小时前
前端入门之VUE--ajax、vuex、router,最后的前端总结
前端·javascript·css·vue.js·vscode·ajax·html5
不吃鱼的羊1 天前
Excel生成DBC脚本源文件
服务器·网络·excel
chenchihwen1 天前
数据分析时的json to excel 转换的好用小工具
数据分析·json·excel
TroubleMaker1 天前
OkHttp源码学习之retryOnConnectionFailure属性
android·java·okhttp
lxxxxl1 天前
C#调用OpenXml,读取excel行数据,遇到空单元跳过现象处理
excel
m0_748246351 天前
前端通过new Blob下载文档流(下载zip或excel)
前端·excel
不吃鱼不吃鱼1 天前
Excel加载项入门:原理、安装卸载流程与常见问题
excel·wps
深耕AI1 天前
在Excel中绘制ActiveX控件:解决文本编辑框定位问题
java·前端·excel