How to open an Excel sheet in browser using Java+S

2019-07-29 06:39发布

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.

1条回答
该账号已被封号
2楼-- · 2019-07-29 07:11
  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.
查看更多
登录 后发表回答