博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在ssh项目中导出excel
阅读量:7252 次
发布时间:2019-06-29

本文共 3629 字,大约阅读时间需要 12 分钟。

一、在这里主要贴出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;
    }

六、页面内容省略

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

本文转自  素颜猪  51CTO博客,原文链接:http://blog.51cto.com/suyanzhu/1562268

转载地址:http://okebm.baihongyu.com/

你可能感兴趣的文章
Spring4.1-Application Event
查看>>
Python内置模块(一)
查看>>
利用最新新浪微博API做到桌面程序
查看>>
TRUNC函数的用法
查看>>
gre
查看>>
灵巧还是笨重?利用Textarea从浏览器复制字符到剪贴板
查看>>
CentOS 7.4利用Iptables开启远程访问
查看>>
linux下日志监控分析工具webalizer的安装及使用
查看>>
HTTPS 原理详解
查看>>
[转载] 七龙珠第一部——第073话 必杀恶魔光线
查看>>
Get和Post请求区别
查看>>
开源史上最成功的8个开源产品
查看>>
PHP操作MySQL
查看>>
单臂路由与三层交换机动态配置
查看>>
MyBatis学习总结(六)——调用存储过程
查看>>
Docker命令详解
查看>>
servlet jsp 各种路径获取。。
查看>>
应用系统架构设计
查看>>
【POJ】第二章 简单计算题之课后题
查看>>
MFC建立应用程序启示录(创世纪新篇)
查看>>