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

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

Guess you like

Origin blog.csdn.net/weixin_48860638/article/details/121490259
Recommended