lunes, 22 de junio de 2009

Crear Excel desde Java

Introducción
POI consiste en APIs para manipular varios formatos de ficheros basados en el formato de Documento Compuesto OLE 2 de Microsoft, utilizando Java puro. En concreto, se pueden leer y escribir ficheros MS Excel utilizando Java.

Voy a poner un ejemplo que yo tuve que hacer:

public class Prueba(){

public String actionExportarExcel(){
ExportarUtils exportar= ExportarUtils.getInstance();
Vector v= new Vector();
// cabecera del excel
v.addElement("Cabecera1, cabecera2,....");
v.addElement(dato1, dato2,dato3,........);

// Generar el fichero
try {
exportar.crearExcel(v, "Titulo", "nombreFichero.xls");
} catch (Exception e) {
log.debug(e.getMessage());
}
return null;
}
}//fin de clase

//Clase para la preparacion del fichero Excel

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.StringTokenizer;
import java.util.Vector;
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;



public class ExportarUtils {
private ExportarUtils() {
}

public static ExportarUtils getInstance() {
if (singleton == null) {
singleton=new ExportarUtils();
}
return singleton;
}

public static void createCell(HSSFRow row, short i, String value, HSSFCellStyle style) {
HSSFCell cell = row.createCell(i);
value = value+" ";
cell.setCellValue(value);
// si no hay estilo, no se aplica
if (style != null)
cell.setCellStyle(style);
}

public void crearExcel(Vector v, String namesheet, String filename)
throws Exception {
try {
workbook = new HSSFWorkbook();
HSSFSheet sheet=workbook.createSheet("Nueva Hoja");
int filas = v.size();
for (int i = 0; i < filas; i++) {
String fila = (String) v.elementAt(i);
StringTokenizer st = new StringTokenizer(fila, ",");
HSSFRow row = sheet.createRow((short) i);
int j = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken();
// para la cabecera, la primera fila, aplicamos un estilo (negrita y color de fondo azul)
if (i == 0) {
HSSFCellStyle style = workbook.createCellStyle();
//style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex()); );

style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Courier New");
font.setItalic(true);
// font.setStrikeout(true);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//font.setColor(Short.parseShort("#ffffff"));
style.setFont(font);
createCell(row, (short)j, token, style);
} else
createCell(row, (short)j, token, null);

j = j + 1;

}

}

// Asignar automaticamente el tamaño de las celdas en funcion del contenido
//for (int i = 0; i < filas; i++) {
sheet.setDefaultColumnWidth((short) 55);
// }

// Escribir el fichero.
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();

} catch (Exception e)
{
e.printStackTrace();
}
}


Aui en este enlace bien mejor explicado POI