You are on page 1of 25

Introduccin

Se describirn a continuacin los elementos principales de la API


JExcel.
El objetivo de esta exposicin es presentar aspectos generales de la API
e introducir el uso de esta herramienta.
Se partir por explicar como se define un libro de trabajo, para luego
continuar con el manejo de celdas, tanto en modo de escritura como en
modo de lectura. Luego se aprender a dar formato a stas celdas.
Se explicar tambin cmo trabajar con frmulas en Excel, una
funcionalidad muy requerida usualmente.
Se acompaar la presentacin con ejemplos prcticos muy breves de
implementacin.
Algunas Libreras Importantes

import jxl.Cell;
Obviamente, las
libreras estn en
import jxl.CellType;
la carpeta jxl. Se
pueden copiar
import jxl.DateCell;
las libreras en
cada espacio de
import jxl.LabelCell;
trabajo, o bien,
trabajar con
import jxl.NumberCell;
NetBeans.
import jxl.Sheet;

import jxl.Workbook;
Clase Cell
Mtodos ms importantes:

CellFeatures getCellFeatures( );
CellFormat getCellFormat( );
Int getColumn( );
Int getRow( );
String getContents();
CellType getType( );
Boolean isHiden();
Clase CellFormat
Mtodos ms importantes:

Alignment getAlignment( );
Color getBackGroudColour( );
BorderLineStyle getBorder( );
Font getFont( );
Clase CellType
Atributo: String description;

Constantes public static final CellType:

EMPTY
LABEL
NUMBER
BOOLEAN
NUMBER_FORMULA
DATE
Clase DateCell
Extiende de Cell.

Mtodos mas importantes:

Date getDate( );
Boolean isTime( );
DateFormat getDateFormat( );
Clase Sheet
Mtodos ms importantes:

Cell getCell( int column, int row);


int getRows( );
Cell [ ] getRow( int row);
Cell [ ] getColumn (int col);
String getName( );
Cell findCell (String contents);
Clase Workbook
Mtodos ms importantes:

Sheet [ ] getSheets( );
Sheet getSheet (int index) throws IndexOutOfBounds Exception;
int getNumberOfSheets( );
Workbook getWorkbook(java.io.File file);
WritableWorkbook createWorkbook( java.io.File file, Workbook in);
Creacin de un Workbook

// libreras varias...
public class Read {
private Workbook workbook;

public Read(String file) {


try {
this.workbook = Workbook.getWorkbook (new File(file));
} catch (java.io.IOException ioe) {
System.out.println ("No se pudo abrir el archivo");
} catch (jxl.read.biff.BiffException jrbe) {
System.out.println("No se pudo crear el libro");
}
}
}
Leer desde un archivo Excel

public void readBook() {

Sheet sheet = workbook.getSheet(0);


Cell a1 = sheet.getCell(0,0);
Cell b2 = sheet.getCell(1,1);
Cell c2 = sheet.getCell(2,2);

String stringa1 = a1.getContents();


String stringb2 = b2.getContents();
String stringc2 = c2.getContents();

workbook.close();

System.out.println( stringa1 + "\n" + stringb2 + "\n" + stringc2);


}
Leer desde un archivo Excel
Tipos de celdas

public void readType() { if (b2.getType() == CellType.NUMBER) {


NumberCell nc = (NumberCell) b2;
String string = null; number = nc.getValue();
double number = 0; }
Date date = null;
if (c2.getType() == CellType.DATE){
Sheet sheet = workbook.getSheet(0); DateCell dc = (DateCell) c2;
Cell a1 = sheet.getCell(0,0); date = dc.getDate();
Cell b2 = sheet.getCell(1,1); }
Cell c2 = sheet.getCell(2,2);
workbook.close();
if (a1.getType() == CellType.LABEL) { }
LabelCell lc = (LabelCell) a1;
string = lc.getString();
}
Tipos de celdas
Escritura en un archivo Excel

int i;

WritableWorkbook workbook = Workbook.createWorkbook(new File("salida.xls"));


WritableSheet sheet = workbook.createSheet("test", 0);

Label label = new Label(0, 0, "Nmeros");


sheet.addCell(label);

for (i=1; i<10; i++) {


Number temp = new Number(0, i, i);
sheet.addCell(temp);
}
Escritura en un archivo Excel
Formatos de celda
Algunas libreras importantes:

import jxl.write.WritableFont;
import jxl.format.BorderLineStyle;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableCell;
import jxl.write.WritableWorkbook;
import jxl.write.WritableCellFormat;
import jxl.format.Colour;
import jxl.format.Alignment;
import jxl.format.Border;
Clase WritableCellFormat

void setAlignment (Alignment a);


void setBorder ( Border b, BorderLineStyle ls);
void setBackGround ( Colour c);
Ejemplo con formato
WritableFont times16font = new WritableFont(WritableFont.TIMES, 16, WritableFont.BOLD, true);
times16font.setColour(Colour.WHITE);
WritableCellFormat formato1 = new WritableCellFormat(times16font);
WritableFont fuente= new WritableFont(WritableFont.ARIAL);
fuente.setColour(Colour.YELLOW);
WritableCellFormat formato2 = new WritableCellFormat(fuente);
formato1.setBackground(Colour.BLUE);
formato1.setAlignment(Alignment.CENTRE);
formato2.setBackground(Colour.RED);
formato2.setAlignment(Alignment.CENTRE);
formato2.setBorder(Border.ALL,BorderLineStyle.MEDIUM);

sheet.setColumnView(0,15);
Label label = new Label(0, 0, "Nmeros", formato1);
sheet.addCell(label);

for (i=1; i<10; i++) {


Number temp = new Number(0, i, i, formato2);
sheet.addCell(temp);
}
Ejemplo con formato
Trabajo con frmulas

Se introduce con la librera: jxl.write.Formula


Constructores:

Formula (int c, int r, String form)


Formula (int c, int r, String form, CellFormat st)

Donde c es la columna de la celda, r es la fila de la celda y form es


un string que contiene el valor de la frmula a introducir.
Inclusin de imgenes

Se usa la librera: jxl.write.WritableImage

Constructor de la clase:

public WritableImage(double x, double y, double width, double height, File image)

Donde x es la columna donde se inserta la imagen, y es la fila


donde se inserta (esquina superior izquierda) y width y height son
el ancho y alto que ocupar la imagen en numero de columnas y
filas respectivamente.
Inclusin de imgenes

Cdigo ejemplo:
WritableImage imagen = new WritableImage(1,12,5,12, new File("foto.png"));
sheet.addImage(imagen);
Ejemplo en red (base de datos)

Se presenta a continuacin un ejemplo del uso de esta herramienta para


mostrar el contenido de una base de datos montada en un servidor. La
idea es que el usuario pueda remotamente y en tiempo real obtener los
valores de los campos de una base de datos y automticamente por
medio de una aplicacin Java usando la API JExcel generar un archivo
Excel con estos datos.
El cdigo fuente se incluye como anexo a la presentacin para lectura
personal del lector.
Ejemplo en red (base de datos)
Ejemplo en red (base de datos)

You might also like