java实现excel导出

来源:互联网 发布:大额借贷软件 编辑:程序博客网 时间:2024/06/06 20:54

1.将poi jar包引入项目


2.后台代码

在导出的action中定义好导出标题

/** 导出标题 */
    private static final String[] EXPORT_SEVEN_QUESTION = {"姓名", "手机号", "意见"};


@RequestMapping("/training/exportSevenQuestion")
    public void exportSevenQuestion(final QuestionNaireQueryBean queryBean, final HttpServletRequest request,
            final HttpServletResponse response) {
        try {
            queryBean.setPageSize(-1);
            List<QuestionNaire> list = questionNaireDao.questionNaireDataAnalysisTablePage(queryBean);//根据前台传的参数查询出符合的结果集
            List<List<String>> exportList = new ArrayList<>();
            for (QuestionNaire questionNaire : list) {
                List<String> strList = new ArrayList<>();
                strList.add(questionNaire.getUname());
                strList.add(questionNaire.getUphone());
                strList.add(questionNaire.getQuestion_7());
                exportList.add(strList);
            }
            ExcelFileGenerator excelFile = new ExcelFileGenerator(Arrays.asList(EXPORT_SEVEN_QUESTION), exportList);
            setExcelContentType(response);
            excelFile.exportExcel(response.getOutputStream());
            logger.info("导出问卷调查第七题.导出记录数:" + exportList.size(), JSON.toJSONString(queryBean));
        } catch (Exception e) {
            logger.error("导出日志excel错误", e);
        }
    }

//设置文件格式

protected void setExcelContentType(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=\"data.xls\"");
    }

// 将信息写入输出流的方法。
    public void exportExcel(OutputStream os) throws Exception {
        workBook = createWorkbook();
        try {
            workBook.write(os);
        } finally {
            if (os != null) {
                os.close();
            }
        }

    }


导出效果:


0 0
原创粉丝点击