Search code examples
javaexcelkill

Kill excel process without saving


I have this code that kills any running Excel process correcly.

 public static void killExcel(){
     while (isProcessRuning("EXCEL.EXE")){
        Runtime.getRuntime().exec("taskkill /IM EXCEL.EXE");
     }
}

 public static boolean isProcessRuning(String serviceName) throws Exception {
         Process p = Runtime.getRuntime().exec(TASKLIST);
         BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
         String line;
         while ((line = reader.readLine()) != null) {
          if (line.contains(serviceName)) {
           return true;
          }
         }    
         return false;
    }

My problem is if the Excel file prompt the saving question, I got an infinit loop.


Solution

  • Have you tried running taskkill with the /f option to forceably kill ? See here for more details.

    It may be more appropriate to use the default option to allow Excel to quit nicely if it can. If it doesn't exit then revert to the forceable variant. Processes will normally exit if requested. If it's not, it's likely for a good reason.