1

I'm trying to open an xls sheet in the browser, not in MS Excel. I've tried with Desktop.getDesktop().browse(fileName.toURI()); but is not working. This is the complete code of the execute method:

public String execute() throws Exception
{    
    String rutaArchivo = System.getProperty("catalina.base")+"/ejemploExcelJava.xls";     

    File archivoXLS = new File(rutaArchivo);

    if(archivoXLS.exists()) {
        archivoXLS.delete();
    }
    archivoXLS.createNewFile();

    Workbook libro = new HSSFWorkbook();

    FileOutputStream archivo = new FileOutputStream(archivoXLS);

    Sheet hoja = libro.createSheet("Mi hoja de trabajo 1");

    Date fechaActual = new Date();
    for (int f = 0; f < 10; f++) {            
        Row fila = hoja.createRow(f);            
        for (int c = 0; c < 5; c++) {
            Cell celda = fila.createCell(c);               
            if (f == 0) {
                celda.setCellValue("Encabezado #" + c);
            } else {
                celda.setCellValue(fechaActual.getHours() +  ":"  + fechaActual.getMinutes());
            }
        }
    }        
    libro.write(archivo);        
    archivo.close();        
    Desktop.getDesktop().browse(archivoXLS.toURI());                                                                                         
 }

Anyway, this works opening excel from Microsoft Office Excel application, but only by running the project from Netbeans. If I try to open it from Tomcat without Netbeans, it doesn't work.

cocacolo
  • 37
  • 8

1 Answers1

0
  1. You can output any binary result with the Stream Result;
  2. To output an Excel file (both by reading an existing one and by creating a new one) you need to set the right Content Type, according to the type of excel file you are streaming out (commonly XLS or XLSX), like described in this answer.
  3. You can instruct the User Agent that it needs to open a file inside the browser (instead of asking for download / open with a desktop application) by changing the default Content Disposition from attachment to inline;
  4. Opening an unknown binary file inline is up to the client: if you stream out a JPEG, the browser will open it easily; if you stream out a PDF (or an Excel document, a Word document, and so on), the browser will search for an appropriate plugin (for example Adobe Acrobat), and if not found, will try to open it with the desktop application (for example Adobe Reader) anyway. That's why opening an Excel in Internet Explorer (that has the plugin inbuilt) works, while opening it in Firefox doesn't.
Community
  • 1
  • 1
Andrea Ligios
  • 47,982
  • 25
  • 109
  • 228
  • 1
    sorry for taking my long time to answer and vote you, dude. I've just rescued my Stack Overflow account since almost 2 years ago and saw this, remembering that it helped me. Thanks, I hope it helps somebody else. – cocacolo Jan 27 '16 at 17:04
  • Better late than never ! :P – Andrea Ligios Jan 27 '16 at 17:08