`
mengke
  • 浏览: 7783 次
  • 性别: Icon_minigender_1
  • 来自: 南通
文章分类
社区版块
存档分类
最新评论

jxls 升级 jexl 1.1 至 2.X 支持中文标签

阅读更多
修改net.sf.jxls.parser包下的
Expression


package net.sf.jxls.parser;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.jxls.transformer.Configuration;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;


/**
 * Represents JEXL expression
 * @author Leonid Vysochyn
 */
public class Expression {

    public static final String aggregateSeparator = "[a-zA-Z()]+[0-9]*:";

    String expression;
    String rawExpression;
    String aggregateFunction;
    String aggregateField;
    Map beans;
    List properties = new ArrayList();
    org.apache.commons.jexl2.Expression jexlExpresssion;

    Configuration config;

    Property collectionProperty;

    public Property getCollectionProperty() {
        return collectionProperty;
    }

    public List getProperties() {
        return properties;
    }

    public String getExpression() {
        return expression;
        
    }

    public Expression(String expression, Configuration config) {
        this.expression = expression;
        this.config = config;
    }

    public Expression(String expression, Map beans, Configuration config) throws Exception {
        this.config = config;
        this.expression = expression;
        this.rawExpression = parseAggregate(expression);
        this.beans = beans;
        //修改表达式 创建方法
        JexlEngine JEXL = new JexlEngine();
       jexlExpresssion = JEXL.createExpression("map."+rawExpression);
        
        
       // jexlExpresssion = ExpressionFactory.createExpression( rawExpression );
        
        
        
        
        
        
        parse();
    }
    private void parse() {
        Property prop = new Property(rawExpression, beans, config);
        this.properties = new ArrayList();
        this.properties.add(prop);
        if (prop.isCollection() && aggregateFunction == null && collectionProperty == null) {
            this.collectionProperty = prop;
        }
    }
    
    
    
    public Object evaluate() throws Exception {
        if (beans != null && !beans.isEmpty()){
            /*-------------------开始修改------------------------------*/
            org.apache.commons.jexl2.JexlContext jc = new MapContext();
            jc.set("map", beans); //jexl 2 开始必须要名称 默认设置一个名称map
	        Object ret = jexlExpresssion.evaluate(jc);
            
	        
	        JexlEngine JEXL1 = new JexlEngine();
	            org.apache.commons.jexl2.Expression e = JEXL1.createExpression("map."+rawExpression);//在表达式中增加 我在前面设置的名称 map
		        Object ret1 = jexlExpresssion.evaluate(jc);
		        /*-------------------结束修改------------------------------*/
            if (aggregateFunction != null) {
            	return calculateAggregate(aggregateFunction, aggregateField, ret);
            }
            return ret;
        }
        return expression;
    }

    private String parseAggregate(String expr)
    {
        String[] aggregateParts = expr.split(aggregateSeparator, 2);
    	int i = expr.indexOf(":");
    	if (aggregateParts.length >= 2 && i >= 0) {
    		String aggregate = expr.substring(0, i);
    		if (aggregate.length() == 0) {
    			aggregateFunction = null;
    			aggregateField = null;
    		}
    		else {
    			int f1 = aggregate.indexOf("(");
    			int f2 = aggregate.indexOf(")");
    			if (f1 != -1 && f2 != -1 && f2 > f1) {
    				aggregateFunction = aggregate.substring(0, f1);
    				aggregateField = aggregate.substring(f1+1, f2);
    			}
    			else {
    				aggregateFunction = aggregate;
    				aggregateField = "c1";
    			}
    		}
    		return expr.substring(i+1);
    	}
        aggregateFunction = null;
        aggregateField = null;
        return expr;
    }
    


    private Object calculateAggregate(String function, String field, Object list)
    {
    	Aggregator agg = Aggregator.getInstance(function);
    	if (agg != null) {
    		if (list instanceof Collection) {
	    		Collection coll = (Collection) list;
                for (Iterator iterator = coll.iterator(); iterator.hasNext();) {
                    Object o = iterator.next();
	    			try {
		    			Object f = PropertyUtils.getProperty(o, field);
		    			agg.add(f);
	    			}
	    			catch (InvocationTargetException e) {
	    				e.printStackTrace();
	    			}
	    			catch (NoSuchMethodException e) {
	    				e.printStackTrace();
	    			}
	    			catch (IllegalAccessException e) {
	    				e.printStackTrace();
	    			}
	    		}
    		}
    		else {
    			try {
    				Object f = PropertyUtils.getProperty(list, field);
    				agg.add(f);
    			}
    			catch (InvocationTargetException e) {
    				e.printStackTrace();
    			}
    			catch (NoSuchMethodException e) {
    				e.printStackTrace();
    			}
    			catch (IllegalAccessException e) {
    				e.printStackTrace();
    			}
    		}
    		return agg.getResult();
    	}
        return list;
    }
    
    public String toString() {
        return expression;
    }
}




ExpressionCollectionParser

package net.sf.jxls.parser;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.parser.ASTIdentifier;
import org.apache.commons.jexl2.parser.ASTReference;
import org.apache.commons.jexl2.parser.Node;
import org.apache.commons.jexl2.parser.Parser;
import org.apache.commons.jexl2.parser.SimpleNode;


public class ExpressionCollectionParser {
    
    public final static String COLLECTION_REFERENCE_SUFFIX = "_JxLsC_";

    // This is set up as a ThreadLocal parser to avoid threading issues.
    private static ThreadLocal parser = new ThreadLocal() {
        protected synchronized Object initialValue() {
            return new Parser(new StringReader(";"));
        }
    };

    private boolean jexlInnerCollectionsAccess;


    private String collectionExpression;
    private Collection collection;
    
    public ExpressionCollectionParser(org.apache.commons.jexl2.JexlContext jexlContext, String expr, boolean jexlInnerCollectionsAccess) {
        try {
            this.jexlInnerCollectionsAccess = jexlInnerCollectionsAccess;
            SimpleNode tree = ((Parser) parser.get()).parse(new StringReader(expr),null);
            ArrayList references = new ArrayList();
            findReferences(references, tree);
            findCollection(jexlContext, references);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getCollectionExpression() {
        return collectionExpression;
    }
    
    public Collection getCollection() {
        return collection;
    }
    
    private void findReferences(List references, Node node) {
        
        if (node instanceof ASTReference) {
            references.add(node);
        }
        
        int childCount = node.jjtGetNumChildren();
        for (int i = 0; i < childCount; i++) {
            findReferences(references, node.jjtGetChild(i));
        }
    }
    
    private void findCollection(JexlContext jexlContext, List references) {
        
        Node node;
        
        for (Iterator itr = references.iterator(); itr.hasNext();) {
            node = (Node) itr.next();
            String newExpression = findCollectionProperties(jexlContext, node);
            if (newExpression != null) {
                if (!newExpression.endsWith(COLLECTION_REFERENCE_SUFFIX)) {
                    this.collectionExpression = newExpression;
                }
                break;
            }
        }
    }
    
    private String findCollectionProperties(JexlContext jexlContext, Node node) {
        
        int childCount = node.jjtGetNumChildren();
        Node child  ;
        String subExpr = null;
        
        for (int i = 0; i < childCount; i++) {
            child = node.jjtGetChild(i);
            if (child instanceof ASTIdentifier) {
                ASTIdentifier ident = (ASTIdentifier) child;
                if (subExpr == null) {
                    subExpr =ident.image;
                } else {
                    subExpr = subExpr + "." + ident.image;;
                	
                }
                if( jexlInnerCollectionsAccess ){
                    if (subExpr.endsWith(COLLECTION_REFERENCE_SUFFIX)) {
                        return subExpr;
                    }
                }
                try {
                	
                	JexlEngine JEXL = new JexlEngine();
        	        Expression e = JEXL.createExpression("map."+subExpr);
//                    Expression e = ExpressionFactory.createExpression(subExpr);
                    Object obj = e.evaluate(jexlContext);
                    if (obj instanceof Collection) {
                        this.collection = (Collection) obj;
                        return subExpr;
                    }
                } catch (Exception e) {
                    // TODO: insert proper logging here
                    return null;
                }
            }
        }
        
        return null;
    }    
}


Property

package net.sf.jxls.parser;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import net.sf.jxls.transformer.Configuration;


import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.MapContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Represents a property in excel template
* @author Leonid Vysochyn
*/
public class Property {
    protected final Log log = LogFactory.getLog(getClass());
    List propertyTokens = new ArrayList();

    private String beanName;
    private Object bean;
    private String collectionName;
    private Collection collection;

    private String property;
    private Object propertyValue;

    Configuration config;

    public Property(String value) {
        propertyValue = value;
    }

    public Property(String property, Map beans, Configuration config) {
        this.property = property;
        this.config = config;
        propertyValue = getPropertyValue(beans);
    }

    public boolean isConstant(){
        return property==null;
    }

    public Object getPropertyValue(Map beans) {
    JexlContext jc = new MapContext();
    jc.set("map", beans);
//        JexlContext context = JexlHelper.createContext();
//        context.setVars(beans);
        ExpressionCollectionParser parser = new ExpressionCollectionParser(jc,this.property + ";", config.isJexlInnerCollectionsAccess());
        if (parser.getCollection() == null) {
            propertyValue = null;
        } else {
            collectionName = parser.getCollectionExpression();
            collection = parser.getCollection();
            beanName = null;
            bean = null;
        }
       
        return propertyValue;
    }

    public boolean isCollection() {
        return collectionName != null;
    }

    public boolean isNull() {
        return getPropertyValue() == null;
    }

    public String getBeanName() {
        return beanName;
    }

    public String getCollectionName() {
        return collectionName;
    }

    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }


    public String getProperty() {
        return property;
    }


    public Collection getCollection() {
        return collection;
    }

    public void setCollection(Collection collection) {
        this.collection = collection;
    }

    public String getFullCollectionName() {
        if (beanName == null) {
            return collectionName;
        }
        return beanName + "." + collectionName;
    }

    public String getPropertyNameAfterLastDot() {
        String propertyName = null;
        if (property != null) {
            int dotIndex = property.lastIndexOf(".");
            if (dotIndex >= 0) {
                propertyName = property.substring(dotIndex + 1);
            } else {
                propertyName = property;
            }
        }
        return propertyName;
    }

    public String getPropertyNameAfterFirstDot() {
        String propertyName = null;
        if (property != null) {
            int dotIndex = property.indexOf(".");
            if (dotIndex >= 0) {
                propertyName = property.substring(dotIndex + 1);
            } else {
                propertyName = property;
            }
        }
        return propertyName;
    }

    public String toString() {
        return "Property{" +
                "property='" + property + "'}";
    }

    public Object getPropertyValue() {
        if( bean instanceof String){
            return bean;
        }
        return propertyValue;
    }

    public void setPropertyValue(Object propertyValue) {
        this.propertyValue = propertyValue;
    }

    public Object getBean() {
        return bean;
    }

    public void setBean(Object bean) {
        this.bean = bean;
    }

}







分享到:
评论
1 楼 jaw111 2014-04-15  
非常感谢!!!
JEXL1对中文支持不是很好,刚好需要用JXLS绑定JEXL2.

相关推荐

    jxls-core完美支持poi4.x

    最近项目poi升级,导出excel有异常。通过修改源码,支持poi4.x。已经完美验证。

    使用 jxls2.X 导出excel文件

    "使用jxls2.X导出Excel文件"的主题涉及了如何利用Java来生成和操作Excel文档,尤其适用于需要动态生成内容的场景。在这个项目案例中,开发者使用了jxls库的最新版本(jxls2),它是一个强大的工具,能够帮助程序员将...

    jxls2.6兼容2.X版本 demo集合 包含 循环 判断 合并单元格等共33个单独的例子,可以单独执行

    jxls作为比较好的excel模版方案,比poi和easyExcel相对扩展性更高。 demo包含全部官方例子和模版, 2.6官方新增合并单元格标签,jx:mergecells 以及其他相关一切demo,很好的资源,分享给大家,供大家学习交流。 ...

    excel模板所需jar:commons-jexl-2.1.1.jar 和 jxls-core1.0.3.jar

    本文将详细阐述`jxls`库以及与之相关的`commons-jexl-2.1.1.jar`和`jxls-core1.0.3.jar`这两个关键的Java库,以及它们如何协同工作来实现Excel模板的动态数据填充。 `jxls`是一个Java库,它的主要功能是帮助开发者...

    commons-jexl-2.0.jar

    &lt;groupId&gt;org.apache.commons &lt;artifactId&gt;commons-jexl &lt;version&gt;2.0 &lt;/dependency&gt;

    jxls-core-1.0.7.jar包,支持poi4.0即以上

    jxls-core-1.0.7.jar包源码,支持jdkl8以及poi4.0以上的版本,原jar包作者的最高版本多年没有维护,通过修改原作者源码,为1.0.7版本支持高版本的poi库如poi4.0.1及以上。

    jxls导excel所需的所有jar包

    2. **jxls-poi-2.x.jar**: 这是JXLS针对Apache POI的扩展,POI是Java处理Microsoft Office格式文档的库。这个扩展使得JXLS能够与POI协同工作,处理Excel文件。 3. **poi-ooxml-schemas-4.x.x.jar**: Apache POI项目...

    解决net.sf.jxls1.0.6中getCellType()和org.apache.poi4.1.2报错问题

    解决net.sf.jxls1.0.6中getCellType()和org.apache.poi4.1.2报错问题

    使用net.sf.jxls下的jxls-core包进行复杂的Excel导出

    使用net.sf.jxls下的jxls-core包进行复杂的Excel导出

    jxls-core-1.1.3.jar ,java根据模版导出excel功能

    此版本是自己编译的,增加了实现java 在excel模版上导出图片的功能,并优化了模版导出数据功能

    官方jxls-2.4.1

    2. **数据绑定**:通过AOP(面向切面编程)技术,Jxls能够将Java对象的数据自动绑定到Excel单元格,极大地提高了数据处理的效率和准确性。 3. **复杂计算与公式**:除了基本的数据填充,Jxls还支持Excel内置的公式...

    jxls包——jxls-1.0.1.zip

    jXLS是一个小而易用的Java库,它用于根据XLS模板文件生成Excel数据文件,或者根据XML配置文件从Excel文件中读出数据。 jXLS的功能是:只使用几行代码就可以建立极端复杂的Excel报表。你所需要实现的大部分工作是...

    关于net.sf.jxls下的jxls-core包与POI 4.1.2版本不兼容的解决

    关于net.sf.jxls下的jxls-core包与POI 4.1.2版本不兼容的解决

    jxls excel导出 中文指导教程.zip

    一.JXLS简介 ,安装,以及标签使用说明 Each数据循环、公式使用、if-else逻辑判断、加载图片、动态表格、数据分组、单元格超链接、SQL模板实现、自定义表达式解析引擎、自定义函数、单元格合并

    jxls 2.3.0

    2. **jxls-jexcel-1.0.6.jar** - 这个库是jxls与JExcelAPI(一个开源的Java API,用于读写Excel文件)的桥梁。JExcelAPI支持旧版本的Excel格式(.xls),而jxls通过此库可以与之交互,处理旧版Excel文件格式。 3. ...

    使用 jxls2.X 导出excel文件源码

    本篇文章将深入探讨如何使用 `jxls2` 库来导出Excel文件,同时参考《使用 jxls2.X 导出excel文件源码》这篇博客文章中的案例进行讲解。 首先,我们需要理解 `jxls2` 的核心概念:模板和转换器。模板是预先设计好的...

    jxls2.3 官网最新下载

    **Jxls库详解** Jxls是一个Java库,用于简化Excel电子表格数据的处理。它将Java集合、POJO(Plain Old Java Object)或其他数据源与Excel模板结合,自动生成复杂的Excel报告。标题“jxls2.3 官网最新下载”指的是你...

    jxls-core1.0.6不支持poi4.1.2

    jxls-core升级为poi4.1.2

    jxls使用的所有jar包(9个)

    包括以下几个: commons-beanutils.jar commons-collections-2.1.1.jar commons-digester.jar commons-jexl-1.1.jar commons-logging.jar jxl.jar jxls.jar jxls-core-0.9.5.jar poi_2006_5_19.jar

    jxls-2.4-jdk1.7.jar

    兼容jdk1.7-兼容POM3.11及以上版本;如果需要源码,可以查看 https://download.csdn.net/download/iamcuilong/12066123

Global site tag (gtag.js) - Google Analytics