Robot robot = new Robot();
Rectangle rectangle = new Rectangle(75, 124, 1095, 480);
File file = new File("screen-capture.jpg");
Desktop.getDesktop().open(new File("C:\\Users\\AnubhavPatel\\Desktop\\Testing_Code.xlsx"));
Thread.sleep(7000);
BufferedImage bufferedImage = robot.createScreenCapture(rectangle);
boolean status = ImageIO.write(bufferedImage, "jpg", file);
System.out.println("Screen Captured ? " + status + " File Path:- " + file.getAbsolutePath());
Runtime.getRuntime().exec("cmd /c taskkill /f /im excel.exe");
Open the file with a library, and then close it with the library's close command.
Right now, you are sending a kill command to Excel. Excel doesn't get a message you want to close a file, it gets the message it needs to shut down. You can't make this kind of an approach inform excel to close a file.
I used this approach-
//Open the excel file using Desktop.getDesktop()
Desktop.getDesktop().open(new
File("C:\\Users\\AnubhavPatel\\Desktop\\Testing_Code_Macro.xlsm"));
Thread.sleep(5000);
//Save and close it using robot class
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_F4);
robot.keyRelease(KeyEvent.VK_F4);
robot.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(5000);
//Then write to it using outputStream
FileOutputStream outputStream = new FileOutputStream(
"C://Users//AnubhavPatel//Desktop/Testing_Code_Macro.xlsm");
workbook.write(outputStream);
outputStream.close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.