jsf从页面的datatable输出到excel

来源:互联网 发布:linux重命名文件命令 编辑:程序博客网 时间:2024/04/27 20:38

 

 前台jsf页面的commandlink:

                        <h:commandLink action="#{exportExcel.exportExcelDoit}">
                            
<f:verbatim>
                                
<span class="linkAddImg"></span>
                            
</f:verbatim>
                            
<t:updateActionListener property="#{exportExcel.tmp}" value="glpProjectList.glpProjects" />
                            
<t:updateActionListener property="#{exportExcel.classname}" value="GlpProject" />
                            
<t:updateActionListener property="#{exportExcel.title}" value="状态,合同编号,项目编号,项目名称,创建人,创建日期,新药种类,项目负责人" />
                            
<t:updateActionListener property="#{exportExcel.function}" value="projectState,compactIdOfGlpCompact.compactId,projectId,projectName,createUserIdOfSysUser.userName,projectCreatdt,drugType,proMasterName" />
                            
<h:outputText styleClass="buttonText" value="导出Excel" />
                        
</h:commandLink>

 

后台的处理managebean:

    public void exportExcelDoit(){        
        List tmplist 
= (List)this.getValueBinding("#{"+tmp+"}");            
        String function [] 
= this.function.split(",");
        String title [] 
= this.title.split(",");        
        String excel [][]  
= new String[tmplist.size()][function.length];
        
        
for (int k = 0; k < function.length; k++{//组合字符串,前边加上get然后第一个字母大写
            function[k] = "get"+function[k].substring(0,1).toUpperCase()+function[k].substring(1);            
        }

        Class objClass 
= null;
        Object objIns 
= null;
        Method getIdMethod 
= null;        
        
try{            
            objClass 
= Class.forName("cn.com.brilliance.begen.model." + this.classname);
            objIns 
= objClass.newInstance();                                                 
            
for(int i=0;i<tmplist.size();i++){                
                objIns 
= tmplist.get(i);                
                
for (int j = 0; j < function.length; j++{
                    String tmpstr 
= "";
                    
if(function[j].indexOf(".")<0){
                        getIdMethod 
= objIns.getClass().getMethod(function[j], new Class[] {});
                        tmpstr 
= getIdMethod.invoke(objIns, new Object[]{}).toString();    
                    }
else if(function[j].indexOf(".")>0){   //如果是找子属性
                        String bef = function[j].substring(0,function[j].indexOf("."));
                        String aft 
= function[j].substring(function[j].indexOf(".")+1);
                        aft 
= "get"+aft.substring(0,1).toUpperCase()+aft.substring(1);            
                        getIdMethod 
= objIns.getClass().getMethod(bef, new Class[] {});
                        Object tmpObj 
= getIdMethod.invoke(objIns, new Object[]{});    
                        
if(tmpObj!=null){
                            getIdMethod 
= tmpObj.getClass().getMethod(aft, new Class[] {});
                            tmpstr 
= getIdMethod.invoke(tmpObj, new Object[]{}).toString();    
                        }
                        
                    }

                    excel [i][j] 
=tmpstr;
                }
    
            }
        
            toExcel(title,excel);
            
this.getResponse().sendRedirect("../ExcleView");
        }
catch(Exception e){e.printStackTrace();}

    }

    
public void toExcel(String title[],String content[][]){
        jxl.write.WritableCellFormat tit 
= new jxl.write.WritableCellFormat();
        jxl.write.WritableCellFormat con 
= new jxl.write.WritableCellFormat();
        
        
int i = 0;
        
int j = 0;
        
try {
            
//设置title样式
            tit.setBorder(jxl.format.Border.ALL,
                    jxl.format.BorderLineStyle.THIN);
            tit.setAlignment(jxl.format.Alignment.CENTRE);
            tit.setBackground(jxl.format.Colour.PALE_BLUE);
            
//----------------------------------------
            con.setBorder(jxl.format.Border.ALL,
                    jxl.format.BorderLineStyle.THIN);
            con.setBorder(jxl.format.Border.ALL,
                    jxl.format.BorderLineStyle.THIN);
            
//-----------------------------------------
            String realPath = this.getRequest().getRealPath("/");
            File file 
=  new File(realPath+"image/viewExcelForExport.xls");
            Workbook rw 
= Workbook.getWorkbook(new File(realPath+"images/excel.xls"));
            WritableWorkbook wwb 
= Workbook.createWorkbook(file,rw);
            WritableSheet ws 
= wwb.getSheet("Sheet1");
            Label label 
= null;
            
int maxlength[] = new int[title.length];
            
for(i=0;i<title.length;i++){
                maxlength[i] 
= countString(title[i]);
                label 
= new Label(i, 0,title[i], tit);
                ws.addCell(label);
            }

            
for(i=0;i<content.length;i++){
                
                
for(j=0;j<content[i].length;j++){
                    maxlength[j] 
= countString(content[i][j])>maxlength[j]?countString(content[i][j]):maxlength[j];
                    label 
= new Label(j, i+1,content[i][j], con);
                    ws.addCell(label);
                }

            }

            
for(i=0;i<title.length;i++)
                ws.setColumnView(i, maxlength[i]);
            }

            wwb.write();
            wwb.close();
            rw.close();
        }
 catch (Exception e) {
//             TODO: handle exception
            e.printStackTrace();    
        }
        
    }

    
public int countString(String str){
          
char [] allChars = str.toCharArray();
          
int num = 0;
          
for ( int i=0;i<allChars.length;i++){
           
if (Pattern.matches("[一-龥]",String.valueOf(allChars[i]) )){
              num 
+= 2;
           }
else{
              num 
+= 1;
           }

          }

        
return num;
    }

实现弹出写好的excel的类

package cn.com.brilliance.begen.ext.webapp.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ExcleView extends HttpServlet{
    
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
// TODO Auto-generated method stub
        doPost(request, response);
    }


    
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(
"application/vnd.ms-excel"); 
        response.setHeader(
"Content-disposition","attachment;filename=excel.xls");   
        
try {
            String realPath 
= request.getRealPath("/")+"image/";
            File file 
= new File(realPath+"viewExcelForExport.xls");
            
long fLength = file.length();
            response.setContentLength((
int) fLength);
            FileInputStream fileInputStream 
= new FileInputStream(file);
            
int b;
            
byte[] buffer = new byte[(int) fLength];
            
while ((b = fileInputStream.read(buffer, 0, (int) fLength)) != -1{
                response.getOutputStream().write(buffer, 
0, b);
            }

            fileInputStream.close();
        }
 catch (Exception e) {
            e.printStackTrace();
        }
 finally {
        }

    }


}
原创粉丝点击