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、接口调用测试
本地启动服务,在浏览器输入配置的地址,调用出现如下即可