由于业务问题,要处理excel的复杂表,但是用java操作excel相对于python来说麻烦很多,所以想试一试用java调用python脚本,我看了两种方法,自己记录一下。
1、使用Jython
导入依赖:(现在建议版本 >= 2.7.2)
<!-- https://mvnrepository.com/artifact/org.python/jython-standalone -->
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.2</version>
</dependency>
//创建PythonInterpreter对象
PythonInterpreter interpreter = new PythonInterpreter();
//简单的直接运行python脚本
interpreter.exec(fileName)
但是实际上我发现麻烦的问题在于,如果python脚本中有第三方库,java是无法运行的,后面环境的配置是大问题。
2、直接运行python
这种方法其实比较好用,它不需要考虑python脚本中有没有第三方库。
try {
// 传递的excel文件地址,用绝对路径比较好
String lj = "";
// 相当于命令行的python 文件路径 lj,执行python脚本
String[] test = new String[]{"python",文件路径,lj};
//命令行操作
Process exec = Runtime.getRuntime().exec(test);
// 设置字符编码为gb2312,要不会出现乱码
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(exec.getInputStream(), "gb2312"));
String line = null;
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println("结束");
}
这个方便但是他不可以传输文件,只能传递参数