Simplificar método [RESOLVIDO]

11 respostas
P

Olá tudo bom?

Tenho esse método para gerar um arquivo excel, queria dar uma melhorada nele só que não sei como...

alguém poderia me dar um help? Eu fiz assim pq mudam direto o que mandam para montar o arquivo, então fiz campo a campo

public void CriarPlanilhaGeraRelatorio(String id_v_sp,
			String id_engine, String id_f_input, String id_ult_mensagem, String cod_dispositivo, String dt_hora_dispositivo, String grama, String login, HttpServletResponse response) throws Exception,
			IOException, BiffException, ClassNotFoundException, SQLException {

		// TÍTULO
		// Adicionando formato de fonte no título..."
		WritableFont bold0 = new WritableFont(WritableFont.ARIAL, 10,
				WritableFont.BOLD);
		bold0.setColour(Colour.WHITE);
		WritableCellFormat arial10fontVeic = new WritableCellFormat(bold0);
		arial10fontVeic.setBackground(Colour.GREEN);
		arial10fontVeic.setAlignment(Alignment.CENTRE);
		arial10fontVeic.setBorder(Border.ALL, BorderLineStyle.MEDIUM, Colour.WHITE);
		
		// SUBTÍTULOS
		// Adicionando formato de fonte no subtítulo..."
		WritableFont bold1 = new WritableFont(WritableFont.ARIAL, 10,
				WritableFont.BOLD);
		bold1.setColour(Colour.WHITE);
		WritableCellFormat arial10font = new WritableCellFormat(bold1);
		arial10font.setBackground(Colour.BLUE);
		arial10font.setAlignment(Alignment.CENTRE);
		arial10font.setBorder(Border.ALL, BorderLineStyle.MEDIUM, Colour.BLACK);

		// RESULTADO
		// Adicionando formato de fonte resultados..."
		WritableFont bold2 = new WritableFont(WritableFont.ARIAL, 10);
		WritableCellFormat arial10fontResult = new WritableCellFormat(bold2);
		arial10fontResult.setAlignment(Alignment.CENTRE);
		arial10fontResult.setBorder(Border.ALL, BorderLineStyle.THIN,
				Colour.BLACK);

		NomeArquivoExcel arquivoExcelRelatorio = new NomeArquivoExcel();
		File filename = arquivoExcelRelatorio.NomeExcelRelatorio(login);

		File filename2 = new File(filename.toString());

		if (!filename2.exists()) {

			// Instanciando a classe q gera o novo arquivo do Excel
			WritableWorkbook workbook = Workbook.createWorkbook(new File(
					filename.toString()));

			// Criando uma nova planilha
			WritableSheet sheet = workbook.createSheet("Resultado 0", 0);

			// TAMANHO DA COLUNA (col , tam)
			sheet.setColumnView(0, 16); 
			sheet.setColumnView(1, 15); 
			sheet.setColumnView(2, 19); 
			sheet.setColumnView(3, 19); 
			sheet.setColumnView(4, 14); 
			sheet.setColumnView(5, 19); 
			
			// MERGE col - lin to col - lin
			sheet.mergeCells(0, 0, 2, 0);
			 
			// col, lin
			Label labelTitulo = new Label(0, 0, "GRAMA: " + grama, arial10fontVeic);
			sheet.addCell(labelTitulo);
			
			Label labelTitulo0 = new Label(0, 2, "V inst", arial10font);
			sheet.addCell(labelTitulo0);

			Label labelTitulo1 = new Label(1, 2, "Rot.", arial10font);
			sheet.addCell(labelTitulo1);

			Label labelTitulo2 = new Label(2, 2, "Nvl", arial10font);
			sheet.addCell(labelTitulo2);

			Label labelTituloUltMsg = new Label(3, 2, "Última Mensagem", arial10font);
			sheet.addCell(labelTituloUltMsg);
			
			Label labelTituloDisp = new Label(4, 2, "Dispositivo", arial10font);
			sheet.addCell(labelTituloDisp);
			
			Label labelTituloDt = new Label(5, 2, "Data Dispositivo", arial10font);
			sheet.addCell(labelTituloDt);
			
			int i = sheet.getRows();

			// col, lin	
			Label label0 = new Label(0, i, id_v_sp, arial10fontResult);
			sheet.addCell(label0);

			Label label1 = new Label(1, i, id_engine, arial10fontResult);
			sheet.addCell(label1);

			Label label2 = new Label(2, i, id_f_input, arial10fontResult);
			sheet.addCell(label2);
			
			Label labelUltMsg = new Label(3, i, id_ult_mensagem, arial10fontResult);
			sheet.addCell(labelUltMsg);
			
			Label labelDisp = new Label(4, i, cod_dispositivo, arial10fontResult);
			sheet.addCell(labelDisp);
			
			Label labelDt = new Label(5, i, dt_hora_dispositivo, arial10fontResult);
			sheet.addCell(labelDt);

			// Escrevedo o arquivo em disco
			workbook.write();

			// Fechando a IO
			workbook.close();

		} else {

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

			WritableSheet sheet = wwb.getSheet(wwb.getNumberOfSheets() - 1);

			int i = sheet.getRows();

			int a = wwb.getNumberOfSheets();

			if (i > 29999) {
				sheet = wwb.createSheet("Resultado " + a, a + 1);
				sheet = wwb.getSheet(a);
				i = 1;

				// col, lin
				Label labelTitulo0 = new Label(0, 0, "V inst", arial10font);
				sheet.addCell(labelTitulo0);

				Label labelTitulo1 = new Label(1, 0, "Rot.", arial10font);
				sheet.addCell(labelTitulo1);

				Label labelTitulo2 = new Label(2, 0, "Nvl", arial10font);
				sheet.addCell(labelTitulo2);
				
				Label labelTituloUltMsg = new Label(3, 2, "Última Mensagem", arial10font);
				sheet.addCell(labelTituloUltMsg);
				
				Label labelTituloDisp = new Label(4, 2, "Dispositivo", arial10font);
				sheet.addCell(labelTituloDisp);
				
				Label labelTituloDt = new Label(5, 2, "Data Dispositivo", arial10font);
				sheet.addCell(labelTituloDt);

			}

			// col, lin
			Label label = new Label(0, i, id_v_sp, arial10fontResult);
			sheet.addCell(label);

			Label label1 = new Label(1, i, id_engine, arial10fontResult);
			sheet.addCell(label1);

			Label label2 = new Label(2, i, id_f_input, arial10fontResult);
			sheet.addCell(label2);

			Label labelUltMsg = new Label(3, i, id_ult_mensagem, arial10fontResult);
			sheet.addCell(labelUltMsg);
			
			Label labelDisp = new Label(4, i, cod_dispositivo, arial10fontResult);
			sheet.addCell(labelDisp);
			
			Label labelDt = new Label(5, i, dt_hora_dispositivo, arial10fontResult);
			sheet.addCell(labelDt);
			
			// Escrevedo o arquivo em disco
			wwb.write();

			// Fechando a IO
			wwb.close();

		}
	}

11 Respostas

E

então pacato
#nome de método inicia com letra minúscula
#não passe 35 parâmetros no seu método, passe um objeto
#nome de variável não é assim id_ult_mensagem com underline é idUltMensagem

as fontes( WritableFont bold0) coloque em uma classe e coloque como estático, dai vc pode usar em todos os relatórios q vc for montar somente chamando como método.

desenvolva um método padrão nessa classe q cria o cabeçalho do seu relatório, com frezze e “logo” se tiver, vc passará somente nome e tamanho da coluna, dai todos seus relatórios terão um padrão a não ser que vc não queira padrão.

só isso já facilitará sua vida nesse e nos próximos relatórios

P

Obrigado pelas dicas Edu…

vc só poderia me dar uma luz no tratamento do objeto?

Pois nele vem os resultados… estou pensando em passar um com os títulos tbm, assim ficaria melhor o que acha?

Rafael_Guerreiro

Apenas complementando o eduJava:
[list]Use métodos privados para separar comportamentos. Evite métodos com mais de 10 linhas.[/list]
[list]Use classes com comportamentos específicos, o ideal é você ter várias classes que fazem pouca coisa.[/list]

Por exemplo: Uma classe para salvar o excel em arquivo, outra para gerar o cabeçalho, etc.

P

Valeu Rafael pela dica também…

Vcs poderiam me dar uma luz em como eu trataria a lista de objetos(resultados)? pq não estou conseguindo ainda criar a lógica do for…

O do título eu fiz assim (abaixo) mas a do resultado que é uma lista de obj eu não sei ainda:

for (int i = 0; i < titulos.size(); i++) {
                Label label = new Label(i, 2, titulos.get(i), arial10font);
                sheet.addCell(label);
                sheet.setColumnView(i, 19);
            }

tentei fazer algo assim para o resultado, mas não consegui:

for (int i = 0; i < listaRes.size(); i++) {
            	for (int j = 0; j < titulos.size(); j++) {
                Label label = new Label(j, i, listaRes.get(i).toString(), format.cellResult());
                sheet.addCell(label);
            	}
            }
P

Não sei como tratar os objtes...

Carrego assim o retorno do banco:

while (rs.next()) {
				 Object[] obj = new Object[selecionado.size()+3]; // +3 por causa do campo mensagem, dispositivo e data
				 for(int i=0;i<selecionado.size();i++){
					 obj[i] = rs.getObject(new Integer(i+1))+"";
					 obj[i+1] = rs.getObject("id_ult_mensagem")+""; // obj[i+1] para pegar a coluna última mensagem
					 obj[i+2] = rs.getObject("cod_dispositivo")+""; // obj[i+2] para pegar a coluna cod do dispositivo
					 obj[i+3] = rs.getObject("dt_hora_dispositivo")+""; // obj[i+3] para pegar a coluna data do dispositivo
				 }
				 
				 listaRes.add(obj);
				 criarExcel.criarPlanilhaGeraRelatorioTeste(titulos, listaRes, grama, login, null); // CHAMO A CLASSE PARA CRIAR O ARQUIVO 
				
			}

Só vem a posição da memória, não consigo converter em string....

Tentei ler assim também e nada:

int rows = sheet.getRows();
            
          
            	for (int j = 0; j < titulos.size(); j++) {
            		for (int i = 0; i < listaRes.size(); i++) {

            			Label label = new Label(j, rows, listaRes.get(i).toString(), format.cellResult()); //.toString não funciona aqui
            			sheet.addCell(label);
            			
            			System.out.println("1= linha:"+rows + " coluna:" + j);
            			
            		}
            		rows = rows +1;
            		System.out.println("2= linha:"+rows + " coluna:" + j);
            	}
E


dentro do listaRes vc colocou um Object[]
então pra chamar listaRes.get(i)[aPosicaoDoObjecto]

vc tem q usar mais o debug
com ele vc veria esse erro na hora

P

Foi mal edu… não manjo muito trabalhar com listas… na verdade programação não é meu forte… acho que percebeu né?

Valeu pela força… e me desculpe mais uma vez…

Mudei o jeito de pegar no BD para lista de String (List ) :

while (rs.next()) {
				 for(int i=0;i<selecionado.size();i++){
					 listaRes.add(rs.getString(new Integer(i+1))+"");
					 
				 }
				 listaRes.add(rs.getString("id_ult_mensagem")+""); // para pegar a coluna última mensagem
				 listaRes.add(rs.getString("cod_dispositivo")+""); // para pegar a coluna cod do dispositivo
				 listaRes.add(rs.getString("dt_hora_dispositivo")+""); // para pegar a coluna data do dispositivo
								 
				
			}
			criarExcel.criarPlanilhaGeraRelatorioTeste(titulos, listaRes, grama, login, null);

Pois o outro jeito estava se perdendo quando tentava imprimir o vetor…

Mas o resultado agora está vindo, porem ainda estou vendo como ordenar corretamente, o resultado do retorno é:

1= linha:793 coluna:0
Valor: QAG0035667
1= linha:793 coluna:1
Valor: QAG0035667
1= linha:793 coluna:2
Valor: QAG0035667
1= linha:793 coluna:3
Valor: QAG0035667
1= linha:793 coluna:4
Valor: QAG0035667
1= linha:793 coluna:5
Valor: QAG0035667
1= linha:794 coluna:0
Valor: 24/09/2014 08:16:02
1= linha:794 coluna:1
Valor: 24/09/2014 08:16:02
1= linha:794 coluna:2
Valor: 24/09/2014 08:16:02
1= linha:794 coluna:3
Valor: 24/09/2014 08:16:02
1= linha:794 coluna:4
Valor: 24/09/2014 08:16:02
1= linha:794 coluna:5
Valor: 24/09/2014 08:16:02

ele repete nas 6 linhas das 6 colunas o valor que deveria ser em uma linha…

int rows = sheet.getRows();
            
          
           	
            		for (int i = 0; i < listaRes.size(); i++) { // LINHAS
            			for (int j = 0; j < titulos.size(); j++) { // COLUNAS
            				System.out.println("Valor: " + listaRes.get(i));	
            				
j = Coluna e Rows = Linha 
            				Label label = new Label(j, rows, (String) listaRes.get(i), format.cellResult()); //AQUI
            				sheet.addCell(label);
            			
            				System.out.println("1= linha:"+rows + " coluna:" + j);
            		
            			
            		}
            			rows = rows +1;
    
            	}
P

Consegui ordenar… mas agora ele não termina todos os registros… :frowning:

int z = 0; int j = 0; for (int i = 0; i < listaRes.size(); i++) { System.out.println("Size: " + listaRes.size()); System.out.println("1= linha:"+rows + " coluna:" + j); System.out.println("Valor: " + listaRes.get(z)); if (j < titulos.size()){ Label label = new Label(j, rows, listaRes.get(z), format.cellResult()); sheet.addCell(label); z++; j++; } else { j = 0; rows = rows +1; } }

Para no registro 679, e no size tem 792… não sei pq sai do for

ViniGodoy

Você também não é obrigado a criar uma variável local se não for usa-la várias vezes.
Linhas como essa:

Label labelTitulo1 = new Label(1, 2, "Rot.", arial10font); sheet.addCell(labelTitulo1);
Podem virar somente:

sheet.addCell(new Label(1, 2, "Rot.", arial10font);  );
P

Obrigado Vini… farei essa atualização tbm…

agora estou enroscado no retorno do resultado…

Não consegui entender pq está saindo do for…

P

Consegui:

Ainad vou dar mais algumas simplificadas, mas já ficou 100% perto do que estava.. a parte que eu estava com dificuldade fiz essa lógica:

// CRIA LINHAS DE RESULTADOS
            int rows = sheet.getRows(); // Número da linha no Excel       
            int z = 0; // Posição da lista de resultado
            for (int i = 0; i < listaRes.size(); i++) { // Varrer a lista de resultado por tamanho
            	
            	for (int j=0; j < titulos.size(); j++){ // varrear a lista de títulos para pegar valor da coluna
           		
            		sheet.addCell(new Label(j, rows, listaRes.get(z), format.cellResult())); // add linha no excel
       				z++; // soma uma posição da lista
    			} 
            	i = z-1; // add no índice da lista o valor anterior porque o z foi somado uma posição a mais;
            	rows = rows +1; // pula uma linha no arquivo excel
            }

Código completo:

public void criarPlanilhaGeraRelatorioTeste(List<String> titulos, List<String> listaRes, String grama, String login, HttpServletResponse response) throws Exception,
			IOException, BiffException, ClassNotFoundException, SQLException {
		
		NomeArquivoExcel arquivoExcelRelatorio = new NomeArquivoExcel();
		File filename = arquivoExcelRelatorio.NomeExcelRelatorio(login);

		File filename2 = new File(filename.toString());

		if (!filename2.exists()) {
			
			FormatCell format = new FormatCell();

			// Instanciando a classe q gera o novo arquivo do Excel
			WritableWorkbook workbook = Workbook.createWorkbook(new File(
					filename.toString()));

			// Criando uma nova planilha
			WritableSheet sheet = workbook.createSheet("Resultado 0", 0);
						
			// MERGE col - lin to col - lin PARA O TÍTULO PRINCIPAL grama
			sheet.mergeCells(0, 0, 2, 0);
			
			// col, lin PARA O TÍTULO PRINCIPAL grama
			sheet.addCell(new Label(0, 0, "grama: " + grama, format.cellVeic()));
			
            // CRIA TÍTULOS
            for (int i = 0; i < titulos.size(); i++) {
            	sheet.addCell(new Label(i, 2, titulos.get(i), format.cellTitle()));
                sheet.setColumnView(i, 19); // seta largura da coluna i
            }

            // CRIA LINHAS DE RESULTADOS
            int rows = sheet.getRows(); // Número da linha no Excel       
            int z = 0; // Posição da lista de resultado
            for (int i = 0; i < listaRes.size(); i++) { // Varrer a lista de resultado por tamanho
            	
            	for (int j=0; j < titulos.size(); j++){ // varrear a lista de títulos para pegar valor da coluna
           		
            		sheet.addCell(new Label(j, rows, listaRes.get(z), format.cellResult())); // add linha no excel
       				z++; // soma uma posição da lista
    			} 
            	i = z-1; // add no índice da lista o valor anterior porque o z foi somado uma posição a mais;
            	rows = rows +1; // pula uma linha no arquivo excel
            }
          
            
			// Escrevedo o arquivo em disco
			workbook.write();

			// Fechando a IO
			workbook.close();

		} else {
			filename2.delete();
			filename2.deleteOnExit();
		}
	}
Criado 29 de setembro de 2014
Ultima resposta 6 de out. de 2014
Respostas 11
Participantes 4