欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-15 10:13:45
...

前端按钮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();
    }
}