Subversion Repositories Integrator Subversion

Rev

Rev 106 | Go to most recent revision | 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
 
94
        public static void main2(String[] args) throws IOException {
95
        HSSFWorkbook wb = new HSSFWorkbook();
96
 
97
        // ABAS
98
        HSSFSheet aba1 = criarAbas(wb, "Planilha 1");
99
        criarAbas(wb, "Planilha 2");
100
        criarAbas(wb, "Planilha 3");
101
 
102
        configurarCabecalho(wb, aba1);
103
 
104
        Row linha = aba1.createRow(1);
105
        criarCelula(wb, aba1, linha, 0, configurarCelulaTexto(wb), "1");
106
        criarCelula(wb, aba1, linha, 1, configurarCelulaTexto(wb), "TESTE");
107
        criarCelula(wb, aba1, linha, 2, configurarCelulaNumerico(wb), "10");
108
 
109
        try {
110
                FileOutputStream stream = new FileOutputStream("d:/planilha.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 main3(String[] args) throws IOException {
123
                String filePath = "d:/planilha.xls";
124
                try{
125
                // Abrindo o arquivo e recuperando a planilha
126
                FileInputStream file = new FileInputStream(new File(filePath));
127
                HSSFWorkbook workbook = new HSSFWorkbook(file);
128
                HSSFSheet sheet = workbook.getSheetAt(0);
129
 
130
                List products = new ArrayList();
131
 
132
                Iterator rowIterator = sheet.rowIterator();
133
                while (rowIterator.hasNext()) {
134
                        Row row = (Row) rowIterator.next();
135
 
136
                        // Descantando a primeira linha com o header
137
                        if(row.getRowNum() == 0){
138
                                continue;
139
                        }
140
 
141
                        Iterator cellIterator = row.cellIterator();
142
        //              Product product = new Product();
143
        //              products.add(product);
144
                        while (cellIterator.hasNext()) {
145
                                Cell cell = (Cell) cellIterator.next();
146
                                switch (cell.getColumnIndex()) {
147
                                        case 0:
148
                        //              product.setId(((Double)cell.getNumericCellValue()).longValue());
149
                                                cell.setCellValue("2");// Substituindo valores
150
                                        System.out.println(cell.getStringCellValue());
151
                                        break;
152
                                        case 1:
153
                                                System.out.println(cell.getStringCellValue());
154
                                        break;
155
                                        case 2:
156
                                                System.out.println(cell.getNumericCellValue());
157
                                        break;
158
                                        }
159
                                }
160
                        }
161
 
162
                // Reescrever
163
                        try {
164
                        FileOutputStream stream = new FileOutputStream("d:/planilha.xls");
165
                        workbook.write(stream);
166
                        stream.close();
167
                        workbook.close();
168
                        System.out.println("Success!!");
169
                } catch (FileNotFoundException e) {
170
                        e.printStackTrace();
171
                } catch (IOException e) {
172
                        e.printStackTrace();
173
                }
174
 
175
                        file.close();
176
                        workbook.close();
177
                } catch (FileNotFoundException e) {
178
                        e.printStackTrace();
179
                }
180
        }
181
 
182
        public static void main(String[] args) throws IOException {
183
                Avaliacao avaliacao = new Avaliacao();
184
                Vigencia vigencia = new Vigencia();
185
                vigencia.setDescricao("11/2020");
186
                avaliacao.setVigencia(vigencia);
187
                List<AvaliacaoFuncionario> participantes = new ArrayList<AvaliacaoFuncionario>();
188
                AvaliacaoFuncionario avaliacaoFuncionario = new AvaliacaoFuncionario();
189
                Funcionario funcionario = new Funcionario();
190
                Pessoa pessoa = new Pessoa();
191
                pessoa.setNome("ADALBERTO SOARES BRITO NETO");
192
                funcionario.setPessoa(pessoa);
193
                funcionario.setCodigoContabilidade(48);
194
                avaliacaoFuncionario.setFuncionario(funcionario);
195
                avaliacaoFuncionario.setValorComissao(new Double(50.0));
196
                participantes.add(avaliacaoFuncionario);
197
                avaliacao.setParticipantes(new HashSet<AvaliacaoFuncionario>());
198
                avaliacao.getParticipantes().add(avaliacaoFuncionario);
199
 
200
                String filePath = "d:/importacao.xls";
201
                try {
202
                        FileInputStream file = new FileInputStream(new File(filePath));
203
                        HSSFWorkbook workbook = new HSSFWorkbook(file);
204
                        HSSFSheet sheet = workbook.getSheetAt(0);
205
 
206
                        Iterator rowIterator = sheet.rowIterator();
207
                        while (rowIterator.hasNext()) {
208
                                Row row = (Row) rowIterator.next();
209
                                Iterator cellIterator = row.cellIterator();
210
                                if (row.getRowNum() < 11) {
211
                                        if (row.getRowNum() == 4) {
212
                                                while (cellIterator.hasNext()) {
213
                                                        Cell cell = (Cell) cellIterator.next();
214
                                                        switch (cell.getColumnIndex()) {
215
                                                                case 2:
216
                                                                        cell.setCellValue(vigencia.getDescricao());
217
                                                                        System.out.println(cell.getRichStringCellValue()); break;
218
                                                        }
219
                                                }
220
                                        }
221
                                        continue;
222
                                }
223
                                Integer codigoFolha = null;
224
                                while (cellIterator.hasNext()) {
225
                                        Boolean atualizar = true;
226
                                        Cell cell = (Cell) cellIterator.next();
227
                                        switch (cell.getColumnIndex()) {
228
                                                case 1:
229
                                                        Integer tipoCelula = cell.getCellType();
230
                                                        if (tipoCelula.equals(Cell.CELL_TYPE_NUMERIC)) {
231
                                                                System.out.println(cell.getNumericCellValue());
232
                                                                Double codigo = cell.getNumericCellValue();
233
                                                                codigoFolha = codigo.intValue();
234
                                                        } else {
235
                                                                atualizar = false;
236
                                                        }
237
                                                        break;
238
                                                case 2:
239
                                                        if (atualizar) {
240
                                                                System.out.println(cell.getStringCellValue()); break;
241
                                                        }
242
                                                case 3:
243
                                                        if (atualizar) {
244
                                                                for (AvaliacaoFuncionario avaliacaoFunc : avaliacao.getParticipantes()) {
245
                                                                        if (avaliacaoFunc.getFuncionario().getCodigoContabilidade().equals(codigoFolha)) {
246
                                                                                String valor = StringUtil.formatarValorComDoisDigitos(avaliacaoFunc.getValorComissao().toString());
247
                                                                                cell.setCellValue(valor.replace(".", ","));
248
                                                                                break;
249
                                                                        }
250
                                                                }
251
                                                                System.out.println(cell.getStringCellValue());
252
                                                        }
253
                                                        break;
254
                                        }
255
                                }
256
                        }
257
 
258
                        try {
259
                        FileOutputStream stream = new FileOutputStream("d:/importacao.xls");
260
                        workbook.write(stream);
261
                        stream.close();
262
                        workbook.close();
263
                        System.out.println("Success!!");
264
                } catch (FileNotFoundException e) {
265
                        e.printStackTrace();
266
                } catch (IOException e) {
267
                        e.printStackTrace();
268
                }
269
 
270
                        file.close();
271
                        workbook.close();
272
                } catch (FileNotFoundException e) {
273
                        e.printStackTrace();
274
                } catch (Exception e) {
275
                        e.printStackTrace();
276
                }
277
        }
278
 
279
        /*
280
        public static void main( String[] args )
281
        {
282
        // Criando o arquivo e uma planilha chamada "Product"
283
        HSSFWorkbook workbook = new HSSFWorkbook();
284
        HSSFSheet sheet = workbook.createSheet("Product");
285
 
286
        // Definindo alguns padroes de layout
287
        sheet.setDefaultColumnWidth(15);
288
        sheet.setDefaultRowHeight((short)400);
289
 
290
        //Carregando os produtos
291
        List products = getProducts();
292
 
293
        int rownum = 0;
294
        int cellnum = 0;
295
        Cell cell;
296
        Row row;
297
 
298
        //Configurando estilos de células (Cores, alinhamento, formatação, etc..)
299
        HSSFDataFormat numberFormat = workbook.createDataFormat();
300
 
301
        CellStyle headerStyle = workbook.createCellStyle();
302
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
303
        headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
304
        headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
305
        headerStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
306
 
307
        CellStyle textStyle = workbook.createCellStyle();
308
        textStyle.setAlignment(CellStyle.ALIGN_CENTER);
309
        textStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
310
 
311
        CellStyle numberStyle = workbook.createCellStyle();
312
        numberStyle.setDataFormat(numberFormat.getFormat("#,##0.00"));
313
        numberStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
314
 
315
        // Configurando Header
316
        row = sheet.createRow(rownum++);
317
        cell = row.createCell(cellnum++);
318
        cell.setCellStyle(headerStyle);
319
        cell.setCellValue("Code");
320
 
321
        cell = row.createCell(cellnum++);
322
        cell.setCellStyle(headerStyle);
323
        cell.setCellValue("Name");
324
 
325
        cell = row.createCell(cellnum++);
326
        cell.setCellStyle(headerStyle);
327
        cell.setCellValue("Price");
328
 
329
        // Adicionando os dados dos produtos na planilha
330
        for (Product product : products) {
331
        row = sheet.createRow(rownum++);
332
        cellnum = 0;
333
 
334
        cell = row.createCell(cellnum++);
335
        cell.setCellStyle(textStyle);
336
        cell.setCellValue(product.getId());
337
 
338
        cell = row.createCell(cellnum++);
339
        cell.setCellStyle(textStyle);
340
        cell.setCellValue(product.getName());
341
 
342
        cell = row.createCell(cellnum++);
343
        cell.setCellStyle(numberStyle);
344
        cell.setCellValue(product.getPrice());
345
        }
346
 
347
        try {
348
 
349
        //Escrevendo o arquivo em disco
350
        FileOutputStream out = new FileOutputStream(new File("/tmp/products.xls"));
351
        workbook.write(out);
352
        out.close();
353
        workbook.close();
354
        System.out.println("Success!!");
355
 
356
        } catch (FileNotFoundException e) {
357
        e.printStackTrace();
358
        } catch (IOException e) {
359
        e.printStackTrace();
360
        }
361
        }
362
        }
363
 
364
        //Simulando uma listagem de produtos
365
        private static List getProducts(){
366
        List products = new ArrayList();
367
 
368
        products.add(new Product(1l, "Produto 1", 200.5d));
369
        products.add(new Product(2l, "Produto 2", 1050.5d));
370
        products.add(new Product(3l, "Produto 3", 50d));
371
        products.add(new Product(4l, "Produto 4", 200d));
372
        products.add(new Product(5l, "Produto 5", 450d));
373
        products.add(new Product(6l, "Produto 6", 150.5d));
374
        products.add(new Product(7l, "Produto 7", 300.99d));
375
        products.add(new Product(8l, "Produto 8", 1000d));
376
        products.add(new Product(9l, "Produto 9", 350d));
377
        products.add(new Product(10l, "Produto 10", 200d));
378
 
379
        return products;
380
        }
381
        */
382
 
383
        /*
384
        public static void main(String[] args) throws IOException, DocumentException {
385
                String caminhoArquivo = "H://recibo.pdf";
386
                List<byte[]> arquivos = separarPDF(caminhoArquivo);
387
                int i = 1;
388
                for (byte[] arquivo : arquivos) {
389
//                      System.out.println(extrairPDF(arquivo));
390
                        String[] linhas = extrairPDFEmLinhas(arquivo);
391
 
392
                        boolean capturar = false;
393
                        for (String linha : linhas) {
394
                                if (capturar) {
395
                                        System.out.println(linha);
396
                                        capturar = false;
397
                                }
398
                                if (linha.contains("CC:")) {
399
                                        capturar = true;
400
                                }
401
                        }
402
 
403
                        System.out.println(caminhoArquivo.substring(0, caminhoArquivo.indexOf(".pdf")) + "-" + String.format("%03d", i + 1) + ".pdf");
404
//                      gravarArquivo(caminhoArquivo.substring(0, caminhoArquivo.indexOf(".pdf")) + "-" + String.format("%03d", i + 1) + ".pdf", arquivo);
405
                        i++;
406
                        //break;
407
                }
408
        }
409
        */
410
        public static void gravarArquivo(String caminhoArquivo, byte[] arquivo) {
411
                try {
412
                        FileOutputStream fos = new FileOutputStream(caminhoArquivo);
413
                        fos.write(arquivo);
414
                        fos.flush();
415
                        fos.close();
416
                } catch (Exception e) {
417
                        e.printStackTrace();
418
                }
419
        }
420
 
421
        public static String[] extrairPDFEmLinhas(byte[] arquivo) throws IOException {
422
                StringBuilder texto = new StringBuilder();
423
                texto.append(extrairPDF(arquivo));
424
                return texto.toString().split("\n");
425
        }
426
 
427
        public static String extrairPDF(byte[] arquivo) throws IOException {
428
                PdfReader reader = new PdfReader(arquivo);
429
                String textoExtraido = null;
430
                try {
431
                        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
432
                        int quantidadePaginas = reader.getNumberOfPages();
433
                        TextExtractionStrategy strategy;
434
 
435
                        for (int i = 1; i <= quantidadePaginas; i++) {
436
                                strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
437
                                textoExtraido = strategy.getResultantText().toString();
438
                        }
439
                } catch (Exception e) {
440
                        e.printStackTrace();
441
                } finally {
442
                        reader.close();
443
                }
444
                return textoExtraido;
445
        }
446
 
447
        public static boolean verificarSeTemTexto(String texto, String textoExtraido) {
448
                if (VerificadorUtil.naoEstaNuloOuVazio(textoExtraido)) {
449
                        if (textoExtraido.contains(texto)) {
450
                                return true;
451
                        }
452
                }
453
                return false;
454
        }
455
 
456
        public static List<byte[]> separarPDF(byte[] arquivo) throws IOException {
457
                return separarPDF(new PdfReader(arquivo));
458
        }
459
 
460
        public static List<byte[]> separarPDF(String caminhoArquivo) throws IOException {
461
                return separarPDF(new PdfReader(caminhoArquivo));
462
        }
463
 
464
        private static List<byte[]> separarPDF(PdfReader reader) {
465
                List<byte[]> arquivos = new ArrayList<byte[]>();
466
                try {
467
            int quantidadePaginas = reader.getNumberOfPages();
468
            int i = 0;
469
            while (i < quantidadePaginas) {
470
                Document documento = new Document(reader.getPageSizeWithRotation(1));
471
                        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
472
                        PdfCopy writer = new PdfCopy(documento, pdfOutputStream);
473
                        documento.open();
474
                PdfImportedPage pagina = writer.getImportedPage(reader, ++i);
475
                writer.addPage(pagina);
476
                documento.close();
477
                writer.close();
478
 
479
                arquivos.add(pdfOutputStream.toByteArray());
480
                pdfOutputStream.close();
481
            }
482
        } catch (Exception e) {
483
            e.printStackTrace();
484
        } finally {
485
                        reader.close();
486
                }
487
                return arquivos;
488
        }
489
 
490
        public static void gerarPDF(byte[] bytesPDF, String destinoArquivo) {
491
                try {
492
                        PdfReader reader = new PdfReader(bytesPDF);
493
            Document documento = new Document(reader.getPageSizeWithRotation(1));
494
            PdfCopy copy = new PdfCopy(documento, new FileOutputStream(destinoArquivo));
495
            documento.open();
496
            PdfImportedPage page = copy.getImportedPage(reader, 1);
497
            copy.addPage(page);
498
            documento.close();
499
            copy.close();
500
                } catch (Exception e) {
501
                        e.printStackTrace();
502
                }
503
        }
504
 
505
        public static void separarSalvandoArquivoPDF(String caminhoArquivo) {
506
                try {
507
            PdfReader reader = new PdfReader(caminhoArquivo);
508
            int n = reader.getNumberOfPages();
509
            int i = 0;
510
            while (i < n) {
511
                String destinoArquivo = caminhoArquivo.substring(0, caminhoArquivo.indexOf(".pdf")) + "-" + String.format("%03d", i + 1) + ".pdf";
512
                Document document = new Document(reader.getPageSizeWithRotation(1));
513
                PdfCopy writer = new PdfCopy(document, new FileOutputStream(destinoArquivo));
514
                document.open();
515
                PdfImportedPage page = writer.getImportedPage(reader, ++i);
516
                writer.addPage(page);
517
                document.close();
518
                writer.close();
519
            }
520
        } catch (Exception e) {
521
            e.printStackTrace();
522
        }
523
        }
524
 
525
}