1、导入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.20</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2、代码
import java.net.URLDecoder;
import org.apache.commons.io.IOUtils;
@Override
public void downLoadPropertyExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
String fileName = "房源信息导入模板.xlsx";
fileName = URLDecoder.decode(fileName, "UTF-8");
InputStream in = this.getClass().getResourceAsStream("/template/房源信息导入模板.xlsx");
String filenamedisplay = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + filenamedisplay);
response.setContentType("application/x-download;charset=utf-8");
OutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
out.flush();
in.close();
}
3、前端测试
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="downLoad">下载</button>
<a href="http://127.0.0.1:8055/yxroom/directSeeding/downLoadBuyerExcel">点击下载文件</a>
</body>
<script>
document.getElementById('downLoad').onclick = function(){
alert("开始下载");
window.location.href = 'http://127.0.0.1:8055/yxroom/directSeeding/downLoadBuyerExcel';
}
</script>
</html>
|