Vue SpringBoot 进行Excel下载

后台代码:

/**
	 * 下载导入实例数据模板
	 */
	@RequestMapping(value = "/template")
    public void userListTemplate(HttpServletRequest request, HttpServletResponse response) {
		
		try {
			
			//创建文件
			XSSFWorkbook wb = new XSSFWorkbook();			
			XSSFSheet sheet = wb.createSheet("mobileList");
			
			XSSFCellStyle style = wb.createCellStyle();
			style.setAlignment(HorizontalAlignment.LEFT);//文字居左
			style.setVerticalAlignment(VerticalAlignment.BOTTOM);// 设置单元格垂直方向对齐方式
			style.setBorderBottom(BorderStyle.THIN);//下边框 
			style.setBorderLeft(BorderStyle.THIN);//左边框 
			style.setBorderRight(BorderStyle.THIN);//右边框 
			style.setBorderTop(BorderStyle.THIN); //上边框
			
			for (int i = 0; i < 3; i++) { //3行
				XSSFRow row =	sheet.createRow(i); 
				for (int j = 0; j < 2; j++) {//2列
					row.createCell(j).setCellStyle(style);
				}
			}
			//填充内容
			XSSFRow row = sheet.getRow(0);
			row.getCell(0).setCellValue("地区编号");
			row.getCell(1).setCellValue("电话");
			XSSFRow row1 = sheet.getRow(1);
			row1.getCell(0).setCellValue("852");
			row1.getCell(1).setCellValue("88888888");
			XSSFRow row2 = sheet.getRow(2);
			row2.getCell(0).setCellValue("86");
			row2.getCell(1).setCellValue("13500202020");
			
			//设置Header并且输出文件
			String fielName = "短讯接收人列表模板.xlsx";
			response.setHeader("Content-type","application/vnd.ms-excel");
	        response.setCharacterEncoding("UTF-8");
            //设置响应头部,以及文件名进行中文防止乱码转码操作
	        response.setHeader("Content-Disposition","attachment;filename="+Encodes.urlEncode(fielName));
	        wb.write(response.getOutputStream());
	        wb.close();
			
		} catch (Exception e) {
			log.error("下载模板错误",e);
		}
		
    }

VUE 前端页面代码:

getUserListTplFun(){
    //使用axios进行请求后台,重点是{responseType: 'blob'} 的设置。
    axios.get("/api1/v1/message/sms/template",{responseType: 'blob'}).then(response=>{

	    if(!response){
		    return
	    }
	    //将response 新建成文件流
	    var blob = new Blob([response], {type: 'application/vnd.ms-excel;charset=utf-8'})
	    //创建下载地址以及a标签,并且模拟a标签的点击事件进行下载文件。
	    var url = window.URL.createObjectURL(blob);
	    var aLink = document.createElement("a");
	    aLink.style.display = "none";
	    aLink.download = '短讯接收人列表模板.xlsx';
	    aLink.href = url;
	    document.body.appendChild(aLink)
	    aLink.click()

    }).catch(error=>{
	    console.log(error);
    })
}

 

你可能感兴趣的:(随笔)