POI 微信小程序的wx.downloadFile API下载文件

本文介绍了一种在Java环境中生成Excel报表的方法,并提供了文件下载的实现细节。通过使用UUID生成唯一文件名,确保了文件的唯一性。文章还涵盖了如何设置HTTP响应头以允许用户下载文件,以及如何在下载完成后清理临时文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

excel报表生成和下载

生成文件并返回下载路径路径

生成文件接口(业务数据没写进去 下方是文件处理代码)

String uuid = UUID.randomUUID().toString().replace("-", "");
	String fileName = uuid + ".xls";
	String root = FileUtill.getResourceBasePath();
	try {
		String path = root + File.separator + "manhours" + File.separator + fileName;
		File file = new File(path);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		FileOutputStream fileOut = new FileOutputStream(path);
		workBook.write(fileOut);
		fileOut.close();
		String pPath = request.getContextPath() + "/manhours/file/" + uuid;
		return result = JtsResultUtil.success(pPath);
	} catch (Exception e) {
		result = JtsResultUtil.success(e.getMessage());
	} finally {
		workBook.close();
}
下载文件接口

请求上一个接口返回的文件下载路径
(注意文件被下载后会被删除,如果不需要请自行删除finally中判断部分的代码)

@RequestMapping(value = "/file/{fileName}")
public void file(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileName") String fileName) throws IOException, Exception {
	InputStream pInputStream = null;
	OutputStream os = response.getOutputStream();
	// 设置相关格式
	response.setContentType("application/force-download");
	// 设置下载后的文件名以及header
	String fileNameAlias = "月工时表.xls";
	fileNameAlias = URLEncoder.encode(fileNameAlias, "utf-8");
	response.setContentType("application/vnd.ms-excel");
	response.addHeader("Content-disposition", "attachment;fileName=" + fileNameAlias);
	String rootPath = FileUtill.getResourceBasePath();
	String filePath = rootPath + File.separator + "manhours" + File.separator + fileName + ".xls";
	File file = new File(filePath);
	try {
		pInputStream = new FileInputStream(file);
		int bufferSize = 1024;
		byte[] buffer = new byte[bufferSize];
		int len = 0;
		while ((len = pInputStream.read(buffer, 0, bufferSize)) != -1) {
			os.write(buffer, 0, len);
		}
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (pInputStream != null) {
			pInputStream.close();
			if (file != null && file.exists()) {
				file.delete();
			}
		}
		os.flush();
		os.close();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值