Java 导出Excel模板文件

1、准备已经填好的导入模板Excel文件

      建议在项目的资源目录下放置,如下图:

    

2、后端代码实现:


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;

@RestController
public class DownloadController {
    
    @ApiOperation("下载导入模板")
	@RequestMapping(value = "/downloadExample", method = RequestMethod.GET)
	public void downloadExample(HttpServletResponse response) {
    	// 获取固定Excel文件作为输入流 (参数为配置的模板路径)
		InputStream in = this.getClass().getResourceAsStream("/statics/importExample.xlsx");
		OutputStream toClient = null;
		byte[] buffer;
		try {
			// 获取导出文件的字节数组
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer1 = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer1)) != -1) {
				outStream.write(buffer1, 0, len);
			}
			in.close();
			buffer = outStream.toByteArray();

			// 导出Excel
			if (null != buffer && buffer.length > 0) {
				// 清空response
				response.reset();
				// 设置response的Header
				response.addHeader("Content-Disposition",
						"attachment;filename=" + new String(("导入模板.xlsx").getBytes("GBK"), "ISO8859_1"));
				response.addHeader("Content-Length", "" + buffer.length);
				toClient = response.getOutputStream();
				response.setContentType("application/octet-stream");
				toClient.write(buffer);
				toClient.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(toClient != null){
				toClient.close();
			}
			if(in != null){
				in.close();
			}
		}
	}
}

3、前端代码配置

     在调用的js中,调用get方法,输出到浏览器即可,如下:

let exportUrl = urlConfig.exportCloudLog + '?' + jsonStr;    // 调用接口
exportUrl = encodeURI(exportUrl);   //解码
window.open(exportUrl, '_self');   

4、接口调用测试

本地启动服务,在浏览器输入配置的地址,调用出现如下即可

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值