springboot下载excel文件:
前端js:
function fnExport() {
window.location.href = xxx + "/api/base/exportByTemplate.do?tempalteName=lddzhtaddbatch";
}
后台:
@Controller
@RequestMapping("pc/api/base")
public class BaseApiController{
private Logger logger = LoggerFactory.getLogger(BaseApiController.class);
@RequestMapping("/exportByTemplate.do")
public void exportByTemplate(HttpServletResponse response) {
TerminalDto dto = getDto();
String tempalteName = dto.getAsString("tempalteName");
String filepath = "excel/" + tempalteName + ".xls";
String fileName = tempalteName + ".xls";
logger.info("开始下载模板");
FileUtils.download(response, filepath, fileName);
logger.info("下载模板成功");
}
}
工具类:
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
public class FileUtils {
public static void download(HttpServletResponse response, String filePath, String fileName){
try {
//通用的mime类型
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
writeBytes(is, response.getOutputStream());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void writeBytes(InputStream is, OutputStream os) {
try {
byte[] buf = new byte[1024];
int len = 0;
while((len = is.read(buf))!=-1)
{
os.write(buf,0,len);
}
}catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
放入对应的模板: