浏览器弹窗式下载excel

////前端JS////
downloadFile(response, fileName, contentType){
	const blob = new Blob([response.body],{type:contentType});
	const url = window.URL.createObjectURL(blob);
	// 以打开新窗口方式进行下载
	window.open(url);    // 每次创建的文件的文件名都是随机的字符串
	// 以动态创建a标签方式进行下载
	const a = document.createElement('a');
	a.href = url;
	a.download = fileName;
	a.click();
	window.URL.revokeObjectURL(url);
}

customDownload(){
	// 业务逻辑的处理
	…………………………
	this.loadingService.show();   
	
	const uri = new Uri(this.uriService.extendUri('api路径'),{});
	const url = uri.toString();
	const headers = new HttpHeaders({'Content-Type': 'application/json'});
	const option = {
		responseType: 'blob' as any,
		headers:headers,
		observe: 'response' as any,
	}
	const body = {
		filters: filters    // 筛选框的参数
	}
	this.httpClient.put(url, body, option).subscribe(response: any) => {
		this.loadingService.hide();
		const contentType = "application/vnd.ms-excel;charset=utf-8";
		let fileName = response.headers.get("Content-Disposition").split(";")[1].split("filename=")[1];
		fileName = decodeURI(fileName);
		if('msSaveOrOpenBlob' in navigator){
			const blob = new Blob([response.body],{type: contentType});
			window.navigator.msSaveBlob(blob,fileName);
		} else {
			this.downloadFile(response, fileName, contentType);
		}
	},
		error => {
			this.loadingService.hide();
			this.msgService.info("下载失败!");
			return EMPTY;
		}
	);
	this.formNotifyService.success("导出成功,请等待文件下载完成!");
}

////后端Java////
public void create(int rowNum, List<…> resList) throws IOException{
	String allColName = {"","",""};
	String allColCode = {"","",""};
	int[] widths = {,,,,,};
	
	XSSFWorkbook workbook = null;
	OutputStream outputStream = null;
	File file = null;
	String fileName = "";
	try{
		//创建工作簿
		workbook = new XSSFWorkbook();
		// 输出主表
		XSSFSheet sheet = workbook.createSheet("sheet名字");
		// 设置样式
		XSSFCellStyle headStyle = headStyle(workbook);  //标题行样式
		XSSFCellStyle textStyle = textStyle(workbook);  //表体样式
		// 输出主表表头
		setTitle(widths, allColName, sheet, headStyle);
		// 输出主表表体
		setMainTable(allColCode, rowNum, sheet, resList, textStyle);
		// 设置输出路径
		// String deskPath = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();
		// String downloadPath = deskPath.substring(0, deskPath.lastIndexOf("\\") + "\\DownLoads");    //C盘下下载文件夹的路径
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssS");
		String nowStr = sdf.format(date);
		fileName = "文件名" + nowStr + ".xlsx";
		file = new File(System.getenv("temp"), fileName);   // System.getenv("temp"):java环境变量里配置的temp属性的路径地址。file:excel的完整路径
		if(file.exists()){
			file.delete();
			file.createNewFile();  // 在磁盘创建文件
		}
		outputStream = new FileOutputStream(file);
		workbook.write(outputStream);
	}catch(IOException e){
		e.printStackTrace();
	} finally{
		if(outputStream != null){
			outputStream.flush();
			outputStream.close();
		}
		if(workbook != null){
			workbook.close();
		}
	}
	download(fileName, file);
}
public void download(String fileName, File file){
	ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	HttpServletResponse response = requestAttributes.getResponse();
	FileInputStream fileInputStream = null;
	OutputStream outputStream = null;
	try{
		response.reset();
		fileName = URLEncoder.encode(fileName, "UTF-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + new String (fileName.getBytes()));
		response.setContentType("application/vnd.ms-excel;charset=utf-8");  // application/octet-stream;charset=utf-8
		ServletOutputStream outps = response.getOutputStream();
		outputStream = new BufferedOutputStream(outps);
		fileInputStream = new FileInputStream(file);
		int length = 0;
		byte[] bytes = new byte[1024];
		while((lenth = fileInputStream.read(bytes))!= -1){
			outputStream.write(bytes, 0, length);
			outputStream.flush();
		}
	}catch(IOException e){
		e.printStackTrace();
	} finally{
		try{	
			if(fileInputStream != null){
				fileInputStream.close();
			}
			if(outputStream != null){
				outputStream.close();
			}
		}catch(IOException e){
			e.printStackTrace();
		} 
	}
}

public void setTitle(int[] width, String[] titles, Sheet sheet, XSSFCellStyle headStyle){
	// 给表头创建一行的空间
	Row row = sheet.createRow(0);
	// 输出表头
	for (int i = 0; i < title.length; i++){
		sheet.setColumnWidth(i, width[i] * 256);  // 设置列宽
		sheet.setDefaultRowHeight((short)(1.5 * 256));   // 设置行高,写在表头设置中,整个sheet均改变行高,放在表体位置,只改变相对应表体的行高
		Cell cell = row.createCell(i);
		cell.setCellStyle(headStyle);
		cell.setCellValue(titles[i]);
	}
}	

// 主表表体内容
public void setMainTable(String[] allColCode, int rowNum, Sheet sheet, List<…> resList, XSSFCellStyle textStyle){
	for(int i = 0; i < rowNum; i++){
		Row row = sheet.createRow(i + 1);  // 给第i条数据创建一行的空间,第一行使表头,数据从第二行开始存放,所以是i+1
		数据类型 record = resListget(i);
		String cellData = "";
		for(int j = 0; j < allColCode.length; j++){
			Cell cell1 = row.createCell(j);   // 给新数据创建一个单元格
			if(record.get(allColCode[j]) == null){
				cellData = " ";
			}else{
				cellData = record.get(allColCode[j]).toString();
			}
			cell1.setCellValue(cellData);
			cell1.setCellStyle(textStyle);
		}		
	}
}


// 表头样式
public XSSFCellStyle headStyle(XSSFWorkbook workbook){
	XSSFCellStyle headersStyle;
	// 当设置了表头字体,行高出现问题(表头字体设置和行高设置只能留其一)
	XSSFFont fontHeader = workbook.createFont();
	// fontHeader.setColor(new XSSFColor(Color.black));
	fontHeader.setFontHeightInPoints((short)12);
	fontHeader.setBold(true);
	fontHeader.setFontName("Calibre");
	headersStyle = workbook.createCellStyle();
	headersStyle.setBorderTop(BorderStyle.THIN);
	headersStyle.setBorderBottom(BorderStyle.THIN);
	headersStyle.setBorderLeft(BorderStyle.THIN);
	headersStyle.setBorderRight(BorderStyle.THIN);
	headersStyle.setFont(fontHeader);
	headersStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
	headersStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
	headersStyle.setAlignment(HorizontalAlignment.CENTER); // 居中设置
	return headersStyle;
}
// 表体样式
public XSSFCellStyle textStyle(XSSFWorkbook workbook){
	XSSFCellStyle textStyle;
	// 设置文本字体
	XSSFFont font = workbook.createFont();
	font.setFontHeightInPoints((short)12);
	font.setFontName("宋体");
	font.setBold(false);
	// 设置文本样式
	textStyle = workbook.createCellStyle();
	textStyle.setBorderTop(BorderStyle.THIN);
	textStyle.setBorderBottom(BorderStyle.THIN);
	textStyle.setBorderLeft(BorderStyle.THIN);
	textStyle.setBorderRight(BorderStyle.THIN);
	textStyle.setFont(font);
	textStyle.setWrapText(true);   // 文本自动换行
	textStyle.setAlignment(HorizontalAlignment.LEFT);
	return textStyle;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值