Natural

           

          查詢結(jié)果轉(zhuǎn)excel保存

              在web業(yè)務(wù)中,有時候會需要把查詢結(jié)果以excel保存下來。實現(xiàn)的方法有很多,這里以jxl.jar+servlet為例。
              
              假定查詢頁面為cx.jsp
              cx.jsp中添加了兩個按鈕,即將分頁查詢的當前頁結(jié)果轉(zhuǎn)存為excel,或?qū)⑺许撚涗涋D(zhuǎn)存為excel。
              代碼如下:
          <!-- 查詢頁面 cx.jsp -->
          <html>
          <head></head>
          <body>
          <form>
          <table>
          ……
          <tr>
          <td><input type="submit" name="excel1" onclick= "pageThis(0)" value="本頁轉(zhuǎn)Excel保存" class="mybutton"></td>
          <td><input type="submit" name="excel2" onclick= "pageThis(1)" value="所有頁轉(zhuǎn)Excel保存" class="mybutton"></td>
          </tr>
          <table>
          </form>

          <script language="JavaScript">
          //轉(zhuǎn)存為excel
          function pageThis(key)
          {
              form1.action
          ="cx_impexcel.jsp?key="+key;
              form1.submit();
          }
          </script>
          </body>
          </html>

              點擊按鈕,調(diào)用excel導出頁面 cx_impexcel.jsp
              cx_impexcel.jsp中的action.getMethodA(),action.getMethodB()方法即查詢當前頁和所有頁記錄的集合。
              調(diào)用ActionImpExcel.writeExcel()方法生成excel數(shù)據(jù)文件到服務(wù)器端的指定配置路徑,并通過servlet讀取該文件轉(zhuǎn)存到客戶端。
              代碼如下:
          <!-- excel導出頁面 cx_impexcel.jsp -->
          <html>
            
          <head>    
            
          </head>
            
          <body>
              
          <%  
                              
          // 配置文件中定義的放置excel的路徑。
                              
          String sFilePath = PropertyManager.getProperty("tempfilepath");
                               
          // 獲取該項目的絕對路徑
                              
          String url=request.getRealPath("/")+"\\"+sFilePath;

                              
          String path = request.getContextPath();
                              
          // 獲取該項目的相對路徑
                              
          String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
                              
                              
          // 查詢結(jié)果集
                      ArrayList listall 
          =new ArrayList();       
                      
          // 生成excel數(shù)據(jù)的結(jié)果
                      
          boolean rtn=false;
                      
                      
          String key = request.getParameter("key");
                          
                      
          // 定義將要導出記錄的字段列名,用自定義的分隔符隔開(這里用的是';')
                      String colName= "columnA;columnB;columnC;columnD;columnE";
                     
          // 定義生成的文件名MakeFileName()
                      
          String fileName=MakeFileName() + ".xls"
                      
                      
          // 返回滿足條件的記錄列表
                      
          if(key.equals("0"))
                      {
                          
          // TODO  調(diào)用自己定義的方法,返回查詢的當前頁記錄
                          listall
          = action.getMethodA();
                      }
                      
          else
                      {
                          
          // TODO  調(diào)用自己定義的方法,返回查詢的所有頁記錄
                          listall
          = action.getMethodB();    
                      }    
                      
          // 生成EXCEL數(shù)據(jù)
                      rtn 
          = ActionImpExcel.writeExcel(url+fileName,listall,colName,";");
                       
          if (rtn) {
                           
          // 自動文件下載
                          response.sendRedirect(basePath
          +"servletdownloadfile?filename="+fileName+"&downloadFlag=1");
                      } 
          else
                          out.print(
          "<div align=center >導出EXCEL失敗</div>");
               
          %>
            
          </body>
          </html>

          用于生成excel的ActionImpExcel類:
          /**生成excel文件*/
          public class ActionImpExcel {
              
          static int rowcount = 0;

              
          static HashMap hmp = new HashMap();

              
          static String arrColName[] = null;

              
              
          static int colcount = 0;

               
          /**
               * 將查詢結(jié)果寫入生成的excel
               * 
          @param filename String 帶路徑的文件名
               * 
          @param list ArrayList 待寫入的查詢結(jié)果
               * 
          @param colName String 導出的列名集合
               * 
          @param sign String 列名的分隔符
               * 
          @return 
               *
          */
              
          public static boolean writeExcel(String fileName, ArrayList list,
                      String colName,String sign) {

                  String key 
          = "";
                  WritableWorkbook wwb 
          = null;
                  
          try {
                      
          // 首先要使用Workbook類的工廠方法創(chuàng)建一個可寫入的工作薄(Workbook)對象
                      wwb = Workbook.createWorkbook(new File(fileName));
                  } 
          catch (IOException e) {
                      e.printStackTrace();
                  }

                  
          if (wwb != null) {
                      
          // 創(chuàng)建一個可寫入的工作表
                      
          // Workbook的createSheet方法有兩個參數(shù),第一個是工作表的名稱,第二個是工作表在工作薄中的位置
                      WritableSheet ws = wwb.createSheet("sheet1"0);
                      arrColName 
          = colName.split(sign);
                      
          for (int k = 0; k < arrColName.length; k++) {
                          Label labelName 
          = new Label(k, 0, arrColName[k]);
                          
          try {
                              ws.addCell(labelName);
                          } 
          catch (RowsExceededException e) {
                              e.printStackTrace();
                          } 
          catch (WriteException e) {
                              e.printStackTrace();
                          }
                      }

                      
          // 下面開始添加單元格
                      for (int i = 0; i < list.size(); i++) {
                          hmp 
          = (HashMap) list.get(i);
                          
          for (int j = 0; j < hmp.size(); j++) {
                              
          // 這里需要注意的是,在Excel中,第一個參數(shù)表示列,第二個表示行
                              key = String.valueOf(j+1);
                              String colvalue 
          = (String) hmp.get(key);
                              Label labelC 
          = new Label(j, i + 1, colvalue);
                              
          try {
                                  
          // 將生成的單元格添加到工作表中

                                  ws.addCell(labelC);
                              } 
          catch (RowsExceededException e) {
                                  e.printStackTrace();
                              } 
          catch (WriteException e) {
                                  e.printStackTrace();
                              }

                          }
                      }

                      
          try {
                          
          // 從內(nèi)存中寫入文件中
                          wwb.write();
                          
          // 關(guān)閉資源,釋放內(nèi)存
                          wwb.close();
                      } 
          catch (IOException e) {
                          e.printStackTrace();
                      } 
          catch (WriteException e) {
                          e.printStackTrace();
                      }

                  }
                  
          return true;
              }
          }

          用于文件下載的servlet類:
          public class ServletDownLoadFile extends HttpServlet {

              
          //Initialize global variables
              public void init() throws ServletException {
              }

              
          //Process the HTTP Get request
              public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                  String sFileName 
          = "";//文件名
                  String sFilePath = "";//文件路徑
                          
                  sFileName 
          = request.getParameter("filename");
                  
          // 配置文件中定義的存放excel的路徑
                  sFilePath = PropertyManager.getProperty("tempfilepath");
                  sFilePath
          =(sFilePath==null)?"":sFilePath;
                  response.reset();
                  
          if("1".equals(request.getParameter("downloadFlag")))
                  {
                      
          //downloadFlag為1時為下載文件
                      response.setContentType("application/x-msdownload");
                      response.setHeader(
          "Content-disposition","faxfile; filename="+new String(sFileName.getBytes("GBK"), "ISO8859_1"));
                  }
                  
          else if("0".equals(request.getParameter("downloadFlag")))
                  {
                      
          //downloadFlag為0時為用指定的程序打開文件
                      response.setContentType("application/x-msdownload");
                   }
          //downloadFlag為其他值時用IE默認的方式打開文件

                  BufferedInputStream bis 
          = null;
                  BufferedOutputStream bos 
          = null;
                  
          try
                  {

                      bis 
          = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath(sFilePath+ sFileName)));
                      bos 
          = new BufferedOutputStream(response.getOutputStream());

                      
          byte[] buff = new byte[2048];
                      
          int bytesRead;

                      
          while(-1 != (bytesRead = bis.read(buff, 0, buff.length)))
                      {
                          bos.write(buff,
          0,bytesRead);
                      }
                  }
                  
          catch(final IOException e)
                  {
                      System.out.println ( 
          "IOException." + e );

                  }
                  
          finally
                  {
                      
          if (bis != null)
                          bis.close();
                      
          if (bos != null)
                          bos.close();
                  }
              }

              
          //Clean up resources
              public void destroy() {
              }
          }


          好了,最后在web.xml中添加servlet的配置信息;并在application.properties配置好存放excel的目錄變量tempfilepath即可。

          posted on 2009-10-28 14:35 此號已被刪 閱讀(590) 評論(0)  編輯  收藏 所屬分類: J2EE

          導航

          統(tǒng)計

          常用鏈接

          留言簿(8)

          隨筆分類(83)

          隨筆檔案(78)

          文章檔案(2)

          相冊

          收藏夾(7)

          最新隨筆

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 石屏县| 平昌县| 库尔勒市| 永康市| 陈巴尔虎旗| 伽师县| 泉州市| 临邑县| 满洲里市| 繁昌县| 香河县| 商洛市| 浦北县| 喀喇沁旗| 芮城县| 潮安县| 汾西县| 安阳县| 崇文区| 夏津县| 尖扎县| 长沙县| 永清县| 平阴县| 广汉市| 会泽县| 屏东市| 家居| 永嘉县| 梁山县| 鹿邑县| 南溪县| 六枝特区| 台北县| 临夏县| 永寿县| 济南市| 安徽省| 栾城县| 邛崃市| 阿荣旗|