Você está na página 1de 5

http://www.andykhan.com/jexcelapi/download.

html

JExcelApi

Al igual que POI, JExcelApi es una API destinada a facilitar la lectura, escritura y
modificación de documentos excel desde aplicaciones java. Los objetos y métodos
disponibles son muy similares a los que hemos visto para POI, siendo súmamente
sencillo manipular libros, hojas y celdas de un documento excel. En el fragmento
siguiente se muestra como realizar las mismas acciones del ejemplo anterior (crear un
libro y escribir varias celdas con distintos tipos de datos), pero esta vez usando
JExcelApi:

1
2
3
4 //Se crea el libro Excel
WritableWorkbook workbook =
5 Workbook.createWorkbook(new File("ejemplo.xls"));
6   
7 //Se crea una nueva hoja dentro del libro
8 WritableSheet sheet =
9 workbook.createSheet("HojaEjemplo", 0);
1   
0 //Creamos celdas de varios tipos
sheet.addCell(new jxl.write.Number(0, 0, 1));
1 sheet.addCell(new jxl.write.Number(1, 0, 1.2));
1 sheet.addCell(new jxl.write.Label(2, 0, "ejemplo"));
1 sheet.addCell(new jxl.write.Boolean(3,0,true));
2
1
3
import java.io.*;
import java.util.Date;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*; 
  
public class DemoJExcel
{
    public static void main(String[] args)
    {
        escribirExcel();
  
        leerExcel();
  
        System.out.println("Ejemplo Finalizado.");
    }
  
    public static void escribirExcel()
    {
        try
        {
            //Se crea el libro Excel
            WritableWorkbook workbook =
                    Workbook.createWorkbook(new File("ejemplo.xls")); 
  
            //Se crea una nueva hoja dentro del libro
            WritableSheet sheet =
                    workbook.createSheet("HojaEjemplo", 0); 
  
            //Creamos celdas de varios tipos
            sheet.addCell(new jxl.write.Number(0, 0, 1));
            sheet.addCell(new jxl.write.Number(1, 0, 1.2));
            sheet.addCell(new jxl.write.Label(2, 0, "ejemplo"));
            sheet.addCell(new jxl.write.Boolean(3,0,true)); 
  
            //Creamos una celda de tipo fecha y la mostramos
            //indicando un patón de formato
            DateFormat customDateFormat =
                    new DateFormat ("d/m/yy h:mm"); 
  
            WritableCellFormat dateFormat =
                    new WritableCellFormat (customDateFormat); 
  
            sheet.addCell(new jxl.write.DateTime(4, 0, new Date(),
dateFormat));
  
            //Escribimos los resultados al fichero Excel
            workbook.write();
            workbook.close(); 
  
            leerExcel();
  
            System.out.println("Ejemplo finalizado.");
        }
        catch (IOException ex)
        {
            System.out.println("Error al crear el fichero.");
        }
        catch (WriteException ex)
        {
            System.out.println("Error al escribir el fichero.");
        }
    }
  
    public static void leerExcel()
    {
        try
        {
            //Se abre el fichero Excel
            Workbook workbook = Workbook.getWorkbook(new
File("ejemplo.xls")); 
  
            //Se obtiene la primera hoja
            Sheet sheet = workbook.getSheet(0); 
  
            //Se leen las primeras 5 celdas
            for(int i=0; i<5; i++)
            {
                //Se obtiene la celda i-esima
                Cell cell = sheet.getCell(i,0);
  
                //Se imprime en pantalla la celda según su tipo
                if (cell.getType() == CellType.NUMBER)
                {
                    System.out.println("Número: " +
((NumberCell)cell).getValue());
                }
                else if (cell.getType() == CellType.LABEL)
                {
                    System.out.println("String: " +
((LabelCell)cell).getString());
                }
                else if (cell.getType() == CellType.BOOLEAN)
                {
                    System.out.println("Boolean: " +
((BooleanCell)cell).getValue());
                }
                else if (cell.getType() == CellType.DATE)
                {
                    System.out.println("Fecha: " +
((DateCell)cell).getDate());
                }
            }
        }
        catch (Exception ex)
        {
            System.out.println("Error!");
        }
    }
}

import java.io.FileOutputStream;
import java.io.OutputStream;

import jxl.*;
// Importamos la libreria JXL del
// archivo descargado
import jxl.write.*;
import jxl.write.Number;

/*
 * DEFINICION DE LA ESTRUCUTURA
 *
 * Workbook: Libro
 * |
 * |
 * |----> Sheets: Hojas de Calculo
 * |
 * |
 * |----->Cells: Celdas*/

public class EscribirXLS {

public static void main(String[] args) throws Exception {


EscribirXLS x = new EscribirXLS();
x.escribir();
}

private void escribir() throws Exception {


OutputStream salida = new FileOutputStream("Archivo.xls");
// Creamos el archivo
WritableWorkbook w = Workbook.createWorkbook(salida);
// Creamo un archivo
WritableSheet s = w.createSheet("Ang3r 1", 0);
// Creamos una hoja de calculo
/*
         * Hay tres tipos de datos que maneja la libreria
         * Label = texto
         * Numbre = numerico
         * Date = fecha
         * */
Label texto = new Label(0,0,"Celda A1");
// Creamos un texto : Celda A1
Number numero = new Number (1,0,2);
// Creamos un numero : 2
s.addCell(texto);
s.addCell(numero);
// Adicionamos las celdas al libro
w.write();
// escribimos
w.close();
}
}

 
Leer de XLS

import java.io.File;

import jxl.*;
//Importamos la libreria JXL del
//archivo descargado

public class LeerXLS {


public static void main(String[] args) throws Exception {
LeerXLS m = new LeerXLS();
m.leer();
}

private void leer() throws Exception {


Workbook w = Workbook.getWorkbook(new File ("Archivo.xls"));
// Obtenemos el archivo XLS
Sheet s = w.getSheet(0);
// Otenemos la primera hoja
Cell a1 = s.getCell(0,0);
// c f
Cell b1 = s.getCell(2,1);
// c f
if (a1.getType()==CellType.LABEL){
System.out.println(a1.getContents()+" Es un LABEL");
}
if (a1.getType()== CellType.NUMBER){
System.out.println(a1.getContents()+" Es un NUMBER");
}

}
}

import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
/**
* @author JocLuis
*/
public class NewClass {
public static void main(String[] args) throws IOException, BiffException {
//ruta de la hoja del calculo
Workbook workbook = Workbook.getWorkbook(new File("c://Libro1.xls"));
Sheet sheet = workbook.getSheet(0);//Elegimos la primera hoja
Cell celdaCurso = null;//inicializo el objeto que leerá el valor de la
celda
String valorCeldaCurso=null;
celdaCurso= sheet.getCell(7,1);//celda de la columna 7 y fila 1
valorCeldaCurso= celdaCurso.getContents();//obteniendo valor
System.out.println(valorCeldaCurso);
workbook.close();
}
}

import java.io.File;
import java.io.IOException;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class FirstJExcelExample {

public static void main(String[] args) {


WritableWorkbook workbook;
try {
workbook = Workbook.createWorkbook(new File("myfile.xls"));
WritableSheet sheet = workbook.createSheet("First Sheet", 0);
Label label = new Label(0, 2, "R4R JExcel API Example");
sheet.addCell(label);
workbook.write();
workbook.close();

} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Você também pode gostar