Foros del Web » Programación para mayores de 30 ;) » Java »

[SOLUCIONADO] excel en jsp

Estas en el tema de excel en jsp en el foro de Java en Foros del Web. estoy utilizando poi para creqr excel crea el excel normal, pero quiero que me envie la ventanita donde me indique si guardo o abrir el ...
  #1 (permalink)  
Antiguo 22/03/2013, 10:20
 
Fecha de Ingreso: agosto-2010
Mensajes: 127
Antigüedad: 13 años, 7 meses
Puntos: 1
excel en jsp

estoy utilizando poi para creqr excel crea el excel normal, pero quiero que me envie la ventanita donde me indique si guardo o abrir el archivo, como lo puedo hacer
  #2 (permalink)  
Antiguo 22/03/2013, 10:55
Avatar de chuidiang
Colaborador
 
Fecha de Ingreso: octubre-2004
Mensajes: 3.774
Antigüedad: 19 años, 6 meses
Puntos: 454
Respuesta: excel en jsp

Hola:

La solución fácil es genrar el fichero excel en un sitio accesible desde el navegador y colocar un enlace en tu página a ese fichero. Al hacer click el navegador te ofrecerá descargarlo. Esta opción vale si el excel está generado antes de mostrarle al usuario la página con el link de descarga.

Si el excel se debe generar al vuelo, la otra opción, un pelín más compleja, crea un jsp o servlet cuyo único cometido sea crear el excel y devolverlo, ese jsp o servlet no debe enviar absolutamente nada más al navegador.

En ese jsp o servlet, fija el content-type del header a application/vnd.ms-excel y si quieres el nombre de fichero puedes ponerlo tambíén el el header

Código jsp:
Ver original
  1. <%
  2. response.setHeader("Content-type","application/vnd.ms-excel");
  3. response.setHeader("Content-disposition","inline; filename=nombre.xls");
  4. ...
  5. %>

Y ahora sólo tienes que abrir el fichero excel como si fuera un fichero binario cualquiera, leerlo con read() como si fueran bytes e ir enviándolo por el response

Código jsp:
Ver original
  1. <%
  2. abre fichero excel
  3. mientras haya bytes {
  4.    lee bytes
  5.    response.getOutputStream().write(bytes);
  6. }
  7. response.flush();
  8. response.close();
  9. %>

En un servlet es más fácil, en un jsp tienes el problema de que no puedes escribir nada hacia el navegador y eso incluye retornos de carro entre tags jsp. Aquí tienes un ejemplo con un pdf y se menciona el problema este de los retornos de carro http://stackoverflow.com/questions/1...-this-response

Se bueno.
__________________
Apuntes Java
Wiki de Programación
  #3 (permalink)  
Antiguo 22/03/2013, 11:09
 
Fecha de Ingreso: mayo-2010
Mensajes: 99
Antigüedad: 13 años, 11 meses
Puntos: 5
Respuesta: excel en jsp

Wenas, pues yo una vez tuve que hacer algo parecido en Struts 1.x,
en mi jsp ponia

codigo javascript
Código PHP:

jQuery
('a[name=exportar]').click(function (){       
       
            
jQuery('#forma').attr("action",'<%=request.getContextPath()%>/repLevels.do?vinculo=exportarExcel');
            
jQuery"#dialogGraficas").dialog"close" );    
            
jQuery'#forma').submit();  
       
    }); 
en mi jsp tenia
Código PHP:

<div    class="   contSinTab "></div>
                    <
div class="right controles">
                    <
a   class="boton-rojo"  name="exportar" id="exportar"><bean:message key='sistema.createGraphic' /></a>
                   </
div
Y en el action

Código PHP:
public ActionForward exportarExcel(ActionMapping mappingActionForm forma
                        
HttpServletRequest requestHttpServletResponse response) {
        ........
        try {

ArrayList exportList=(ArrayList)request.getSession().getAttribute("nivelesList");
           .................
//mas codigo
             
             
report = new RepLevelsExcel();
            
            
report.process(request,responsetipografexportList,formtemp);
            
            
actionForward "success";
           
            
        } catch (
Exception e) {
            
            
actionForward "error";
        } 
finally {
            return (
mapping.findForward(actionForward));
        }
    } 
Y para el excel yo use plantillas
Código PHP:
..........//mas codigo

/** Excel file used as template  */
    
public static final String EXCEL_FILE_LEVELS "/plantilla_reportes/ReporteNivelesService.xls";
    
    public 
RepLevelsExcel() {
        
    }
    
    
/**Processes requests for both HTTP GET and POST methods.
     * @param request servlet request
     * @param response servlet response
     */
    
public void process(HttpServletRequest requestHttpServletResponse responseString graficasArrayList listaBeanForm formthrows ServletExceptionIOException {
                    
        
String[] abc = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        
        
HttpSession session request.getSession();
        
ServletContext context session.getServletContext();
        
String pathreal context.getRealPath(EXCEL_FILE_LEVELS);
        
        
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(pathreal));

        
HSSFWorkbook libro = new HSSFWorkbook(fs);
        
HSSFCell cel null;
        
hoja libro.getSheetAt(0);
        
        
hoja libro.getSheetAt(3);
        for (
int i1;i<=3;i++){
        
cel setCell(abc[1] + iform.getFechaSinIni()+" al "+form.getFechaSinFin());
        
        }
        
hoja libro.getSheetAt(2);

...............
//mas codigo

 
response.setContentType("application/xls"); 
        
Calendar cal Calendar.getInstance();
        
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy_HH:mm:ss");
        
response.setHeader("Content-disposition""attachment;filename=Services_"+sdf.format(cal.getTime())+".xls");
        
libro.write(response.getOutputStream()); 
Saludos, espero te ayude esto

Última edición por abulon81; 22/03/2013 a las 11:17
  #4 (permalink)  
Antiguo 18/10/2014, 23:43
 
Fecha de Ingreso: octubre-2014
Mensajes: 1
Antigüedad: 9 años, 6 meses
Puntos: 0
Respuesta: excel en jsp

Cree un servlet que me genera un archivo en excel y se descarga de forma automatica ,el incoveniente viene cuando llamo al servlet desde jquery no se puede descargar y me direcciona a la funcion error de jquery ajax, espero alguien me pueda ayudar

copio parte del servlet donde se genera el archivo utilizo la libreria apache poi

excel2007 x = (excel2007) imp;
Workbook libro = x.getLibro();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment;filename=" + repo.getNOMARC() + ".xlsx");
libro.write(response.getOutputStream());
response.getOutputStream().close();

adjunto mi codigo de jquery

$(document).ready(function() {
$("#generar").click(function(e) {
e.preventDefault();
var btn = $(this);
btn.button('loading');
var dataString = $('#myform').serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "GenerarArchivo",
data: dataString,
error: problemas,
success: function(data) {
$("#resultado2").html("se genero");
}
}).always(function() {
btn.button('reset')
});
;
});
});
function problemas() {
alert("ERROR");
}

Etiquetas: excel, jsp
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:52.