Ir al contenido principal

Java export Excel JExcel - POI

Escribir un Excel con JExcel

Liberias que utiliza
import java.io.File;
import java.util.Date;
import jxl.*;
import jxl.write.*;

//Declaro la variable
WritableWorkbook workbook = Workbook.createWorkbook(new File("output.xls"));

//Creo una hoja en el workbook generado
WritableSheet sheet = workbook.createSheet("First Sheet", 0);

//Ahora solo queda agregar información a las celdas.

Label label = new Label(0, 2, "A label record");
sheet.addCell(label);

Number number = new Number(3, 4, 3.1459);
sheet.addCell(number);

// Luego que todas las celdas estan cargadas guardamos el workbook
workbook.write();
workbook.close();

Formateo de datos


Formato en celdas

WritableFont arial10font = new WritableFont(WritableFont.ARIAL, 10);
WritableCellFormat arial10format = new WritableCellFormat (arial10font);

Label label2 = new Label(1,0, "Arial 10 point label", arial10format);
sheet.addCell(label2);

Formatear numeros

WritableCellFormat integerFormat = new WritableCellFormat (NumberFormats.INTEGER);
Number number2 = new Number(0, 4, 3.141519, integerFormat);
sheet.addCell(number2);

WritableCellFormat floatFormat = new WritableCellFormat (NumberFormats.FLOAT);
Number number3 = new Number(1, 4, 3.141519, floatFormat);
sheet.addCell(number3);

Agregar mascaras

NumberFormat fivedps = new NumberFormat("#.#####");
WritableCellFormat fivedpsFormat = new WritableCellFormat(fivedps);
Number number4 = new Number(2, 4, 3.141519, fivedpsFormat);
sheet.addCell(number4);

Formateamos fechas

Date now = Calendar.getInstance().getTime();
DateFormat customDateFormat = new DateFormat ("dd MMM yyyy hh:mm:ss");
WritableCellFormat dateFormat = new WritableCellFormat (customDateFormat);
DateTime dateCell = new DateTime(0, 6, now, dateFormat);
sheet.addCell(dateCell);


- Exportar Excel con POI

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.
HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class DemoPOI {

public static void main(String[] args){
escribirExcel();
// leerExcel();
System.out.println("Ejemplo Finalizado.");
}

public static void escribirExcel(){

try{
/*
//Se crea el libro Excel
HSSFWorkbook wb = new HSSFWorkbook();
//Se crea una nueva hoja dentro del libro
HSSFSheet sheet = wb.createSheet("HojaEjemplo");
//Se crea una fila dentro de la hoja
HSSFRow row = sheet.createRow((short)0);
//Creamos celdas de varios tipos
row.createCell((short)0).setCellValue(1);
row.createCell((short)1).setCellValue(1.2);
row.createCell((short)2).setCellValue("ejemplo");
row.createCell((short)3).setCellValue(true);
//Creamos una celda de tipo fecha y la mostramos
//indicando un patrón de formato
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("d/m/yy h:mm"));
HSSFCell cell = row.createCell((short)4);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
//Escribimos los resultados a un fichero Excel
FileOutputStream fileOut = new FileOutputStream("C:/ejemplo.xls");
wb.write(fileOut);
fileOut.close();
*/

HSSFWorkbook objLibro = new HSSFWorkbook();

// Creo la hoja
HSSFSheet hoja1 = objLibro.createSheet("hoja 1");

// Proceso la información y genero el xls.



HSSFFont fuente = objLibro.createFont();
fuente.setFontHeightInPoints((short)11);
fuente.setFontName(fuente.FONT_ARIAL);
fuente.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

// Luego creamos el objeto que se encargará de aplicar el estilo a la celda
HSSFCellStyle estiloCelda = objLibro.createCellStyle();
estiloCelda.setWrapText(true);
estiloCelda.setAlignment(HSSFCellStyle. ALIGN_JUSTIFY);
estiloCelda.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
estiloCelda.setFont(fuente);

// También, podemos establecer bordes...
estiloCelda.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
estiloCelda.setBottomBorderColor((short)8);
estiloCelda.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
estiloCelda.setLeftBorderColor((short)8);
estiloCelda.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
estiloCelda.setRightBorderColor((short)8);
estiloCelda.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
estiloCelda.setTopBorderColor((short)8);

// Establecemos el tipo de sombreado de nuestra celda
estiloCelda.setFillForegroundColor((short)01);
estiloCelda.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

// Creamos la celda, aplicamos el estilo y definimos
// el tipo de dato que contendrá la celda
for(int i =0;i<10; i++){
HSSFRow fila = hoja1.createRow((short)i);
if(i==4 || i==8){
for(int j =0;j<4; j++){
HSSFCell celda = fila.createCell((short)j);
// celda.setCellStyle(estiloCelda);
//celda.setCellType(HSSFCell.CELL_TYPE_STRING);
// Finalmente, establecemos el valor
//celda.setCellValue("Un valor");
}
}else{
for(int j =0;j<4; j++){
HSSFCell celda = fila.createCell((short)j);
celda.setCellStyle(estiloCelda);
celda.setCellType(HSSFCell.CELL_TYPE_STRING);
// Finalmente, establecemos el valor
celda.setCellValue("Un valor");
}
}





}

// Volcamos la información a un archivo.
String strNombreArchivo = "C:/libro1.xls";
File objFile = new File(strNombreArchivo);
FileOutputStream archivoSalida = new FileOutputStream(objFile);
objLibro.write(archivoSalida);
archivoSalida.close();



}catch(IOException e){
System.out.println("Error al escribir el fichero.");
}
}

public static void leerExcel()
{
try
{
//Se abre el fichero Excel
POIFSFileSystem fs =
new POIFSFileSystem(
new FileInputStream("c:/ejemplo.xls"));

//Se obtiene el libro Excel
HSSFWorkbook wb = new HSSFWorkbook(fs);

//Se obtiene la primera hoja
HSSFSheet sheet = wb.getSheetAt(0);

//Se obtiene la primera fila de la hoja
HSSFRow row = sheet.getRow(0);

//Se leen las primeras 5 celdas
for(int i=0; i<5; i++)
{
//Se obtiene la celda i-esima
HSSFCell cell = row.getCell((short)i);

//Si la celda leida no está vacía
if (cell != null)
{
//Se imprime en pantalla la celda según su tipo
switch(cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:
System.out.println("Número: " + cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
System.out.println("String: " + cell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
System.out.println("Boolean: " + cell.getBooleanCellValue());
break;
default:
System.out.println("Default: " + cell.getDateCellValue());
break;
}
}
}
}
catch(IOException ex)
{
System.out.println("Error al leer el fichero.");
}
}
}

Comentarios

Publicar un comentario

Entradas populares de este blog

Debugging Remoto con Eclipse + WebSphere 7 + Maven

Tienes proyectos java en Maven y no puedes ubicar bugs fácilmente a falta de junit. Sin embargo, existe la alternativa de debugear la aplicación web a través de Java Debugger (jdb). Aquí les muestro una guía de como hacer un debug remoto de la aplicación web en Eclipse y WebSphere 7 a través de Java Debugger (JDB). Eclipse <----> Java Debugger (jdb) <----> WebSphere 7 1. Habilitar el WebSphere en modo Debug. Para esto seguir los siguientes pasos:  1. Servers –> Server Types –> WebSphere application servers 2. Under Server Infrastructure section –> expandir Java and Process Management –> Process definition 3. dentro de la seccion Additional Properties –> click Java Virtual Machine 4. clic en el check “Debug Mode” 5. En texbox Debug arguments, poner este valor:  -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8888 6. Reiniciar el servidor WebSphere. Ahora, WebSphere se inicia en modo debug, y escuchando en el pu

Java POI HSSFCell : añadir comentario en una celda

POI HSSFComment: Una manera simple de añadir un comentario en una celda de excel usando el metodo cell.setCellComment(). public class ExcelTools { public static void main(String[] args){ //escribirExcel(); //leerExcel(); validarValoresDuplicadosLista(); System.out.println("Ejemplo Finalizado."); } public static void escribirExcel(){ try{ //Se crea el libro Excel HSSFWorkbook wb = new HSSFWorkbook(); //Se crea una nueva hoja dentro del libro HSSFSheet sheet = wb.createSheet("HojaEjemplo"); //Se crea una fila dentro de la hoja HSSFRow row = sheet.createRow((short)0); HSSFPatriarch patr = sheet.createDrawingPatriarch(); //Creamos celdas de varios tipos row.createCell((short)0).setCellValue(1); row.createCell((short)1).setCellValue(1.2); row.createCell((short)2).setCellValue("ejemplo&

DB2 Error SQL20054N

Ejecutando un alter table me da el  siguiente error: db2 "ALTER TABLE PRG_REC.ESTIMADO_OBJETIVO DROP COLUMN VTA_OBJ_CAMP_FALTA_EXTRANJERA"; Error:  [db2inst1@ibmdb2test]:/home/db2inst1/1223/REQ1223/rollback$ db2 "ALTER TABLE PRG_REC.ESTIMADO_OBJETIVO DROP COLUMN VTA_OBJ_CAMP_FALTA_EXTRANJERA"; DB21034E  The command was processed as an SQL statement because it was not a valid Command Line Processor command.  During SQL processing it returned: SQL20054N  The table "PRG_REC.ESTIMADO_OBJETIVO" is in an invalid state for the operation.  Reason code="23" .  SQLSTATE=55019 Segun IBM la descripcion del error: SQL20054N:  La tabla   nombre-tabla   está en un estado no válido para la operación. Código de razón= código-razón . 23 Se ha realizado el número máximo de modificaciones recomendadas de REORG. Se permite un máximo de tres modificaciones recomendadas de REORG en una tabla antes de que se deba realizar reorg, para actualizar las fila