1、概念
在使用Excel时,此时handler方法的返回值为ExcelView。
它依赖于Apache的POI框架,使用之前需要引入
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency>
ExcelView与pdf极其类似,它必须实现AbstractXlsView, AbstractXlsxView,AbstractExcelView三者之一。
2、使用
第一步,编写ExcelView(名字随意)对象实现AbstractXlsView接口,实现buildExcelDocument方法。
第二步,注册ExcelView,在视图解析器的方法中,调用registry的enableContentNegotiation方法
第三步,handler方法直接返回ExcelView对象,不是字符串。
3、示例
1、编写ExcelView(名字随意)对象实现AbstractXlsView接口,实现buildExcelDocument方法,
public class ExcelView extends AbstractXlsView {
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename="users.xls"");
// 创建Sheet对象
Sheet sheet = workbook.createSheet("userXls");
// 创建行
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("First Name");
header.createCell(1).setCellValue("Last Name");
header.createCell(2).setCellValue("Email");
}
}
2、注册ExcelView,调用registry的enableContentNegotiation方法
registry.enableContentNegotiation(new ExcelView());
3、编写handler方法,返回ExcelView对象
@GetMapping("test/excel")
public ExcelView testExcelView()
{
ModelAndView model = new ModelAndView();
List<String> wordList = Arrays.asList(new String[] {"第一行","第二行","第三行"});
model.addObject("wordList", wordList);
ExcelView excel = new ExcelView();
return excel;
}
与pdf一样,它也可以直接向response对象的输出流写excel的内容,并指定excel类型。