I have a Java program that edits an existing excel file and saves it as a new file. However, I would also like the program to automatically open the newly created file upon ending. Is there an apache poi command that lets me do this?
As you have not Provided Code , I m using the Example of ViralPatel Tutorial
Lets Create Excel File First
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] { "Emp No.", "Name", "Salary" });
data.put("2", new Object[] { 1d, "John", 1500000d });
data.put("3", new Object[] { 2d, "Sam", 800000d });
data.put("4", new Object[] { 3d, "Dean", 700000d });
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
try {
FileOutputStream out = new FileOutputStream(new File("D:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
/** Opening Excel File From Java **/
try {
Desktop.getDesktop().open(new File("D:\\new.xls"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Output

Solution : Put this code with Try/Catch Block after You have created Excel with correct Location, It will be opened Automatically
Desktop.getDesktop().open(new File("D:\new.xls"));
Else u can invoke this as well
Try to use Desktop.open() instead of Desktop.edit() :
Desktop dt = Desktop.getDesktop();
dt.open(new File("D:\\new.xls"));
If Desktop.open() is not available then the Windows file association can be used :
Process p = Runtime.getRuntime() .exec("rundll32
url.dll,FileProtocolHandler " + "D:\\new.xls");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With