java导出服务器已经配置好的excel模板
采用springboot的项目架构。
目录结构
1. 前台代码(设置一个按钮)
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>导出excel模板</title> <script th:src="@{|/js/jquery-2.1.4.min.js|}"></script> <script> $(function () { $("#exportExcelModel").bind("click",function () { window.location.href = "/exportExcelModel"; }) }) </script> </head> <body> <button id="exportExcelModel">导出excel模板</button> </body> </html>
2. 后台代码
package com.bjpowernode.excel.exportExcelModel.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * ClassName:ExportExcelModelController * Package:com.bjpowernode.excel.exportExcelModel.controller * Description: * * @Date:2019/2/23 15:21 * @Author: 郑军 */ @Controller public class ExportExcelModelController { @RequestMapping("/toExportExcelModel") public String toExportExcelModel() { return "exportExcelModel"; } @RequestMapping("/exportExcelModel") public void exportExcelModel(HttpServletRequest request, HttpServletResponse response) { // 模板名称 String fileName = "失信.xlsx"; String excelName = "失信"; InputStream inputStream = null; OutputStream outputStream = null; try { /** * 设置excel文件导出的时候,浏览器响应头 */ response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setHeader("Content-disposition", "attachment;fileName=" + new String(excelName.getBytes("utf-8"), "iso-8859-1") + ".xlsx"); // 读取服务器中配置好的excel模板 inputStream = ExportExcelModelController.class.getClassLoader(). getResourceAsStream(fileName); /** * 读取excel中的数据,然后通过outputStream输出流输出 */ outputStream = response.getOutputStream(); byte[] bytes = new byte[1024]; int length = inputStream.read(bytes); while (length > 0) { outputStream.write(bytes, 0, length); length = inputStream.read(bytes); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }