一、在这里主要贴出struts中的配置及Action的写法,至于持久层和业务层就不再贴出。

二、使用的是poi-3.2.jar实现Excel数据导出

三、struts.xml配置文件中的配置
        <action name="chapterAction_*" class="chapterAction" method="{1}">
            <result name="success" type="stream">
                <param name="contentType">application/vnd.ms-excel</param>
                <param name="inputName">excelStream</param>
                <param name="contentDisposition">attachment;filename="${fileName}.xls"</param>
                <param name="bufferSize">1024</param>
            </result>
            <result name="error">/WEB-INF/page/academic/error.jsp</result>
        </action>

四、导出数据封装的类

    public class ExpChapter {
        //章节名称
        private String chapterName;
        //课程名称
        private String courseName;

        //Excel表头
        private String[] columnNames = new String[] { "章节名称","课程名称" };
        //方法名称数组
        private String[] columnMethods = new String[] { "getChapterName","getCourseName" };

        

        //省略get 和 set 方法

    }

五、Action中具体代码实现

    //id数组

    private String[] chapterIds;

    private InputStream excelStream;
    private String fileName;
    @Resource(name = ChapterService.BEAN_NAME)
    private ChapterService chapterService;

    //省略get 和 set 方法

    

    public String exp() throws Exception{
        if (null != chapterIds) {
            //从数据库查询出需要的数据
            List<Chapter> chapters = chapterService.find(chapterIds);
            //导出数据集合
            List<ExpChapter> ecs = new ArrayList<ExpChapter>();
            for (Chapter chapter : chapters) {
                ExpChapter ec = new ExpChapter();
                ec.setChapterName(chapter.getChapterTitle());
                ec.setCourseName(chapter.getCourse().getCourseName());
                ecs.add(ec);
            }
            //创建Excel
            HSSFWorkbook workbook = getWorkbook(ecs);
            if (workbook != null) {
                try {
                    Calendar c = Calendar.getInstance();
                    int year = c.get(Calendar.YEAR);
                    int month = c.get(Calendar.MONTH) + 1;
                    String month_ = new String("" + month);
                    if (month < 10) {
                        month_ = "0" + month;
                    }
                    int day = c.get(Calendar.DAY_OF_MONTH);
                    String day_ = new String("" + day);
                    if (day < 10) {
                        day_ = "0" + day;
                    }
                    // 第四步:将工作簿写入最上面定义的InputStream流——名称为excelStream,这个名字对应struts.xml中配置的inputName参数
                    this.workbook2InputStream(workbook, year + "-" + month_
                            + "-" + day_ + "");
                    return SUCCESS;
                } catch (IOException e) {
                    e.printStackTrace();
                    request.setAttribute("message", "创建Excel失败");
                    return ERROR;
                }
            } else {
                System.out.println("创建失败");
                return ERROR;
            }
        }
        return ERROR;
    }


    /*
      * 将Workbook写入到InputStream
      */
     private void workbook2InputStream(HSSFWorkbook workbook,String fileName) throws Exception{
            this.fileName = fileName; //设置fileName
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            baos.flush();
            byte[] aa = baos.toByteArray();
            excelStream = new ByteArrayInputStream(aa, 0, aa.length);
            baos.close();
     }


    /*
     * 将list转换为Excel工作表
     */
    private HSSFWorkbook getWorkbook(List<ExpChapter> expChapters)
            throws SecurityException, NoSuchMethodException,
            IllegalArgumentException, IllegalAccessException,
            InvocationTargetException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("sheet1");
        String[] columnNames;
        String[] columnMethods;

        ExpChapter c = expChapters.get(0);
        columnNames = c.getColumnNames();
        columnMethods = c.getColumnMethods();

        HSSFRow row = sheet.createRow(0);
        HSSFCell cell;
        for (int i = 0; i < columnNames.length; i++) {
            cell = row.createCell(i); // 创建第i列
            cell.setCellValue(new HSSFRichTextString(columnNames[i]));
        }
        // 下面是输出各行的数据
        for (int i = 0; i < expChapters.size(); i++) {
            c = expChapters.get(i);
            row = sheet.createRow(i + 1);// 创建第i+1行
            for (int j = 0; j < columnMethods.length; j++) {
                cell = row.createCell(j);// 创建第j列
                Method method;
                method = c.getClass().getMethod(columnMethods[j]); // 这里用到了反射机制,通过方法名来取得对应方法返回的结果对象
                Object obj = method.invoke(c);
                cell.setCellValue(obj.toString());
            }
        }
        return workbook;
    }

六、页面内容省略

七、说明:代码不能直接运行,只是贴出主要部分。

QQ截图20181015134224.png