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);
        }
    }
相关推荐
开心点幸运点11 小时前
Excel——宏教程(1)
excel
boy快快长大20 小时前
将大模型生成数据存入Excel,并用增量的方式存入Excel
java·数据库·excel
Leuanghing20 小时前
使用Python生成F分布表并导出为Excel文件
开发语言·python·excel·f分布
爱编程的小生20 小时前
Easyexcel(4-模板文件)
java·excel
Lucky me.21 小时前
本地maven添加jar包
okhttp·maven·jar
今日之风甚是温和1 天前
【Excel】拆分多个sheet,为单一表格
java·excel·sheet·vb宏
如意机反光镜裸1 天前
Excel如何批量导入图片
excel
技术拾荒者1 天前
Day03_AJAX原理 (黑马笔记)
ajax
闲人编程1 天前
Spark使用过程中的 15 个常见问题、详细解决方案
python·ajax·spark·解决方案·调度·作业
ac-er88881 天前
ThinkPHP中使用ajax接收json数据的方法
前端·ajax·json·php