excel下载前后端代码,防下载中文乱码

43 篇文章 0 订阅

前端按钮chick()事件js模仿a标签点击

function dakai(){
	window.open('localhost:8080/project/excelDown');
}

后端

/**
 * 下载excel
 * @param response
 * @param dr 参数对象
 */
@RequestMapping(value = "/excelDown", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
public void createExcelToDisk(HttpServletResponse response,DetailReportQuery dr) {
    try {
        response.reset(); // 清除buffer缓存
        // 文件名
        String fname = "未命名";
        String houzui = ".xlsx";
        // 要下载的excel对象
        XSSFWorkbook workbook = null;
        switch (dr.getId()){
            case 1:
                fname = "屋明细账"+System.currentTimeMillis()+houzui;
                workbook = detailReportService.excelExportStoried(dr);
                break;
            case 2:
                fname = "物明细账"+System.currentTimeMillis()+houzui;
                workbook = detailReportService.excelExportStructure(dr);
                break;
            case 3:
                fname = "地明细账"+System.currentTimeMillis()+houzui;
                workbook = detailReportService.excelExportGround(dr);
                break;
            case 4:
                break;
            case 5:
                break;
            case 6:
                break;
            case 7:
                break;
        }

        // 设置前端响应
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes("gb2312"), "ISO8859-1")); // 防止文件名乱码
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        OutputStream output = response.getOutputStream();
        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
        bufferedOutPut.flush();
        workbook.write(bufferedOutPut);
        bufferedOutPut.close();
    }catch (Exception e){
        e.getMessage();
    }
}

防止乱码2

response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("自动统计导出", "UTF-8")
        .replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" +
        fileName + ".xlsx");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值