Subversion Repositories Integrator Subversion

Rev

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

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