I have created a simple java program to open an excel file and write data to it, once the data is written I then proceed to open the file to view the spreadsheet:
String[] cmdarray=new String[]{"cmd.exe","/c","C:\\Users\\Jason\\Documents\\*******\\********\\******.xls"};
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec(cmdarray);
as part of the learning curve I then try to close the file 10 secs later with:
process.destroy();
but this isn't closing the window. Can anyone point out where I am going wrong? Thank you.
private static void OpenExcel() throws IOException {
//Find the File and open it
String[] cmdarray=new String[]{"cmd.exe","/c","C:\\Users\\Jason\\Documents\\*********\\*********\\********.xls"};
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec(cmdarray);
try{
//Delay
TimeUnit.SECONDS.sleep(10);
}catch (InterruptedException e) {
e.printStackTrace();
//Handle exception
}
//Close Excel
System.out.println("Closing Excel");
process.destroy();
}
}
One of the reason could be well-known JDK bug:
The fundamental problem here is that, unlike Unix, Windows does that maintain parent-child relationships between processes. A process can kill its own immediate children, but unless you make other arrangements to obtain the information, can't kill any 'grand-children' because it has no way of finding them.
You can try with direct execution of Excel, not via cmd:
Runtime.getRuntime().exec("C:\\full\\path\\to\\excel.exe C:\\file.xls");