Apache POI 第五講之利用POI 實現數據的批量導出

有時候我們在做項目時,有些項目需要生成Microsoft Excel文件格式的報告。有時,甚至希望將Excel文件作爲輸入數據。這是我們需要用到Apache POI 。例如,一個公司開發的應用程序將財務部門需要所有輸出生成自己的Excel。

利用 POI 實現數據的批量導出

1.編寫導出工具類
public class ExcelUtil {

    public static void fillExcelData(ResultSet rs,Workbook wb,String[] headers)throws Exception{
        int rowIndex=0;
        Sheet sheet=wb.createSheet();
        Row row=sheet.createRow(rowIndex++);
        for(int i=0;i<headers.length;i++){
            row.createCell(i).setCellValue(headers[i]);
        }
        while(rs.next()){
            row=sheet.createRow(rowIndex++);
            for(int i=0;i<headers.length;i++){
                row.createCell(i).setCellValue(rs.getObject(i+1).toString());
            }
        }
    }
}
public class ResponseUtil {

    public static void write(HttpServletResponse response,Object o)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        out.print(o.toString());
        out.flush();
        out.close();
    }

    public static void export(HttpServletResponse response,Workbook wb,String fileName)throws Exception{
        response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"iso8859-1"));
        response.setContentType("application/ynd.ms-excel;charset=UTF-8");
        OutputStream out=response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();
    }

}
2.編寫action類導出方法
public String export()throws Exception{
        Connection con=null;
        try {
            con=dbUtil.getCon();
            Workbook wb=new HSSFWorkbook();
            String headers[]={"編號","姓名","電話","Email","QQ"};
            ResultSet rs=userDao.userList(con, null);
            ExcelUtil.fillExcelData(rs, wb, headers);
            ResponseUtil.export(ServletActionContext.getResponse(), wb, "導出excel.xls");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
3.編寫頁面
function exportUser(){
    window.open('user!export') ;
}
5.查看結果

這裏寫圖片描述

這裏寫圖片描述

這裏寫圖片描述

本實例用了easyui 與 struts2 ,無關緊要,簡單的把相關POI代碼粘貼出來,僅供參考。。

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