在ssh項目中導出excel

一、在這裏主要貼出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;
    }

六、頁面內容省略

七、說明:代碼不能直接運行,只是貼出主要部分。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章