Spring mvc 自定义视图解析(pdf和excel)

1.首先我们需要导入两个必备的jar包

poi-3.16.jar、itext-2.1.7.jar

2.生成pdf
首先创建一个继承于AbstractPdfView类的class,重写其中的方法
public class MyPdfView extends AbstractPdfView  {

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        List list = (List) model.get("list");
        for (int i = 0; i < list.size(); i++) {
            //将数据加载到视图上
            document.add(new Paragraph((String)(list.get(i))));
        }

    }
在controller中
@RequestMapping("/pdf")
    public ModelAndView mypdf() {
        ModelAndView mav = new ModelAndView();
        //添加自定义视图
        mav.setView(new MyPdfView());
        List list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i+"");
        }
        mav.addObject("list", list);
        return mav;
    }
--------pdf视图就做完了 ,直接访问url即可

3.自定义的excel视图解析,跟自定义pdf视图很像
public class MyExcelView extends AbstractExcelView  {

    @Override
    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        HSSFSheet sheet;//工作簿的名字
        HSSFRow sheetRow;//行
        HSSFCell cell;//单元格

        sheet = workbook.createSheet("spring");
        sheet.setDefaultColumnWidth(12);

        List list =  (List) model.get("list");
        for (int i = 0; i < list.size(); i++) {
            //三个参数,第一个为工作簿,第二个为行,第三个为单元格
            cell = getCell(sheet, 0, i);
            setText(cell, (String) list.get(i));
            cell = getCell(sheet, i+1, 2);
            setText(cell, (String) list.get(i));
        }
    }
controller中
@RequestMapping("/excle")
    public ModelAndView myexcle() {
        ModelAndView mav = new ModelAndView();
        //添加视图
        mav.setView(new MyExcelView());
        List list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i+"");
        }
        mav.addObject("list", list);
        return mav;
    }
    *over*
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值