Escribir un Excel con JExcel
Liberias que utilizaimport 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.
import org.apache.poi.hssf.usermodel.
import org.apache.poi.hssf.usermodel.
import org.apache.poi.hssf.usermodel.
import org.apache.poi.hssf.usermodel.
import org.apache.poi.hssf.usermodel.
import org.apache.poi.poifs.
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).
row.createCell((short)1).
row.createCell((short)2).
row.createCell((short)3).
//Creamos una celda de tipo fecha y la mostramos
//indicando un patrón de formato
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
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.
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((
fuente.setFontName(fuente.
fuente.setBoldweight(HSSFFont.
// Luego creamos el objeto que se encargará de aplicar el estilo a la celda
HSSFCellStyle estiloCelda = objLibro.createCellStyle();
estiloCelda.setWrapText(true);
estiloCelda.setAlignment(
estiloCelda.
estiloCelda.setFont(fuente);
// También, podemos establecer bordes...
estiloCelda.setBorderBottom(
estiloCelda.
estiloCelda.setBorderLeft(
estiloCelda.
estiloCelda.setBorderRight(
estiloCelda.
estiloCelda.setBorderTop(
estiloCelda.setTopBorderColor(
// Establecemos el tipo de sombreado de nuestra celda
estiloCelda.
estiloCelda.setFillPattern(
// 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(
//celda.setCellType(HSSFCell.
// Finalmente, establecemos el valor
//celda.setCellValue("Un valor");
}
}else{
for(int j =0;j<4; j++){
HSSFCell celda = fila.createCell((short)j);
celda.setCellStyle(
celda.setCellType(HSSFCell.
// 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.
//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.");
}
}
}
WstanalPprovzoOlathe Nathan White https://wakelet.com/wake/kHn44YcrzPERyDF5Yo6XL
ResponderEliminardiaperreno