Criar(gerar) Excel com Jexcel [RESOLVIDO]

Pessoal, estou tentando criar uma planilha em excel com a api JXL.

É o seguinte, recebo uma planilha, com alguns valores para fazer a consulta no bd, até aqui ok, ta feito.

Depois pego os resultados das consultas, e quero gravar no excel… só que tenho que criar o arquivo, e dependendo do valor, ele muda de método para ir buscar os resultados…

Ou seja, tenho que ficar gravando no mesmo arquivo até terminar os dados de entrada…

A dúvida é…

Não sei como fazer a lógica para isso, ficar gravando no excel os parametros em linhas e colunas enquanto estiver resultados, e se já tiver gravado algo, começar da linha que parou em diante… pois assim fica reescrevendo e deixando só o último registro…

[code]
package br.com.simcard;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class CriarExcel {   
  
    /*public static void main(String[] args) {   
        try{   
            CriarPlanilha();   
            System.out.println("Planilha escrita com sucesso");   
        } catch (NullPointerException npe){   
            npe.printStackTrace();   
        } catch (IOException ioe){   
            ioe.printStackTrace();   
        } catch (RowsExceededException ree){   
            ree.printStackTrace();   
        } catch (WriteException we){   
            we.printStackTrace();   
        }   
    }*/   

	
    public void CriarPlanilhaColetiva(String dispositivo, String codTecnologia, String apnConfigurada, String simCard,
    		String linha, String operadora, String apnProvisionada, String statusSIMCard, String fonte, String imei,
    		String imsi, String statusLinha, String consDados, String matricula) throws IOException, RowsExceededException, WriteException{   
           
       
    	GregorianCalendar calendar = new GregorianCalendar();   
        SimpleDateFormat formatador = new SimpleDateFormat("dd' de 'MMMMM' de 'yyyy' - 'HH'h'mm'min'ss's'");     
        System.out.println(formatador.format(calendar.getTime()));   
           
        String filename = "C://Consulta_Coletiva - "+formatador.format(calendar.getTime())+".xls"; 
    	
    	//Instanciando a classe q gera o novo arquivo do Excel   
        WritableWorkbook workbook = Workbook.createWorkbook(new File(filename));   
           
        //Criando uma nova planilha   
        WritableSheet sheet = workbook.createSheet("First Sheet", 0);   
        
    	//col, lin
        Label labelTitulo = new Label(0, 0, "Dispositivo");   
        sheet.addCell(labelTitulo);
        
        Label labelTitulo1 = new Label(1, 0, "SIMCard");   
        sheet.addCell(labelTitulo1);
        
        Label labelTitulo2 = new Label(2, 0, "Linha");   
        sheet.addCell(labelTitulo2);
        
        Label labelTitulo3 = new Label(3, 0, "Tecnologia");   
        sheet.addCell(labelTitulo3);
        
        Label labelTitulo4 = new Label(4, 0, "APN Configurada");   
        sheet.addCell(labelTitulo4);
        
        Label labelTitulo5 = new Label(5, 0, "Operadora");   
        sheet.addCell(labelTitulo5);
        
        Label labelTitulo6 = new Label(6, 0, "APN Provisionada");   
        sheet.addCell(labelTitulo6);
        
        Label labelTitulo7 = new Label(7, 0, "Status SIMCard");   
        sheet.addCell(labelTitulo7);
        
        Label labelTitulo8 = new Label(8, 0, "Fonte");   
        sheet.addCell(labelTitulo8);
        
        Label labelTitulo9 = new Label(9, 0, "IMEI");   
        sheet.addCell(labelTitulo9);
        
        Label labelTitulo10 = new Label(10, 0, "IMSI");   
        sheet.addCell(labelTitulo10);
        
        Label labelTitulo11 = new Label(11, 0, "Status Linha");   
        sheet.addCell(labelTitulo11);
        
        Label labelTitulo12 = new Label(12, 0, "Consumo de Dados");   
        sheet.addCell(labelTitulo12);
        
        Label labelTitulo13 = new Label(13, 0, "Matricula");   
        sheet.addCell(labelTitulo13);
        
        for(int i=1; i <= 7; i++){ // NÃO SEI QUE CONDIÇÃO USO PARA FICAR NO LOOP
        
    	//col, lin
        Label label = new Label(0, i, dispositivo);   
        sheet.addCell(label);
        
        Label label1 = new Label(1, i, simCard);   
        sheet.addCell(label1);
        
        Label label2 = new Label(2, i, linha);   
        sheet.addCell(label2);
        
        Label label3 = new Label(3, i, codTecnologia);   
        sheet.addCell(label3);
        
        Label label4 = new Label(4, i, apnConfigurada);   
        sheet.addCell(label4);
        
        Label label5 = new Label(5, i, operadora);   
        sheet.addCell(label5);
        
        Label label6 = new Label(6, i, apnProvisionada);   
        sheet.addCell(label6);
        
        Label label7 = new Label(7, i, statusSIMCard);   
        sheet.addCell(label7);
        
        Label label8 = new Label(8, i, fonte);   
        sheet.addCell(label8);
        
        Label label9 = new Label(9, i, imei);   
        sheet.addCell(label9);
        
        Label label10 = new Label(10, i, imsi);   
        sheet.addCell(label10);
        
        Label label11 = new Label(11, i, statusLinha);   
        sheet.addCell(label11);
        
        Label label12 = new Label(12, i, consDados);   
        sheet.addCell(label12);
        
        Label label13 = new Label(13, i, matricula);   
        sheet.addCell(label13);
        
        }
        
        // adicionando uma celula no formato de texto   
        /*Label label = new Label(0, 2, "A label record");   
        sheet.addCell(label);*/   
  
        // adicionando uma celula no formato de texto   
        /*jxl.write.Number number = new jxl.write.Number(3, 4, 3.1459);   
        sheet.addCell(number);*/   
           
        // Escrevedo o arquivo em disco   
        workbook.write();   
           
        // Fechando a IO   
        workbook.close();   
  
    }   
}  


  
    }   [/code]

Ninguem??

eu só quero saber como deixar um loop para passar todas as linhas, e não ficar sobreescrevendo por cima

Olá Pacato tudo bem?
Eu tenho esse código(abaixo) que desenvolvi, não sei se é isso o que você procura, mas espero que ajude.

    private static void writeDataSheet(WritableSheet s, Usuario lista1[], int lin)
    throws WriteException
    {
        /* Fonte em negrito */
        WritableFont wf = new WritableFont(WritableFont.ARIAL, 
        10, WritableFont.BOLD);
        WritableCellFormat cf = new WritableCellFormat(wf);
        cf.setWrap(true);
        //Fonte normal
        WritableFont wf2 = new WritableFont(WritableFont.ARIAL, 
        10, WritableFont.NO_BOLD);
        WritableCellFormat cf2 = new WritableCellFormat(wf2);
        cf2.setWrap(true);
        WritableCellFormat cf3 = new WritableCellFormat(NumberFormats.INTEGER);
        cf2.setWrap(true);
        /* Cria um label e escreve o conteúdo na primeira linha da coluna*/
        Label c = new Label(0,0,lista1[0].gs,cf);
        s.addCell(c);
        Label c2 = new Label(1,0,lista1[0].nome,cf);
        s.addCell(c2);
        Label c3 = new Label(2,0,lista1[0].cc,cf);
        s.addCell(c3);
        Label c4 = new Label(3,0,lista1[0].responsavel,cf);
        s.addCell(c4);
        for (int i = 1; i < lin-Plan.plan; i++) {
            Label c5 = new Label(0,i,lista1[i+Plan.plan].gs,cf2);
            s.addCell(c5);
            Label c6 = new Label(1,i,lista1[i+Plan.plan].nome,cf2);
            s.addCell(c6);
            jxl.write.Number c7 = new jxl.write.Number(2,i,lista1[i+Plan.plan].cc,cf3);
            s.addCell(c7);
            Label c8 = new Label(3,i,lista1[i+Plan.plan].responsavel,cf2);
            s.addCell(c8);
            if (i!=((lin-1)-Plan.plan)) {
                if (!lista1[i+Plan.plan].responsavel.equals(lista1[(i+Plan.plan)+1].responsavel)) {
                    Plan.plan += i;
                    break;
                }
            }
        }
    }

O “Plan” eu pego de uma classe que eu criei, e uso ele como referencia para indicar o ultimo índice de onde a folha(ou arquivo) Excel parou, para continuar continuar a sequencia na próxima folha.

Não sei se é isso que você procura, mas espero que ajude. :thumbup:

Abraço.

é praticamente isso…

vou fazer uns testes durante o dia…

Valeu mesmo xandelol

Abs

Estamos aí para isso, qualquer coisa só chamar que eu tento ajudar!

Abs.

Valeu mesmo… to perdido com a lógica disso… agora deu uma clariada… qualquer coisa volto a postar (positiva ou negativamente)

Vc por um acaso saberia me dizer como faço para escrever no mesmo arquivo caso ele já exista no diretório??

Nesse caso você poderia usar uma condição IF, analisando se tem ou não um arquivo no diretório…Se existir, você lê o arquivo, pega os dados que você quer, salva em variáveis, depois manda escrever os dados antigos junto com os novos, usando o mesmo nome de arquivo e diretório.
Vê se é isso mais ou menos que você quer.

é isso… só que não sei como fazer, não sei a instrução (códgio) para isso

Bom…você já sabe como faz para ler um arquivo excel? Caso não segue o código abaixo.

boolean naoexiste=false;
try {
            //FileInputStream file = new FileInputStream("Teste 2010.xlsx");
             File file = new File("caminho");
             String name = file.toString();
             int pos = name.lastIndexOf('.');
             String ext = name.substring(pos + 1);
             FileInputStream fileIn = new FileInputStream(file);
             Workbook obj = null;
             if (ext.equals("xlsx")) {
                try {
                    //Metodo aceita o path do arquivo
                    obj = new XSSFWorkbook(fileIn);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
             } else if (ext.equals("xls")) {
                try {
                    //Metodo nao aceita string do path do arquivo
                    obj = new HSSFWorkbook(fileIn);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
             }
             else
             {
                 throw new IllegalArgumentException("Received file does not have a standard excel extension.");
             }
             int o = 0;
            Sheet worksheet = obj.getSheet("Plan1");
            Row row;
            Cell cell;
            for(int i=0;i<=worksheet.getLastRowNum();i++){
                row = worksheet.getRow(i);
                String linha = "";
                for(int j =0;j<2;j++){
                    cell = row.getCell(j);
 
                   if(cell.getCellType()==1)
                    linha += " | "+ cell.getStringCellValue();
                   else{
                       double aux = 0;
                       int aux2 =0;
                       aux = cell.getNumericCellValue();
                       aux2 = (int) aux;
                       linha += " | " + aux2;
                   }
               }
                
                System.out.println(linha);
            }  

        } catch (FileNotFoundException ex) {
            naoexiste=true;
            System.out.println("Arquivo não encontrado");
        }

Você pode criar uma variável boolean naoexiste(exemplo) iniciada com false, caso o arquivo não exista, naoexiste fica igual a true, e cria um arquivo novo(usando o código que você já criou). Se o arquivo existir, naoexiste continua false, e com dos dados que você pegou na hora de ler, junta com os dados novos, e cria um arquivo de mesmo nome e caminho.

A parte da condição blz… uso o “.exist()”

Só que em:

	        String filename = "C://Consulta_Coletiva - "+formatador.format(calendar.getTime())+".xls"; 
	    	
	        
	    	//Instanciando a classe q gera o novo arquivo do Excel   
	        WritableWorkbook workbook = Workbook.createWorkbook(new File(filename));   
	           
	        //Criando uma nova planilha   
	        WritableSheet sheet = workbook.createSheet("First Sheet", 0);   

Só que esse “create” esta me dando dor de cabeça… pois se uso o get, da erro em tudo… pq to usando esse Writetable

Vish ai complicou! :shock:

Consegui…

é só chamar com o get, e depois passar o create de novo… Copiarei o método inteiro para caso alguem for ver

 public void CriarPlanilhaColetiva(String dispositivo, String codTecnologia, String apnConfigurada, String simCard,
	    		String linha, String operadora, String apnProvisionada, String statusSIMCard, String fonte, String imei,
	    		String imsi, String statusLinha, String consDados, String matricula) throws IOException, RowsExceededException, WriteException, BiffException{   
	        
	    	//FORMATANDO FONTE
	    	// Adicionando formato de fonte... se adicionar ", true" depois de bold adiciona Italico	    	
	    	WritableFont bold = new WritableFont(WritableFont.ARIAL,                 
	    	10, WritableFont.BOLD);         
	    	bold.setColour(Colour.WHITE);         
	    	WritableCellFormat arial10font = new WritableCellFormat(bold);         
	    	arial10font.setBackground(Colour.BLUE);         
	    	arial10font.setAlignment(Alignment.CENTRE);         
	    	arial10font.setBorder(Border.ALL,BorderLineStyle.MEDIUM,Colour.BLACK); 

	    	
	    	//ADICIONA DATA/HORA NO ARQUIVO GERADO
	    	GregorianCalendar calendar = new GregorianCalendar();   
	        SimpleDateFormat formatador = new SimpleDateFormat("dd' de 'MMMMM' de 'yyyy");     
	        System.out.println(formatador.format(calendar.getTime()));   
	           
	        String filename = "C://Consulta_Coletiva - "+formatador.format(calendar.getTime())+".xls"; 
	    	File filename2 = new File(filename);
	        
	    	if (!filename2.exists()){
	    	
	    	//Instanciando a classe q gera o novo arquivo do Excel   
	        WritableWorkbook workbook = Workbook.createWorkbook(new File(filename));   
	           
	        //Criando uma nova planilha   
	        WritableSheet sheet = workbook.createSheet("First Sheet", 0);
	        
	        
        	//col, lin
	        Label labelTitulo0 = new Label(0, 0, "Dispositivo", arial10font);   
	        sheet.addCell(labelTitulo0);
	        
	        Label labelTitulo1 = new Label(1, 0, "SIMCard", arial10font);   
	        sheet.addCell(labelTitulo1);
	        
	        Label labelTitulo2 = new Label(2, 0, "Linha", arial10font);   
	        sheet.addCell(labelTitulo2);
	        
	        Label labelTitulo3 = new Label(3, 0, "Tecnologia", arial10font);   
	        sheet.addCell(labelTitulo3);
	        
	        Label labelTitulo4 = new Label(4, 0, "APN Configurada", arial10font);   
	        sheet.addCell(labelTitulo4);
	        
	        Label labelTitulo5 = new Label(5, 0, "Operadora", arial10font);   
	        sheet.addCell(labelTitulo5);
	        
	        Label labelTitulo6 = new Label(6, 0, "APN Provisionada", arial10font);   
	        sheet.addCell(labelTitulo6);
	        
	        Label labelTitulo7 = new Label(7, 0, "Status SIMCard", arial10font);   
	        sheet.addCell(labelTitulo7);
	        
	        Label labelTitulo8 = new Label(8, 0, "Fonte", arial10font);   
	        sheet.addCell(labelTitulo8);
	        
	        Label labelTitulo9 = new Label(9, 0, "IMEI", arial10font);   
	        sheet.addCell(labelTitulo9);
	        
	        Label labelTitulo10 = new Label(10, 0, "IMSI", arial10font);   
	        sheet.addCell(labelTitulo10);
	        
	        Label labelTitulo11 = new Label(11, 0, "Status Linha", arial10font);   
	        sheet.addCell(labelTitulo11);
	        
	        Label labelTitulo12 = new Label(12, 0, "Consumo de Dados", arial10font);   
	        sheet.addCell(labelTitulo12);
	        
	        Label labelTitulo13 = new Label(13, 0, "Matricula", arial10font);   
	        sheet.addCell(labelTitulo13);
	        
	        int i = sheet.getRows() + 1;
	        
        	//col, lin
	        Label label = new Label(0, i, dispositivo);   
	        sheet.addCell(label);
	        
	        Label label1 = new Label(1, i, simCard);   
	        sheet.addCell(label1);
	        
	        Label label2 = new Label(2, i, linha);   
	        sheet.addCell(label2);
	        
	        Label label3 = new Label(3, i, codTecnologia);   
	        sheet.addCell(label3);
	        
	        Label label4 = new Label(4, i, apnConfigurada);   
	        sheet.addCell(label4);
	        
	        Label label5 = new Label(5, i, operadora);   
	        sheet.addCell(label5);
	        
	        Label label6 = new Label(6, i, apnProvisionada);   
	        sheet.addCell(label6);
	        
	        Label label7 = new Label(7, i, statusSIMCard);   
	        sheet.addCell(label7);
	        
	        Label label8 = new Label(8, i, fonte);   
	        sheet.addCell(label8);
	        
	        Label label9 = new Label(9, i, imei);   
	        sheet.addCell(label9);
	        
	        Label label10 = new Label(10, i, imsi);   
	        sheet.addCell(label10);
	        
	        Label label11 = new Label(11, i, statusLinha);   
	        sheet.addCell(label11);
	        
	        Label label12 = new Label(12, i, consDados);   
	        sheet.addCell(label12);
	        
	        Label label13 = new Label(13, i, matricula);   
	        sheet.addCell(label13);
	        
	        
	        // adicionando uma celula no formato de texto   
	        /*Label label = new Label(0, 2, "A label record");   
	        sheet.addCell(label);*/   
	  
	        // adicionando uma celula no formato de texto   
	        /*jxl.write.Number number = new jxl.write.Number(3, 4, 3.1459);   
	        sheet.addCell(number);*/   
	           
	        // Escrevedo o arquivo em disco   
	        workbook.write();   
	           
	        // Fechando a IO   
	        workbook.close();   
	    	
	    	} else {
	    		// AQUI EU CHAMO O JÁ CRIADO E "CRIO" EM CIMA DO MESMO

	    		Workbook rw = Workbook.getWorkbook (new File (filename2.toString())); 
	    		WritableWorkbook wwb = Workbook.createWorkbook (new File (filename2.toString()), rw);    
		        
	    		
	    		WritableSheet sheet = wwb.getSheet (0); 

	    		
	    		int i = sheet.getRows() + 1;
		        
	        	//col, lin
		        Label label = new Label(0, i, dispositivo);   
		        sheet.addCell(label);
		        
		        Label label1 = new Label(1, i, simCard);   
		        sheet.addCell(label1);
		        
		        Label label2 = new Label(2, i, linha);   
		        sheet.addCell(label2);
		        
		        Label label3 = new Label(3, i, codTecnologia);   
		        sheet.addCell(label3);
		        
		        Label label4 = new Label(4, i, apnConfigurada);   
		        sheet.addCell(label4);
		        
		        Label label5 = new Label(5, i, operadora);   
		        sheet.addCell(label5);
		        
		        Label label6 = new Label(6, i, apnProvisionada);   
		        sheet.addCell(label6);
		        
		        Label label7 = new Label(7, i, statusSIMCard);   
		        sheet.addCell(label7);
		        
		        Label label8 = new Label(8, i, fonte);   
		        sheet.addCell(label8);
		        
		        Label label9 = new Label(9, i, imei);   
		        sheet.addCell(label9);
		        
		        Label label10 = new Label(10, i, imsi);   
		        sheet.addCell(label10);
		        
		        Label label11 = new Label(11, i, statusLinha);   
		        sheet.addCell(label11);
		        
		        Label label12 = new Label(12, i, consDados);   
		        sheet.addCell(label12);
		        
		        Label label13 = new Label(13, i, matricula);   
		        sheet.addCell(label13);
		        
		        
		        // adicionando uma celula no formato de texto   
		        /*Label label = new Label(0, 2, "A label record");   
		        sheet.addCell(label);*/   
		  
		        // adicionando uma celula no formato de texto   
		        /*jxl.write.Number number = new jxl.write.Number(3, 4, 3.1459);   
		        sheet.addCell(number);*/   
		           
		        // Escrevedo o arquivo em disco   
		        wwb.write();   
		           
		        // Fechando a IO   
		        wwb.close();
	    		
	    	}
	    	
	    }   
	    
	}