Natural

 

查询结果转excel保存

    在web业务中,有时候会需要把查询结果以excel保存下来。实现的方法有很多,这里以jxl.jar+servlet为例。
    
    假定查询页面为cx.jsp
    cx.jsp中添加了两个按钮,即将分页查询的当前页结果转存为excel,或将所有页记录转存为excel。
    代码如下:
<!-- 查询页面 cx.jsp -->
<html>
<head></head>
<body>
<form>
<table>
……
<tr>
<td><input type="submit" name="excel1" onclick= "pageThis(0)" value="本页转Excel保存" class="mybutton"></td>
<td><input type="submit" name="excel2" onclick= "pageThis(1)" value="所有页转Excel保存" class="mybutton"></td>
</tr>
<table>
</form>

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

    点击按钮,调用excel导出页面 cx_impexcel.jsp
    cx_impexcel.jsp中的action.getMethodA(),action.getMethodB()方法即查询当前页和所有页记录的集合。
    调用ActionImpExcel.writeExcel()方法生成excel数据文件到服务器端的指定配置路径,并通过servlet读取该文件转存到客户端。
    代码如下:
<!-- 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+"/";
                    
                    
// 查询结果集
            ArrayList listall 
=new ArrayList();       
            
// 生成excel数据的结果
            
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  调用自己定义的方法,返回查询的当前页记录
                listall
= action.getMethodA();
            }
            
else
            {
                
// TODO  调用自己定义的方法,返回查询的所有页记录
                listall
= action.getMethodB();    
            }    
            
// 生成EXCEL数据
            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;

     
/**
     * 将查询结果写入生成的excel
     * 
@param filename String 带路径的文件名
     * 
@param list ArrayList 待写入的查询结果
     * 
@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类的工厂方法创建一个可写入的工作薄(Workbook)对象
            wwb = Workbook.createWorkbook(new File(fileName));
        } 
catch (IOException e) {
            e.printStackTrace();
        }

        
if (wwb != null) {
            
// 创建一个可写入的工作表
            
// Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
            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中,第一个参数表示列,第二个表示行
                    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 {
                
// 从内存中写入文件中
                wwb.write();
                
// 关闭资源,释放内存
                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 此号已被删 阅读(573) 评论(0)  编辑  收藏 所属分类: J2EE


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(8)

随笔分类(83)

随笔档案(78)

文章档案(2)

相册

收藏夹(7)

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜