对于Excel而言,Spring MVC所推荐的是使用AbstractXlsView,它实现了视图接口,从其命名也可以知道它只是一个抽象类,不能生成实例对象。它自己定义了一个抽象方法——buildExcelDocument要去实现。其他的方法Spring的AbstractXlsView已经实现了,所以对于我们而言完成这个方法便可以使用Excel的视图功能了
  buildExcelDocument方法的主要任务是创建一个Workbook,它要用到POI的API,这需要我们自行下载并导入项目中。这里的参数在代码中也给出了,在Spring MVC中已经对导出Excel进行了很多的封装,所以很多细节我们并不需要关心。

<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>

  假设需要一个导出所有角色信息的功能,但是将来也许还有其他的导出功能。为了方便,先定义一个接口,这个接口主要是让开发者自定义生成Excel的规则,如代码清单15-46所示。
  代码清单15-46:自定义导出接口定义

package com.ssm.chapter15.view;

import org.apache.poi.ss.usermodel.Workbook;

import java.util.Map;

public interface ExcelExportService {

    /***
* 生成exel文件规则
* @param model 数据模型
* @param workbook excel workbook
*/
public void makeWorkBook(Map<String, Object> model, Workbook workbook); }

  有了这个接口还需要完成一个可实例化的Excel视图类——ExcelView,对于导出而言还需要一个下载文件名称,所以还会定义一个文件名(fileName)属性,由于该视图不是一个逻辑视图,所以无须视图解析器也可以运行它,其定义如代码清单15-47所示。
  代码清单15-47:定义Excel视图

package com.ssm.chapter15.view;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.document.AbstractXlsView; public class ExcelView extends AbstractXlsView { //文件名
private String fileName = null; //导出视图自定义接口
private ExcelExportService excelExpService = null; //构造方法1
public ExcelView(ExcelExportService excelExpService) {
this.excelExpService = excelExpService;
} //构造方法2
public ExcelView(String viewName, ExcelExportService excelExpService) {
this.setBeanName(viewName);
} public String getFileName() {
return fileName;
} public void setFileName(String fileName) {
this.fileName = fileName;
} public ExcelExportService getExcelExpService() {
return excelExpService;
} public void setExcelExpService(ExcelExportService excelExpService) {
this.excelExpService = excelExpService;
} @Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { //没有自定义接口
if (excelExpService == null) {
throw new RuntimeException("导出服务接口不能为null!!");
}
// 文件名不为空,为空则使用请求路径中的字符串作为文件名
if (!StringUtils.isEmpty(fileName)) { //进行字符转换
String reqCharset = request.getCharacterEncoding();
reqCharset = reqCharset == null ? "UTF-8" : reqCharset;
fileName = new String(fileName.getBytes(reqCharset), "ISO8859-1");
// 设置下面文件名
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
}
// 回调接口方法,使用自定义生成Excel文档
excelExpService.makeWorkBook(model, workbook);
}
}

  上面的代码实现了生成Excel的buildExcelDocument方法,这样就完成了一个视图类。回调了自定义的接口方法可以根据需要进行自定义生成Excel的规则,接着我们需要在角色控制器中加入新的方法,来满足导出所有角色的要求,如代码清单15-48所示。

  代码清单15-48:使用ExcelView导出Excel

package com.ssm.chapter15.controller;

import com.ssm.chapter15.pojo.PageParams;
import com.ssm.chapter15.pojo.Role;
import com.ssm.chapter15.pojo.RoleParams;
import com.ssm.chapter15.view.ExcelExportService;
import com.ssm.chapter15.view.ExcelView;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; import java.util.ArrayList;
import java.util.List;
import java.util.Map; @Controller
@RequestMapping("/excel")
public class ExcelController { @RequestMapping(value = "/export", method = RequestMethod.GET)
public ModelAndView export() {
//模型和视图
ModelAndView mv = new ModelAndView();
// Excel视图,并设置自定义导出接口
ExcelView ev = new ExcelView(exportService());
//文件名
ev.setFileName("所有角色.xlsx");
// // 设置SQL后台参数
// RoleParams roleParams = new RoleParams();
// // 限制1万条
// PageParams page = new PageParams();
// page.setStart(0);
// page.setLimit(10000);
// roleParams.setPageParams(page);
// 查询
// List<Role> roleList = roleService.findRoles(roleParams);
List<Role> roleList = new ArrayList<>();
roleList.add(new Role(1l, "射手", "远程物理输出"));
roleList.add(new Role(2l, "法师", "魔法输出"));
// 加入数据模型
mv.addObject("roleList", roleList);
mv.setView(ev);
return mv;
} @SuppressWarnings({"unchecked"})
private ExcelExportService exportService() {
// 使用Lambda表达式自定义导出excel规则
return (Map<String, Object> model, Workbook workbook) -> {
// 获取用户列表
List<Role> roleList = (List<Role>) model.get("roleList");
// 生成Sheet
Sheet sheet = workbook.createSheet("所有角色");
// 加载标题
Row title = sheet.createRow(0);
title.createCell(0).setCellValue("编号");
title.createCell(1).setCellValue("名称");
title.createCell(2).setCellValue("备注");
//便利角色列表,生成一行行的数据
for (int i = 0; i < roleList.size(); i++) {
Role role = roleList.get(i);
int rowIdx = i + 1;
Row row = sheet.createRow(rowIdx);
row.createCell(0).setCellValue(role.getId());
row.createCell(1).setCellValue(role.getRoleName());
row.createCell(2).setCellValue(role.getNote());
}
};
} }

  这样就能够导出Excel了,ExcelExportService接口的实现使用了Lambda表达式,因此Java版本是8及以上,Java 8以下的版本可以使用匿名类的方法去实现它。这里使用了ExcelExportService接口,就可以在自己的控制器上自定义导出规则,这样就可以根据需要开发了。

Spring MVC 实例:Excel视图的使用的更多相关文章

  1. spring mvc:内部资源视图解析器2(注解实现)@Controller/@RequestMapping

    spring mvc:内部资源视图解析器2(注解实现)  @Controller/@RequestMapping 访问地址: http://localhost:8080/guga2/hello/goo ...

  2. spring mvc:内部资源视图解析器(注解实现)@Controller/@RequestMapping

    spring mvc:内部资源视图解析器(注解实现)@Controller/@RequestMapping 项目访问地址: http://localhost:8080/guga2/hello/prin ...

  3. Spring MVC 数据模型与视图

      从控制器获取数据后,会装载数据到数据模型和视图中,然后将视图名称转发到视图解析器中,通过解析器解析后得到最终视图,最后将数据模型渲染到视图中,展示最终的结果给用户. 用ModelAndView来定 ...

  4. spring mvc: 资源绑定视图解析器(不推荐)

    spring mvc: 资源绑定视图解析器(不推荐) 不适合单控制器多方法访问,有知道的兄弟能否告知. 访问地址: http://localhost:8080/guga2/hello/index 项目 ...

  5. Spring MVC资源绑定视图解析器

    ResourceBundleViewResolver使用属性文件中定义的视图bean来解析视图名称. 以下示例显示如何使用Spring Web MVC框架中的ResourceBundleViewRes ...

  6. spring mvc 导出 excel

    // js 触发导出 excel 方法 导出当前页的数据 含有条件查询的结果 // js 框架使用的 是 easyui function doExport(){ var optins = $(&quo ...

  7. [Spring MVC] - JSP + Freemarker视图解释器整合

    Spring MVC中如果只使用JSP做视图,可以使用下面这段即可解决: <!-- 视图解释类 --> <bean class="org.springframework.w ...

  8. spring mvc的excel报表文件下载时流的冲突解决

    在jsp或者在servlet中有时要用到 response.getOutputStream(),但是此时会在后台报这个错误java.lang.IllegalStateException: getOut ...

  9. spring mvc velocity多视图

    1.ViewResolverUrlBasedViewResolver 这个东西是根据url 进行路由的.网上搜了 1.order 排序,同名出现各种问题 2.XmlViewResolver,BeanN ...

随机推荐

  1. N皇后问题代码

    /*.h*/ #ifndef _NQUEEN_H #define _NQUEEN_H #include<iostream> #include<vector> #include& ...

  2. linux 中截取字符串

    shell中截取字符串的方法有很多中,${expression}一共有9种使用方法.${parameter:-word}${parameter:=word}${parameter:?word}${pa ...

  3. mysql 连接过多解决方案

    方案1.登录mysql控制台:mysql -h192.168.20.199 -uroot -proot flush hosts 方案2.直接重启服务:service mysqld restart(暴力 ...

  4. Spark运行架构及作业提交流程

    1.yarn-cluster模式: (1)client客户端提交spark Application应用程序到yarn集群. (2)ResourceManager收到了请求后,在集群中选择一个NodeM ...

  5. Java入门程序HelloWord

    Java程序开发三步骤:编写,编译,运行 编译器(编译):javac.exe 解释器(运行):java.exe 编译:把我们能看得懂的java代码(xxx.java)翻译成jvm可以运行的java字节 ...

  6. nginx 超时配置、根据域名、端口、链接 配置不同跳转

    Location正则表达式location的作用  location指令的作用是根据用户请求的URI来执行不同的应用,也就是根据用户请求的网站URL进行匹配,匹配成功即进行相关的操作. locatio ...

  7. [Flutter] Router Navigation

    Basic navigation by using 'Navigator.push' & 'Navigator.pop()', for example, we have two screen, ...

  8. C# CRC16校验码 1.0

      /// <summary> /// 计算CRC16校验码 1.0 /// </summary> /// <param name="bytes"&g ...

  9. 删除tppabs,href="javascript:if(confirm)...",、/*tpa=http://...

    扒网站,据说是web从业人员的必备技能; 废话不多,下面应该是你想要的; 1:   tppabs="h[^"]*" 2: href="javascript\:i ...

  10. Pytest权威教程21-API参考-07-配置选项(Configuration Options)

    目录 配置选项(Configuration Options) addopts cache_dir confcutdir console_output_style doctest_encoding do ...