Vue SpringBoot Excelのダウンロード

2577 ワード

バックグラウンドコード:
/**
	 *           
	 */
	@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);
    })
}