Estimados, tengo una aplicación que hice y quiero exportar a excel a partir de un arraylist, la cosa es que me crea el excel, lo bajo me abre con errores, se reinicia el office y automaticamente me lo repara y me lo abre bien, pero la cosa es que quiero que abra sin errores, adjunto metodo
public void postProcessXLS() {
if (movimientos == null) {
cargaTablaDinamica();
}
System.out.println("Entre al metodo postProcess");
// HSSFWorkbook wb = (HSSFWorkbook) document;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Movimientos");
// wb.setSheetName(0, "Ejemplo"); //Asignamos nombre a la hoja de calculo
// HSSFRow header = sheet.createRow(0);
HSSFRow fila = null;
//HSSFRow fila = sheet.getRow(1);
/* Llenar las cosas*/
for (int i = 0; i < movimientos.size(); i++) {
fila = sheet.createRow(i);
for (int j = 0; j < 5; j++) {
fila.createCell(j);
}
/* fila.getCell(0).setCellValue("Fecha");
fila.getCell(1).setCellValue("Descripcion");
fila.getCell(2).setCellValue("Serie");
fila.getCell(3).setCellValue("Monto");
fila.getCell(4).setCellValue("Saldo");*/
fila.getCell(0).setCellValue(movimientos.get(i).getFecha().toLocaleString());
fila.getCell(1).setCellValue(movimientos.get(i).getDescripcion());
fila.getCell(2).setCellValue(movimientos.get(i).getSerie());
fila.getCell(3).setCellValue((double)movimientos.get(i).getMonto());
fila.getCell(4).setCellValue((double)movimientos.get(i).getSaldo());
}
/*
HSSFCellStyle cellStyle = wb.createCellStyle(); //estilo para la primera fila
HSSFCellStyle estilo = wb.createCellStyle(); // otro estilo para la segunda fila
HSSFCellStyle estilo2 = wb.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);// color Naranjo
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
estilo.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);//estilo para la segunda fila
estilo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
estilo2.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
estilo2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);*/
System.out.println("El documento pesa : " + wb.getBytes().length);
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
// response.resetBuffer();
response.setContentLength(wb.getBytes().length);
response.setContentType("application/vnd.ms-excel");
// System.out.println("RespuestA ? : " + response.getOutputStream().toString());
// ServletOutputStream out = response.getOutputStream();
ServletOutputStream out = response.getOutputStream();
out.write(wb.getBytes());
// out.flush();
out.close();
// baosPDF.flush();
// baosPDF.close();
facesContext.responseComplete();
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
// estilo2.setFont(HSSFFont.);
// Este ciclo pintara todas las celdas de la fila 1
/* for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
//header.getPhysicalNumberOfCells obtiene el numero de celdas de la fila
HSSFCell cell = header.getCell(i);
cell.setCellStyle(cellStyle);//le asigna el estilo a cada celda de la primera fila
sheet.autoSizeColumn((short) i); // Deja las columnas en un tamaño que se vea todo bien.
System.out.println("Numero : " + i);//Cantidad de celdas rellenadas
}
// pruebas con las columnas
// Pintara toda la columna 3 de todas las filas.
for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
HSSFRow fila = sheet.getRow(i);
HSSFCell cell = fila.getCell(2);
cell.setCellStyle(estilo2);
}
/*Este ciclo pintara todas las celdas de la fila 2
for (int i = 0; i < fila.getPhysicalNumberOfCells(); i++) {
HSSFCell cell = fila.getCell(i);
cell.setCellStyle(estilo);
}*/
}
Se agradece cualquier ayuda, sugerencia, gracias de antemano.
Disculpen el doble post, si editaba el mensaje el geshi se me iba a la shit, asi que publico aqui, debo señalar que al recuperar el excel generado me sale este mensaje al mostrar los errores.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>error027520_01.xml</logFileName>
<summary>Se han detectado errores en el archivo "C:\Documents and Settings\Administrador\Mis documentos\Downloads\6tff5e5tfg.xls"</summary>
- <additionalInfo>
<info>Excel ha intentado recuperar las fórmulas y los valores de las celdas, pero algunos datos pueden haberse perdido.</info>
</additionalInfo>
</recoveryLog>
No uso formulas, solo lo que ven ustedes en el codigo, gracias de antemano y disculpen nuevamente.(Por romper la regla del doble post)
Ok señores, recién pude solucionar el problema, la cosa es que lo hice todo desde cero nuevamente y nunca supe donde estaba el problema :xD, disculpen los post seguidos pero si edito codigo el geshi muere, no se porque , los espacios se ven como asteriscos, pero acá colocare la solución, saludos.
public void exportarExcel() {
if (movimientos == null) {// Cargamos el ArrayList si esta nulo
cargaTablaDinamica();
}
HSSFWorkbook workbook = new HSSFWorkbook();//Creamos el libro excel
/*Creamos la hoja de Excel llamada "Movimientos"*/
HSSFSheet sheet = workbook.createSheet("Movimientos");
/* Creamos la primera fila para colocar los titulos correspondientes a
* cada columna*/
HSSFRow header = sheet.createRow(0);
HSSFRow fila = null;
for (int i = 0; i < movimientos.size(); i++) {
/* Creamos las filas segun la cantidad de datos que contiene
* el arraylist
*/
fila = sheet.createRow(i + 1);
/* Creamos las celdas, se sabe que son 5*/
for (int j = 0; j < 5; j++) {
fila.createCell(j);
}
/* Asignamos los titulos a la primera fila,
* en cada celda correspondiente */
header.createCell(0).setCellValue(new HSSFRichTextString("Fecha"));
header.createCell(1).setCellValue(new HSSFRichTextString("Descripcion"));
header.createCell(2).setCellValue(new HSSFRichTextString("Serie"));
header.createCell(3).setCellValue(new HSSFRichTextString("Monto"));
header.createCell(4).setCellValue(new HSSFRichTextString("Saldo"));
/* Seteamos los valores a cada celda correspondiente */
fila.getCell(0).setCellValue("" + movimientos.get(i).getFecha().toLocaleString());
fila.getCell(1).setCellValue(new HSSFRichTextString(movimientos.get(i).getDescripcion()));
fila.getCell(2).setCellValue(new HSSFRichTextString(movimientos.get(i).getSerie()));
fila.getCell(3).setCellValue(Integer.parseInt(String.valueOf(movimientos.get(i).getMonto()).replace(".0", "")));
fila.getCell(4).setCellValue(Integer.parseInt(String.valueOf(movimientos.get(i).getSaldo()).replace(".0", "")));
/*Modificamos el tamaño de las celdas segun el contenido de las celdas*/
sheet.autoSizeColumn((short) (i));
}
sheet.autoSizeColumn((short) (0));//Arreglamos el tamaño al header
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
/* Le asignamos el tipo de fichero que abrirá*/
response.setContentType("application/vnd.ms-excel");
/* El nombre que recibira el archivo a descargar */
response.setHeader("Content-disposition", "attachment; filename=movimientos.xls");
ServletOutputStream out = response.getOutputStream();
/*Escribimos el fichero al out */
workbook.write(out);
out.close(); // Cerramos el streaming
} catch (Exception e) {
e.printStackTrace();
}
}