Download powerpoint

Document related concepts
no text concepts found
Transcript
Introducción
Se describirán a continuación los elementos principales de la API
JExcel.
El objetivo de esta exposición 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á también cómo trabajar con fórmulas en Excel, una
funcionalidad muy requerida usualmente.
Se acompañará la presentación con ejemplos prácticos muy breves de
implementación.
Algunas Librerías Importantes
Obviamente, las
librerías están en
la carpeta jxl. Se
pueden copiar
las librerías en
cada espacio de
trabajo, o bien,
trabajar con
NetBeans.
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.LabelCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
Clase Cell
Métodos más importantes:
CellFeatures getCellFeatures( );
CellFormat getCellFormat( );
Int getColumn( );
Int getRow( );
String getContents();
CellType getType( );
Boolean isHiden();
Clase CellFormat
Métodos más 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.
Métodos mas importantes:
Date getDate( );
Boolean isTime( );
DateFormat getDateFormat( );
Clase Sheet
Métodos más 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
Métodos más 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);
Creación de un Workbook
// librerías 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() {
String string = null;
double number = 0;
Date date = null;
Sheet sheet = workbook.getSheet(0);
Cell a1 = sheet.getCell(0,0);
Cell b2 = sheet.getCell(1,1);
Cell c2 = sheet.getCell(2,2);
if (b2.getType() == CellType.NUMBER) {
NumberCell nc = (NumberCell) b2;
number = nc.getValue();
}
if (c2.getType() == CellType.DATE){
DateCell dc = (DateCell) c2;
date = dc.getDate();
}
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, "Números");
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 librerías 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, "Números", 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 fórmulas
• Se introduce con la librería: 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 fórmula a introducir.
Inclusión de imágenes
Se usa la librería: 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.
Inclusión de imágenes
Código 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 continuación 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 automáticamente por
medio de una aplicación Java usando la API JExcel generar un archivo
Excel con estos datos.
El código fuente se incluye como anexo a la presentación para lectura
personal del lector.
Ejemplo en red (base de datos)
Ejemplo en red (base de datos)