S.O OpenSuse

openSUSE es un sistema operativo libre basado en Linux. La distribución openSUSE es estable, sencilla de usar, completa y de propósito general

Node.js

Node es una platafoma y un entorno de desarrollo basado en JavaScript al lado del servidor

Java

Java es un entorno de desarrollo multiplataforma

Java

Java es un entorno de desarrollo multiplataforma

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

Mostrando entradas con la etiqueta iText. Mostrar todas las entradas
Mostrando entradas con la etiqueta iText. Mostrar todas las entradas

miércoles, 27 de febrero de 2013

Exportar lista de Directorios a Excel, txt o Pdf usando itext y POI

En algunas ocaciones necesite una saber la lista de de archivos que se encontraban dentro de un directorio y subdirectorio y guardarlos en un archivo. asi que implemente una pequeña utileriapara ello.


Requisitos


Creando el proyecto

Creamos un nuevo proyecto Java y agregamos las librerias de iText y POI



Creamos una nueva clase llamada ExportaTxt dentro de esta crearemos el metodo crearTxt le pasaremos como parametros un List de String y un String con la cadena y el nombre del archivo.
01 public class ExportaTxt {
02 
03     public void crearTxt(ArrayList<String> list, String archivo) {
04         FileWriter fichero = null;
05         PrintWriter pw = null;
06         try {
07             fichero = new FileWriter(archivo);
08             pw = new PrintWriter(fichero);
09 for (String string : list) {
10                 pw.println(string);
11             }
12         } catch (Exception e) {
13             e.printStackTrace();
14         }
15         finally {
16             try {
17                 if (fichero != null) {
18                     fichero.close();
19                 }
20             } catch (Exception e) {
21                 e.printStackTrace();
22             }
23         }
24     }
25 }
26 
Ahora agregamos la clase exporta excel esta tendra un metodo que crearExcel al cual le pasaremos como parametros una lista de directorios, el nombre del libro y la ruta con el nombre del archivo.
01 public class ExportaExcel {
02 
03     public void crearExcel(ArrayList<String> list, String libro, String archivo) {
04         HSSFWorkbook book = new HSSFWorkbook();
05         HSSFSheet hoja = book.createSheet(libro);
06         HSSFRow fil = hoja.createRow(0);
07         HSSFCell celd = fil.createCell(0);
08         celd.setCellValue("Lista de archivos");
09         CellStyle stilo = book.createCellStyle();
10         stilo.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
11         stilo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
12         HSSFFont font = book.createFont();
13         font.setFontHeightInPoints((short) 12);
14         font.setBoldweight(Font.BOLDWEIGHT_BOLD);
15         stilo.setFont(font);
16         celd.setCellStyle(stilo);
17 for (String lis : list) {
18             HSSFRow fila = hoja.createRow(list.indexOf(lis) + 1);
19             HSSFCell celda = fila.createCell(0);
20             celda.setCellValue(lis);
21             hoja.autoSizeColumn(0);
22             try {
23                 FileOutputStream fichero = new FileOutputStream(archivo);
24                 book.write(fichero);
25                 fichero.close();
26             } catch (Exception e) {
27                 e.printStackTrace();
28             }
29         }
30     }
31 }
32 

ahora creamos la clase ExportaPdf esta clase tendra un metodo llamado crearPdf le pasaremos como parametros la lista de archivos o directorios y la ruta con el nombre del archivo.
01 public class ExportaPdf {
02 
03     public void crerPdf(ArrayList<String> list, String archivo) {
04         try {
05             Document document = new Document();
06             PdfWriter.getInstance(document, new FileOutputStream(archivo));
07             document.open();
08             Font font = new Font();
09             font.setStyle(Font.BOLD);
10             PdfPTable table = new PdfPTable(1);
11             table.setWidths(new int[] {1});
12             PdfPCell cell;
13             cell = new PdfPCell(new Phrase("lista de archivos", font));
14             cell.setHorizontalAlignment(Element.ALIGN_CENTER);
15             table.addCell(cell);
16 for (String string : list) {
17                 cell = new PdfPCell(new Phrase(string));
18                 cell.setHorizontalAlignment(Element.ALIGN_LEFT);
19                 table.addCell(cell);
20             }
21             document.add(table);
22             document.close();
23         } catch (Exception e) {
24             e.printStackTrace();
25         }
26 
27     }
28 } 

Creamos una clase que sera nuestro controlador esta clase contenda un medor que nos retorne una lista de los archivos ,directorios y subdirectorios. ademas se implemetaran tres metodos exportarTxt, exportarExcel y exportarPdf.
01 public class Direc {
02 
03     ArrayList lista = new ArrayList<String>();
04 
05     public ArrayList<String> getDir(String directorio) {
06         File file = new File(directorio);
07         File[] dirs = file.listFiles();
08 for (File file1 : dirs) {
09             lista.add(file1.getName());
10             if (file1.isDirectory()) {
11                 getDir(file1.getAbsolutePath());
12             }
13         }
14 
15         return lista;
16     }
17 
18     public void exportarExcel(String dir, String dondeGuardar) {
19         ArrayList<String> list = getDir(dir);
20         ExportaExcel excel = new ExportaExcel();
21         excel.crearExcel(list, "lista de archivos", dondeGuardar + "/archivos.xls");
22     }
23 
24     public void exportarTxt(String dir, String dondeGuardar) {
25         ArrayList<String> list = getDir(dir);
26         ExportaTxt txt = new ExportaTxt();
27         txt.crearTxt(list, dondeGuardar + "/archivos.txt");
28     }
29 
30     public void exportarPdf(String dir, String dondeGuardar) {
31         ArrayList<String> list = getDir(dir);
32         ExportaPdf pdf = new ExportaPdf();
33         pdf.crerPdf(list, dondeGuardar + "/archivos.pdf");
34     }
35 }
36 

y por ultimo implementamos un pequeña interfaz.


 y listo.

aqui les dejo el codigo fuente.