使用环境变量查找Excel目录并运行脚本

问题描述 投票:0回答:3

在Java中,我需要将.xlsb文件转换为.xlsx,然后通过运行console命令执行:

String command = "C:\\Program Files (x86)\\Microsoft Office\\Office12\\excelcnv.exe -oice "+fileName+" "+convertedFileName;
Runtime commandPrompt = Runtime.getRuntime();
try {           
    Process powershell = commandPrompt.exec(command);
    powershell.waitFor();
} catch (Exception e) { 
    System.out.println("Error converting file to XLSX");
    e.printStackTrace();
}

但我想将路径替换为Excel文件,因为每台机器可能会有所不同。我正在尝试使用%ProgramFiles(x86)%而不是C:\\Program Files (x86)但是它不起作用,任何想法如何替换excelcnv.exe的路径并使其更普遍?

java excel windows type-conversion
3个回答
0
投票

String command =“excelcnv -oice”+ fileName“”+ convert FileName;如果excel在$ Path中,应该可以工作


0
投票

你可以简单地将它作为参数传递给程序。假设您的类在org.stack.com包中,那么您需要执行以下操作:

在代码中使用以下行(args[0]表示从命令行传递的第一个参数)

String command = args[0] + " -oice " + fileName + " " + convertedFileName;;

编译 :

javac Test.java

执行 :

java org.stack.com.Test my_dynamic_path_here

0
投票

尝试使用System.getenv(“FOO”)来获取环境变量

对于程序文件目录,请使用:

System.getenv("ProgramFiles");

或者对于64位PC上的32位文件夹

System.getenv("%programfiles% (x86)"); 
© www.soinside.com 2019 - 2024. All rights reserved.