[resolvido]poi hssf xls jsp servlet

1 resposta
J

Pessoal, estou criando um sistema para cadastro de chamados, e gostaria de disponibilizar o dados, “tabelas” do banco de dados, em excel , utilizando POI HSSF. Utilizando classe e atribuindo um endereço onde a planilha será gerada esta funcionando , porém meu intuito é que o usuário consiga baixar o excel direto da pagina jsp através de um botão, pesquisando na internet e em revistas encontrei diversos exemplos e muitos bugs mais nenhum exemplo utilizando servlet e jsp. Abaixo a classe

package br.com.teste;

import java.io.*;
import java.sql.PreparedStatement;

import java.sql.Connection;

import  org.apache.poi.hssf.usermodel.HSSFSheet;

import  org.apache.poi.hssf.usermodel.HSSFWorkbook;

import  org.apache.poi.hssf.usermodel.HSSFRow;

import  org.apache.poi.hssf.usermodel.HSSFCell;

import br.com.util.ConnectionFactory;
import br.com.dao.JDBCChamadoDAO;

import com.mysql.jdbc.ResultSet;

public class CreateExlFile{ // classe que gera o arquivo

static Connection connection=null;

public static void main(String[]args){
connection = ConnectionFactory.getCoonection();
	
	try {
		String filename="G:/NewExcelFile.xls" ;
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet =  workbook.createSheet("Tabela1");  
        
        HSSFRow rowhead=   sheet.createRow((short)0);
        rowhead.createCell(0).setCellValue("numChamado");
        rowhead.createCell(1).setCellValue("Analista");
        rowhead.createCell(2).setCellValue("data");
        rowhead.createCell(3).setCellValue("piloto");
        rowhead.createCell(4).setCellValue("sistema");
        rowhead.createCell(5).setCellValue("origem");
        rowhead.createCell(6).setCellValue("resolvidoN1");
        rowhead.createCell(7).setCellValue("redirecionado Para");
        rowhead.createCell(8 ).setCellValue("Resolução Final");
      
        String SQL = "SELECT * FROM chamado";
		PreparedStatement ps = connection.prepareStatement(SQL);
		ResultSet rs = (ResultSet) ps.executeQuery();
		
		int i =0;
		
		while(rs.next()){
			HSSFRow row =   sheet.createRow(i);
			row.createCell(0).setCellValue(rs.getString("numChamado"));
	        row.createCell(1).setCellValue(rs.getString("nomeAnalista"));
	        row.createCell(2).setCellValue(rs.getString("data"));
	        row.createCell(3).setCellValue(rs.getString("piloto"));
	        row.createCell(4).setCellValue(rs.getString("sistema"));
	        row.createCell(5).setCellValue(rs.getString("origem"));
	        row.createCell(6).setCellValue(rs.getString("resolvidoN1"));
	        row.createCell(7).setCellValue(rs.getString("redirecionadoPara"));
	        row.createCell(8 ).setCellValue(rs.getString("resolucaoFinal"));
		i++;
		}
        
          
        FileOutputStream fileOut =  new FileOutputStream(filename);
        workbook.write(fileOut);
        fileOut.close();
        System.out.println("Seu arquivo excel foi gerado!");
		
		
	} catch (Exception e) {
		throw new RuntimeException ("Falha", e);
	}

}}

Gostaria que o arquivo que é gerado por esta classe, estivesse disponível para download na pagina JSP, Somebody Help-me , Thks

1 Resposta

J

Boa Noite Pessoal, consegui colando o arquivo POI .jar dentro da pasta lib no eclipse , pois adicionando na biblioteca “Java Build Path” estava gerando diversos erros , segue abaixo pagina de teste caso alguém tenha a mesma dúvida.

<%<a class="mention" href="/u/page">@page</a> import=“com.sun.org.apache.xerces.internal.util.URI”%>

<%<a class="mention" href="/u/page">@page</a> import=“java.lang.ProcessBuilder.Redirect”%>

<%@ page import=java.util.List %>

<%@ page import=java.sql.Connection %>

<%@ page import=br.com.dao.<em>" %>

<%@ page import="br.com.bean.</em>” %>

<%@ page import=br.com.util.<em>" %>

<%<a class="mention" href="/u/page">@page</a> import="java.sql.</em>%>

<%<a class="mention" href="/u/page">@page</a> import=“<a href="http://java.io">java.io</a>.*”%>

<%<a class="mention" href="/u/page">@page</a> import=“java.sql.PreparedStatement”%>

<%@page import=“java.sql.Connection”%>
<%@page import=“org.apache.poi.hssf.usermodel.HSSFSheet”%>

<%<a class="mention" href="/u/page">@page</a> import=“org.apache.poi.hssf.usermodel.HSSFWorkbook”%>

<%<a class="mention" href="/u/page">@page</a> import=“org.apache.poi.hssf.usermodel.HSSFRow”%>

<%<a class="mention" href="/u/page">@page</a> import=“org.apache.poi.hssf.usermodel.HSSFCell”%>

<%<a class="mention" href="/u/page">@page</a> import=“org.apache.poi.hssf.usermodel.HSSFCell”%>

<%<a class="mention" href="/u/page">@page</a> import=“br.com.ConnectionFactory” %>

<%<a class="mention" href="/u/page">@page</a> import=“br.com.dao.JDBCChamadoDAO”%>

<%@include file=httpservletrequest.jsp %>

<%@ page import=<a href="http://java.io">java.io</a>.<em>,javax.servlet.</em>,javax.servlet.http.<em>"%>

<%<a class="mention" href="/u/page">@page</a> contentType=“text/html; charset=utf-8 language=java import="java.sql.</em>” errorPage="" %>

<%@include file=cabecalho.jsp %>

<%@include file=menus.jsp %>
<%

Connection connection=null;

connection = ConnectionFactory.getCoonection();

try {
String nomePlanilha = “planilhaTeste”;

HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet =  workbook.createSheet("Plan System "+nomePlanilha);  
// criando as linhas
HSSFRow rowhead =   sheet.createRow(0);
rowhead.createCell(0).setCellValue("Chamado");
rowhead.createCell(1).setCellValue("Analista");
rowhead.createCell(2).setCellValue("Data");
rowhead.createCell(3).setCellValue("Piloto");
rowhead.createCell(4).setCellValue("Sistema");
rowhead.createCell(5).setCellValue("Origem");
rowhead.createCell(6).setCellValue("ResolvidoN1");
rowhead.createCell(7).setCellValue("Redirecionado Para");
rowhead.createCell(8).setCellValue("Resolução Final");


String SQL = " SELECT * FROM chamado";
PreparedStatement ps = connection.prepareStatement(SQL);
ResultSet rs = (ResultSet) ps.executeQuery();

int i = 1;



while(rs.next()){
	HSSFRow row =   sheet.createRow(i);
	row.createCell(0).setCellValue(rs.getString("numChamado"));
    row.createCell(1).setCellValue(rs.getString("nomeAnalista"));
    row.createCell(2).setCellValue(rs.getString("data"));
    row.createCell(3).setCellValue(rs.getString("piloto"));
    row.createCell(4).setCellValue(rs.getString("sistema"));
    row.createCell(5).setCellValue(rs.getString("origem"));
    row.createCell(6).setCellValue(rs.getString("resolvidoN1"));
    row.createCell(7).setCellValue(rs.getString("redirecionadoPara"));
    row.createCell(8).setCellValue(rs.getString("resolucaoFinal"));
i++;
}


Date dataDeHoje = new Date();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");

String dataAtual = df.format(dataDeHoje);
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();

workbook.write(outByteStream);

byte [] outArray = outByteStream.toByteArray();
response.setContentType(application/octet-stream);

response.setContentLength(outArray.length);

response.setHeader(Expires:, 0); // eliminates browser caching

response.setHeader(Content-Disposition, attachment; filename=planilha+dataAtual+".xls");

OutputStream outStream = response.getOutputStream();

outStream.write(outArray);

outStream.flush();

outStream.close();

} catch (Exception e) {

throw new RuntimeException (e);

}

%>

<%@include file=“rodape.jsp”%>

Criado 12 de setembro de 2015
Ultima resposta 12 de set. de 2015
Respostas 1
Participantes 1