ssm应用中Excel的导出

1 SSM框架搭好,推荐:https://www.cnblogs.com/zyw-205520/p/4771253.html

2 jsp页面中弄个a标签,href为请求地址
    <a href="downloadLog">导出操作记录</a>

3 controller中使用一个RequestMapping进行处理
    @RequestMapping(value="/downloadLog")
    返回视图为对象视图,bean的名字
    返回到自定义视图解析器中,map数据传到Map参数参数中

  //查询数据库,把要下载的数据全部查询出来,然后进行处理
        List<Tb_borrow_wish_op_detail> list=opService.selectAll();
        ModelAndView view=new ModelAndView();
        view.setViewName("productOpLogView");  //ProductOpLogView 类在spring中定义的bean的id
        view.addObject("list", list);     //要填充到表格中的数据,作为参数传递到下面的arg0
        return view;

4 返回值为BeanNameViewResolver,添加导出excel的插件org.apache.poi
    <!-- 导出excel的插件 -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.9</version>
    </dependency>

5 spring mvc中添加对象视图解析器
    <!-- 对象视图解析器 -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="1"></property>
    </bean>

6 新建一个类ProductOpLogView 继承 org.springframework.web.servlet.view.document.AbstractXlsView
  重写protected void buildExcelDocument(Map<String, Object> arg0, Workbook arg1, HttpServletRequest arg2,
            HttpServletResponse arg3) throws Exception
    在其中完成表格的生成,以及表格的输出(浏览器中弹出下载框)
    //弹出下载框的主要代码:
   response.setHeader("content-disposition", "attachment;filename=file.xls"); //弹出下载框

   response.setContentType("application/ms-excel; charset=UTF-8"); //导出数据格式为表格

   新建的类ProductOpLogView ,需要注入到spring容器中
  arg1作为工作簿,可以创建sheet(一个excel文件可以有多个sheet,每个sheet就是一个表格,每个sheet有多个row,每个row有多个cell)

    //创建表格的部分代码

  Sheet sheet=workbook.createSheet();
        int rows=0;  //首行
        Row row=sheet.createRow(rows++);
        row.createCell(0).setCellValue("编号");
        row.createCell(1).setCellValue("产品名称");
        row.createCell(2).setCellValue("产品类型");
        row.createCell(3).setCellValue("年利率");

  //表格中内容仿照着写

自己对知识的一个梳理,希望对大家有帮助

 

posted @ 2018-11-05 19:22  gulchan  阅读(1314)  评论(0编辑  收藏  举报