JAVA的JS引擎实例(包含Excel读取)

需引入下图所示包:
需引入包
首先ParseExcel.js文件的内容如下:

importClass(org.apache.poi.ss.util.CellRangeAddress);
importClass(org.apache.poi.ss.usermodel.Cell);
importClass(org.apache.poi.ss.usermodel.DateUtil);
importClass(org.apache.poi.ss.usermodel.Row);
importClass(org.apache.poi.ss.usermodel.Sheet);
importClass(org.apache.poi.ss.usermodel.Workbook);
importClass(org.apache.poi.ss.usermodel.WorkbookFactory);

importClass(java.util.List);
importClass(java.util.ArrayList);
importClass(java.util.HashMap);
importClass(java.util.Map);

var wb = WorkbookFactory.create( $P.get("inputStream") );
var data = new ArrayList();
for(var k=0;k<wb.getNumberOfSheets(); k++){
     var st = wb.getSheetAt(k);    
     for(var rowIndex = 1; rowIndex <= st.getLastRowNum(); rowIndex++){
     var row = st.getRow(rowIndex);
     if (row == null) { 
       continue;
     }
     var map=new HashMap();
     var cell = null;
     for (var columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
           cell = row.getCell(columnIndex);
           if (cell== null) { 
               continue;
           }
          if(cell != null){
              cell.setCellType(cell.CELL_TYPE_STRING);
          }
          map.put("COL_"+columnIndex,cell.getStringCellValue());
          }
     data.add(map); 
    }
}

java代码:

package test.jsonp.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JsEngineTest
{

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception
    {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName( "javascript" );

        // 1 
        engine.put( "msg", "test" );
        String str = "msg += 'for syngna';var user = {name:'syngna',age:27,compose:['t1','t2']}; var name = user.name; var cp = user.compose[1];";
        engine.eval( str );

        String msg = (String) engine.get( "msg" );
        String name = (String) engine.get( "name" );
        String cp = (String) engine.get( "cp" );
        System.out.println( msg );
        System.out.println( name + ":" + cp );
        System.out.println(obj2map( engine, engine.get( "user" ) ));
        // 2 
        engine.eval( "function add (a, b) {c = a + b; return c; }" );
        Invocable jsInvoke = (Invocable) engine;

        Object result1 = jsInvoke.invokeFunction( "add", new Object[] { 10, 5 } );
        System.out.println( result1 );

        // 3 
        Adder adder = jsInvoke.getInterface( Adder.class );
        int result2 = adder.add( 10, 35 );
        System.out.println( result2 );

        // 4 
        engine.eval( "function run() {print('for function test');}" );
        Invocable invokeEngine = (Invocable) engine;
        Runnable runner = invokeEngine.getInterface( Runnable.class );
        Thread t = new Thread( runner );
        t.start();
        t.join();

        //------------------------------------------------------------------------------------------------------------------------
        HashMap<String, Object> $P = new HashMap<String, Object>();
        InputStream is = new FileInputStream( "D:/test.xlsx" );
        $P.put( "inputStream", is );
        engine.put( "$P", $P );

        String userDirPath = System.getProperty( "user.dir" );
        String jsFilePath = userDirPath + "/WebRoot/js/ParseExcel.js";
        String jsStr = readText( new File( jsFilePath ) );
        //------------------------------------------------------------------------------------------------------------------------
        // 5 
        String jsCode = "importPackage(java.util); importClass(java.util.HashMap); \n var list2 = Arrays.asList(['A', 'B', 'C']);\n var map1=new HashMap();\n map1.put('name','syngna'); $P.put('value','tet')";
        jsCode = jsCode + jsStr;

        engine.eval( jsCode );
        List<String> list2 = (List<String>) engine.get( "list2" );
        HashMap<String, String> map = (HashMap<String, String>)engine.get( "map1" );
        for( String val : list2 ) {
            System.out.println( val );
        }
        for( String key : map.keySet() ){
            System.out.println(map.get( key ));
        }
        System.out.println($P);

        List<HashMap<String, String>> data = (List<HashMap<String, String>>) engine.get( "data" );
        for( int i = 0; i < data.size(); i++ ) {
            System.out.println(data.get( i ));
        }
    }

    /*
     * js对象转HashMap
     */
    public static Map<String, Object> obj2map(ScriptEngine engine,  
            Object nativeObject) throws ScriptException, NoSuchMethodException {  
        Map<String, Object> map = new HashMap<String, Object>();  

        //engine.put("map", map);  
        //engine.put("obj", nativeObject);
        String script = "   function dosomething(map, obj){                                         "  
                + "                         for (i in obj){                                         "  
                + "                             map.put(i,obj[i]);                                  "  
                + "                         }                                                       " + "                   }                                                               ";  
        engine.eval(script);  

        Invocable inv = (Invocable) engine;  
        inv.invokeFunction("dosomething", map, nativeObject);  
        return map;  

    }

    public static String readText(File file){
        String result = "";
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次读一行
                result = result + "\n" +s;
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }
}

interface Adder
{
    int add(int a, int b);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值