Subversion Repositories Integrator Subversion

Rev

Rev 195 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
106 espaco 1
package br.com.ec.controller.util;
2
 
3
import java.io.ByteArrayOutputStream;
4
import java.io.File;
5
import java.io.FileInputStream;
6
import java.io.FileNotFoundException;
7
import java.io.FileOutputStream;
8
import java.io.IOException;
9
import java.util.ArrayList;
10
import java.util.HashSet;
11
import java.util.Iterator;
12
import java.util.List;
13
 
14
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
15
import org.apache.poi.hssf.usermodel.HSSFSheet;
16
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
17
import org.apache.poi.ss.usermodel.Cell;
18
import org.apache.poi.ss.usermodel.CellStyle;
19
import org.apache.poi.ss.usermodel.FillPatternType;
20
import org.apache.poi.ss.usermodel.HorizontalAlignment;
21
import org.apache.poi.ss.usermodel.IndexedColors;
22
import org.apache.poi.ss.usermodel.Row;
23
import org.apache.poi.ss.usermodel.VerticalAlignment;
24
 
25
import com.itextpdf.text.Document;
26
import com.itextpdf.text.pdf.PdfCopy;
27
import com.itextpdf.text.pdf.PdfImportedPage;
28
import com.itextpdf.text.pdf.PdfReader;
29
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
30
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
31
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
32
 
195 espaco 33
import br.com.ec.core.util.StringUtil;
34
import br.com.ec.core.util.VerificadorUtil;
106 espaco 35
import br.com.ec.domain.model.Avaliacao;
36
import br.com.ec.domain.model.AvaliacaoFuncionario;
37
import br.com.ec.domain.model.Funcionario;
38
import br.com.ec.domain.model.Pessoa;
39
import br.com.ec.domain.model.Vigencia;
40
 
41
public class ExcelUtil {
42
 
43
        public static HSSFSheet criarAbas(HSSFWorkbook workbook, String nomeAba) {
44
                 HSSFSheet aba = workbook.createSheet(nomeAba);
45
                 return aba;
46
        }
47
 
48
        public static void definirPadraoAba(HSSFSheet aba, Integer larguraColunas, short alturaLinhas) {
49
                aba.setDefaultColumnWidth(larguraColunas);//15
50
                aba.setDefaultRowHeight((short)alturaLinhas);//400
51
        }
52
 
53
        public static CellStyle configurarCelulaCabecalho(HSSFWorkbook workbook) {
54
                CellStyle headerStyle = workbook.createCellStyle();
55
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
56
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
57
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
58
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
59
        return headerStyle;
60
        }
61
 
62
        public static CellStyle configurarCelulaTexto(HSSFWorkbook workbook) {
63
                CellStyle textStyle = workbook.createCellStyle();
64
                textStyle.setAlignment(HorizontalAlignment.CENTER);
65
        textStyle.setVerticalAlignment(VerticalAlignment.CENTER);
66
        return textStyle;
67
        }
68
 
69
        public static CellStyle configurarCelulaNumerico(HSSFWorkbook workbook) {
70
                CellStyle numberStyle = workbook.createCellStyle();
71
        //Configurando estilos de células (Cores, alinhamento, formatação, etc..)
72
        HSSFDataFormat numberFormat = workbook.createDataFormat();
73
        numberStyle.setDataFormat(numberFormat.getFormat("#,##0.00"));
74
        numberStyle.setVerticalAlignment(VerticalAlignment.CENTER);
75
        return numberStyle;
76
        }
77
 
78
        public static void configurarCabecalho(HSSFWorkbook workbook, HSSFSheet aba) {
79
                CellStyle headerStyle = configurarCelulaCabecalho(workbook);
80
        Row linha = aba.createRow(0);
81
        criarCelula(workbook, aba, linha, 0, headerStyle, "CÓDIGO");
82
//        criarCelula(workbook, aba, linha, 1, headerStyle, "NOME");
83
//        criarCelula(workbook, aba, linha, 2, headerStyle, "PREÇO");
84
        }
85
 
86
        public static void criarCelula(HSSFWorkbook workbook, HSSFSheet aba, Row linha, Integer posicaoColuna, CellStyle estilo, String valor) {
87
        Cell celula = linha.createCell(posicaoColuna);
88
        if (VerificadorUtil.naoEstaNulo(estilo)) {
89
                celula.setCellStyle(estilo);
90
        }
91
        celula.setCellValue(valor);
92
        }
93
 
441 espaco 94
        public static void main(String[] args) throws IOException {
106 espaco 95
        HSSFWorkbook wb = new HSSFWorkbook();
96
 
97
        // ABAS
441 espaco 98
        HSSFSheet aba1 = criarAbas(wb, "lista funcionários para pagamen");
99
 
100
        Row linha = aba1.createRow(0);
101
        criarCelula(wb, aba1, linha, 0, configurarCelulaTexto(wb), "1465");
102
        criarCelula(wb, aba1, linha, 1, configurarCelulaTexto(wb), "84044");
103
        criarCelula(wb, aba1, linha, 2, configurarCelulaTexto(wb), "3");
104
        criarCelula(wb, aba1, linha, 3, configurarCelulaNumerico(wb), "Adalberto Soares Brito Neto");
105
        criarCelula(wb, aba1, linha, 4, configurarCelulaTexto(wb), "074.713.574-60");
106
        criarCelula(wb, aba1, linha, 5, configurarCelulaTexto(wb), "1");
107
        criarCelula(wb, aba1, linha, 6, configurarCelulaTexto(wb), "2306,98");
108
 
109
        try {
110
                FileOutputStream stream = new FileOutputStream("d:/planilhaaa.xls");
111
                wb.write(stream);
112
                stream.close();
113
                wb.close();
114
                System.out.println("Success!!");
115
        } catch (FileNotFoundException e) {
116
                e.printStackTrace();
117
        } catch (IOException e) {
118
                e.printStackTrace();
119
        }
120
        }
121
 
122
        public static void main33(String[] args) throws IOException {
123
        HSSFWorkbook wb = new HSSFWorkbook();
124
 
125
        // ABAS
106 espaco 126
        HSSFSheet aba1 = criarAbas(wb, "Planilha 1");
127
        criarAbas(wb, "Planilha 2");
128
        criarAbas(wb, "Planilha 3");
129
 
130
        configurarCabecalho(wb, aba1);
131
 
132
        Row linha = aba1.createRow(1);
133
        criarCelula(wb, aba1, linha, 0, configurarCelulaTexto(wb), "1");
134
        criarCelula(wb, aba1, linha, 1, configurarCelulaTexto(wb), "TESTE");
135
        criarCelula(wb, aba1, linha, 2, configurarCelulaNumerico(wb), "10");
136
 
137
        try {
441 espaco 138
                FileOutputStream stream = new FileOutputStream("d:/planilhaaa.xls");
106 espaco 139
                wb.write(stream);
140
                stream.close();
141
                wb.close();
142
                System.out.println("Success!!");
143
        } catch (FileNotFoundException e) {
144
                e.printStackTrace();
145
        } catch (IOException e) {
146
                e.printStackTrace();
147
        }
148
        }
149
 
150
        public static void main3(String[] args) throws IOException {
151
                String filePath = "d:/planilha.xls";
152
                try{
153
                // Abrindo o arquivo e recuperando a planilha
154
                FileInputStream file = new FileInputStream(new File(filePath));
155
                HSSFWorkbook workbook = new HSSFWorkbook(file);
156
                HSSFSheet sheet = workbook.getSheetAt(0);
157
 
158
                List products = new ArrayList();
159
 
160
                Iterator rowIterator = sheet.rowIterator();
161
                while (rowIterator.hasNext()) {
162
                        Row row = (Row) rowIterator.next();
163
 
164
                        // Descantando a primeira linha com o header
165
                        if(row.getRowNum() == 0){
166
                                continue;
167
                        }
168
 
169
                        Iterator cellIterator = row.cellIterator();
170
        //              Product product = new Product();
171
        //              products.add(product);
172
                        while (cellIterator.hasNext()) {
173
                                Cell cell = (Cell) cellIterator.next();
174
                                switch (cell.getColumnIndex()) {
175
                                        case 0:
176
                        //              product.setId(((Double)cell.getNumericCellValue()).longValue());
177
                                                cell.setCellValue("2");// Substituindo valores
178
                                        System.out.println(cell.getStringCellValue());
179
                                        break;
180
                                        case 1:
181
                                                System.out.println(cell.getStringCellValue());
182
                                        break;
183
                                        case 2:
184
                                                System.out.println(cell.getNumericCellValue());
185
                                        break;
186
                                        }
187
                                }
188
                        }
189
 
190
                // Reescrever
191
                        try {
192
                        FileOutputStream stream = new FileOutputStream("d:/planilha.xls");
193
                        workbook.write(stream);
194
                        stream.close();
195
                        workbook.close();
196
                        System.out.println("Success!!");
197
                } catch (FileNotFoundException e) {
198
                        e.printStackTrace();
199
                } catch (IOException e) {
200
                        e.printStackTrace();
201
                }
202
 
203
                        file.close();
204
                        workbook.close();
205
                } catch (FileNotFoundException e) {
206
                        e.printStackTrace();
207
                }
208
        }
209
 
441 espaco 210
        public static void main4(String[] args) throws IOException {
106 espaco 211
                Avaliacao avaliacao = new Avaliacao();
212
                Vigencia vigencia = new Vigencia();
213
                vigencia.setDescricao("11/2020");
214
                avaliacao.setVigencia(vigencia);
215
                List<AvaliacaoFuncionario> participantes = new ArrayList<AvaliacaoFuncionario>();
216
                AvaliacaoFuncionario avaliacaoFuncionario = new AvaliacaoFuncionario();
217
                Funcionario funcionario = new Funcionario();
218
                Pessoa pessoa = new Pessoa();
219
                pessoa.setNome("ADALBERTO SOARES BRITO NETO");
220
                funcionario.setPessoa(pessoa);
221
                funcionario.setCodigoContabilidade(48);
222
                avaliacaoFuncionario.setFuncionario(funcionario);
223
                avaliacaoFuncionario.setValorComissao(new Double(50.0));
224
                participantes.add(avaliacaoFuncionario);
225
                avaliacao.setParticipantes(new HashSet<AvaliacaoFuncionario>());
226
                avaliacao.getParticipantes().add(avaliacaoFuncionario);
227
 
228
                String filePath = "d:/importacao.xls";
229
                try {
230
                        FileInputStream file = new FileInputStream(new File(filePath));
231
                        HSSFWorkbook workbook = new HSSFWorkbook(file);
232
                        HSSFSheet sheet = workbook.getSheetAt(0);
233
 
234
                        Iterator rowIterator = sheet.rowIterator();
235
                        while (rowIterator.hasNext()) {
236
                                Row row = (Row) rowIterator.next();
237
                                Iterator cellIterator = row.cellIterator();
238
                                if (row.getRowNum() < 11) {
239
                                        if (row.getRowNum() == 4) {
240
                                                while (cellIterator.hasNext()) {
241
                                                        Cell cell = (Cell) cellIterator.next();
242
                                                        switch (cell.getColumnIndex()) {
243
                                                                case 2:
244
                                                                        cell.setCellValue(vigencia.getDescricao());
245
                                                                        System.out.println(cell.getRichStringCellValue()); break;
246
                                                        }
247
                                                }
248
                                        }
249
                                        continue;
250
                                }
251
                                Integer codigoFolha = null;
252
                                while (cellIterator.hasNext()) {
253
                                        Boolean atualizar = true;
254
                                        Cell cell = (Cell) cellIterator.next();
255
                                        switch (cell.getColumnIndex()) {
256
                                                case 1:
257
                                                        Integer tipoCelula = cell.getCellType();
258
                                                        if (tipoCelula.equals(Cell.CELL_TYPE_NUMERIC)) {
259
                                                                System.out.println(cell.getNumericCellValue());
260
                                                                Double codigo = cell.getNumericCellValue();
261
                                                                codigoFolha = codigo.intValue();
262
                                                        } else {
263
                                                                atualizar = false;
264
                                                        }
265
                                                        break;
266
                                                case 2:
267
                                                        if (atualizar) {
268
                                                                System.out.println(cell.getStringCellValue()); break;
269
                                                        }
270
                                                case 3:
271
                                                        if (atualizar) {
272
                                                                for (AvaliacaoFuncionario avaliacaoFunc : avaliacao.getParticipantes()) {
273
                                                                        if (avaliacaoFunc.getFuncionario().getCodigoContabilidade().equals(codigoFolha)) {
274
                                                                                String valor = StringUtil.formatarValorComDoisDigitos(avaliacaoFunc.getValorComissao().toString());
275
                                                                                cell.setCellValue(valor.replace(".", ","));
276
                                                                                break;
277
                                                                        }
278
                                                                }
279
                                                                System.out.println(cell.getStringCellValue());
280
                                                        }
281
                                                        break;
282
                                        }
283
                                }
284
                        }
285
 
286
                        try {
287
                        FileOutputStream stream = new FileOutputStream("d:/importacao.xls");
288
                        workbook.write(stream);
289
                        stream.close();
290
                        workbook.close();
291
                        System.out.println("Success!!");
292
                } catch (FileNotFoundException e) {
293
                        e.printStackTrace();
294
                } catch (IOException e) {
295
                        e.printStackTrace();
296
                }
297
 
298
                        file.close();
299
                        workbook.close();
300
                } catch (FileNotFoundException e) {
301
                        e.printStackTrace();
302
                } catch (Exception e) {
303
                        e.printStackTrace();
304
                }
305
        }
306
 
307
        /*
308
        public static void main( String[] args )
309
        {
310
        // Criando o arquivo e uma planilha chamada "Product"
311
        HSSFWorkbook workbook = new HSSFWorkbook();
312
        HSSFSheet sheet = workbook.createSheet("Product");
313
 
314
        // Definindo alguns padroes de layout
315
        sheet.setDefaultColumnWidth(15);
316
        sheet.setDefaultRowHeight((short)400);
317
 
318
        //Carregando os produtos
319
        List products = getProducts();
320
 
321
        int rownum = 0;
322
        int cellnum = 0;
323
        Cell cell;
324
        Row row;
325
 
326
        //Configurando estilos de células (Cores, alinhamento, formatação, etc..)
327
        HSSFDataFormat numberFormat = workbook.createDataFormat();
328
 
329
        CellStyle headerStyle = workbook.createCellStyle();
330
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
331
        headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
332
        headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
333
        headerStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
334
 
335
        CellStyle textStyle = workbook.createCellStyle();
336
        textStyle.setAlignment(CellStyle.ALIGN_CENTER);
337
        textStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
338
 
339
        CellStyle numberStyle = workbook.createCellStyle();
340
        numberStyle.setDataFormat(numberFormat.getFormat("#,##0.00"));
341
        numberStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
342
 
343
        // Configurando Header
344
        row = sheet.createRow(rownum++);
345
        cell = row.createCell(cellnum++);
346
        cell.setCellStyle(headerStyle);
347
        cell.setCellValue("Code");
348
 
349
        cell = row.createCell(cellnum++);
350
        cell.setCellStyle(headerStyle);
351
        cell.setCellValue("Name");
352
 
353
        cell = row.createCell(cellnum++);
354
        cell.setCellStyle(headerStyle);
355
        cell.setCellValue("Price");
356
 
357
        // Adicionando os dados dos produtos na planilha
358
        for (Product product : products) {
359
        row = sheet.createRow(rownum++);
360
        cellnum = 0;
361
 
362
        cell = row.createCell(cellnum++);
363
        cell.setCellStyle(textStyle);
364
        cell.setCellValue(product.getId());
365
 
366
        cell = row.createCell(cellnum++);
367
        cell.setCellStyle(textStyle);
368
        cell.setCellValue(product.getName());
369
 
370
        cell = row.createCell(cellnum++);
371
        cell.setCellStyle(numberStyle);
372
        cell.setCellValue(product.getPrice());
373
        }
374
 
375
        try {
376
 
377
        //Escrevendo o arquivo em disco
378
        FileOutputStream out = new FileOutputStream(new File("/tmp/products.xls"));
379
        workbook.write(out);
380
        out.close();
381
        workbook.close();
382
        System.out.println("Success!!");
383
 
384
        } catch (FileNotFoundException e) {
385
        e.printStackTrace();
386
        } catch (IOException e) {
387
        e.printStackTrace();
388
        }
389
        }
390
        }
391
 
392
        //Simulando uma listagem de produtos
393
        private static List getProducts(){
394
        List products = new ArrayList();
395
 
396
        products.add(new Product(1l, "Produto 1", 200.5d));
397
        products.add(new Product(2l, "Produto 2", 1050.5d));
398
        products.add(new Product(3l, "Produto 3", 50d));
399
        products.add(new Product(4l, "Produto 4", 200d));
400
        products.add(new Product(5l, "Produto 5", 450d));
401
        products.add(new Product(6l, "Produto 6", 150.5d));
402
        products.add(new Product(7l, "Produto 7", 300.99d));
403
        products.add(new Product(8l, "Produto 8", 1000d));
404
        products.add(new Product(9l, "Produto 9", 350d));
405
        products.add(new Product(10l, "Produto 10", 200d));
406
 
407
        return products;
408
        }
409
        */
410
 
411
        /*
412
        public static void main(String[] args) throws IOException, DocumentException {
413
                String caminhoArquivo = "H://recibo.pdf";
414
                List<byte[]> arquivos = separarPDF(caminhoArquivo);
415
                int i = 1;
416
                for (byte[] arquivo : arquivos) {
417
//                      System.out.println(extrairPDF(arquivo));
418
                        String[] linhas = extrairPDFEmLinhas(arquivo);
419
 
420
                        boolean capturar = false;
421
                        for (String linha : linhas) {
422
                                if (capturar) {
423
                                        System.out.println(linha);
424
                                        capturar = false;
425
                                }
426
                                if (linha.contains("CC:")) {
427
                                        capturar = true;
428
                                }
429
                        }
430
 
431
                        System.out.println(caminhoArquivo.substring(0, caminhoArquivo.indexOf(".pdf")) + "-" + String.format("%03d", i + 1) + ".pdf");
432
//                      gravarArquivo(caminhoArquivo.substring(0, caminhoArquivo.indexOf(".pdf")) + "-" + String.format("%03d", i + 1) + ".pdf", arquivo);
433
                        i++;
434
                        //break;
435
                }
436
        }
437
        */
438
        public static void gravarArquivo(String caminhoArquivo, byte[] arquivo) {
439
                try {
440
                        FileOutputStream fos = new FileOutputStream(caminhoArquivo);
441
                        fos.write(arquivo);
442
                        fos.flush();
443
                        fos.close();
444
                } catch (Exception e) {
445
                        e.printStackTrace();
446
                }
447
        }
448
 
449
        public static String[] extrairPDFEmLinhas(byte[] arquivo) throws IOException {
450
                StringBuilder texto = new StringBuilder();
451
                texto.append(extrairPDF(arquivo));
452
                return texto.toString().split("\n");
453
        }
454
 
455
        public static String extrairPDF(byte[] arquivo) throws IOException {
456
                PdfReader reader = new PdfReader(arquivo);
457
                String textoExtraido = null;
458
                try {
459
                        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
460
                        int quantidadePaginas = reader.getNumberOfPages();
461
                        TextExtractionStrategy strategy;
462
 
463
                        for (int i = 1; i <= quantidadePaginas; i++) {
464
                                strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
465
                                textoExtraido = strategy.getResultantText().toString();
466
                        }
467
                } catch (Exception e) {
468
                        e.printStackTrace();
469
                } finally {
470
                        reader.close();
471
                }
472
                return textoExtraido;
473
        }
474
 
475
        public static boolean verificarSeTemTexto(String texto, String textoExtraido) {
476
                if (VerificadorUtil.naoEstaNuloOuVazio(textoExtraido)) {
477
                        if (textoExtraido.contains(texto)) {
478
                                return true;
479
                        }
480
                }
481
                return false;
482
        }
483
 
484
        public static List<byte[]> separarPDF(byte[] arquivo) throws IOException {
485
                return separarPDF(new PdfReader(arquivo));
486
        }
487
 
488
        public static List<byte[]> separarPDF(String caminhoArquivo) throws IOException {
489
                return separarPDF(new PdfReader(caminhoArquivo));
490
        }
491
 
492
        private static List<byte[]> separarPDF(PdfReader reader) {
493
                List<byte[]> arquivos = new ArrayList<byte[]>();
494
                try {
495
            int quantidadePaginas = reader.getNumberOfPages();
496
            int i = 0;
497
            while (i < quantidadePaginas) {
498
                Document documento = new Document(reader.getPageSizeWithRotation(1));
499
                        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
500
                        PdfCopy writer = new PdfCopy(documento, pdfOutputStream);
501
                        documento.open();
502
                PdfImportedPage pagina = writer.getImportedPage(reader, ++i);
503
                writer.addPage(pagina);
504
                documento.close();
505
                writer.close();
506
 
507
                arquivos.add(pdfOutputStream.toByteArray());
508
                pdfOutputStream.close();
509
            }
510
        } catch (Exception e) {
511
            e.printStackTrace();
512
        } finally {
513
                        reader.close();
514
                }
515
                return arquivos;
516
        }
517
 
518
        public static void gerarPDF(byte[] bytesPDF, String destinoArquivo) {
519
                try {
520
                        PdfReader reader = new PdfReader(bytesPDF);
521
            Document documento = new Document(reader.getPageSizeWithRotation(1));
522
            PdfCopy copy = new PdfCopy(documento, new FileOutputStream(destinoArquivo));
523
            documento.open();
524
            PdfImportedPage page = copy.getImportedPage(reader, 1);
525
            copy.addPage(page);
526
            documento.close();
527
            copy.close();
528
                } catch (Exception e) {
529
                        e.printStackTrace();
530
                }
531
        }
532
 
533
        public static void separarSalvandoArquivoPDF(String caminhoArquivo) {
534
                try {
535
            PdfReader reader = new PdfReader(caminhoArquivo);
536
            int n = reader.getNumberOfPages();
537
            int i = 0;
538
            while (i < n) {
539
                String destinoArquivo = caminhoArquivo.substring(0, caminhoArquivo.indexOf(".pdf")) + "-" + String.format("%03d", i + 1) + ".pdf";
540
                Document document = new Document(reader.getPageSizeWithRotation(1));
541
                PdfCopy writer = new PdfCopy(document, new FileOutputStream(destinoArquivo));
542
                document.open();
543
                PdfImportedPage page = writer.getImportedPage(reader, ++i);
544
                writer.addPage(page);
545
                document.close();
546
                writer.close();
547
            }
548
        } catch (Exception e) {
549
            e.printStackTrace();
550
        }
551
        }
552
 
553
}