Java 点击按钮下载Excel

前端js

function downloadGet(url) {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
        if (this.status === 200) {
            let blob = this.response;
            let reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function (e) {
                let a = document.createElement('a');
                a.download = 'topology_report.xls';
                a.href = e.target.result;
                $("body").append(a);
                a.click();
                $(a).remove();
            }
        }
    };
    xhr.send();
}

后台java代码:

    private static final String sheetName = "sheet";
    public static <T> String convert(List<T> list, String rootPath, String filePath, String excelName, HttpServletResponse response) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(sheetName);
        Field[] fs = list.get(0).getClass().getDeclaredFields();
        int len = fs.length;
        List<Field> fieldList = null;
        List<String> titleList = null;
        PoiExcelColumn column;
        for (Field f : fs) {
            column = f.getAnnotation(PoiExcelColumn.class);
            if (column != null) {
                if (fieldList == null) {
                    fieldList = new ArrayList<>(len);
                }
                f.setAccessible(true);
                fieldList.add(f);
                if (titleList == null) {
                    titleList = new ArrayList<>(len);
                }
                titleList.add(column.value());
            }
        }
        if (titleList == null) {
            return null;
        }
        int rowIdx = 0, colSum = titleList.size();
        HSSFRow row = sheet.createRow(rowIdx++);
        HSSFCell cell;
        for (int i = 0; i < colSum; i++) {
            cell = row.createCell(i);
            cell.setCellValue(titleList.get(i));
        }
        Object obj;
        String value;
        FileOutputStream fos = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            for (T t : list) {
                row = sheet.createRow(rowIdx++);
                for (int i = 0; i < colSum; i++) {
                    obj = fieldList.get(i).get(t);
                    value = obj == null ? "" : obj.toString();
                    cell = row.createCell(i);
                    cell.setCellValue(value);
                }
            }
            String downFilePath = rootPath + filePath;
            File f = new File(downFilePath);
            if (f.exists()) {
                f.delete();
            }
            fos = new FileOutputStream(downFilePath);
            sheet.setGridsPrinted(true);
            HSSFFooter footer = sheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            workbook.write(fos);
            //  按流下载数据
            // 下载到IE客户端
            // 解决中文乱码问题,设置后产生一个新的String对象此对象以改变了编码
            String newPath = URLEncoder.encode(excelName, "utf-8");
            // 在页面上弹出一个下在窗口指定下载文件保存的文件类型
            response.setContentType("application/vnd.ms-excel");
            // 设置报头信息,弹出窗口中显示的文件名
            response.setHeader("Content-Disposition", "attachment; filename=" + newPath);
            is = new FileInputStream(downFilePath);
            os = response.getOutputStream();
            // 具体的输入输出流操作
            byte[] b = new byte[1024 * 8];
            int i = 0;
            while ((i = is.read(b)) != -1) {
                os.write(b, 0, i);
                i = 0;
            }
            os.flush();
            return filePath + excelName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值