Example usage for org.apache.poi.ss.usermodel Workbook createSheet

List of usage examples for org.apache.poi.ss.usermodel Workbook createSheet

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Workbook createSheet.

Prototype

Sheet createSheet();

Source Link

Document

Create a Sheet for this Workbook, adds it to the sheets and returns the high level representation.

Usage

From source file:com.helger.poi.excel.ExcelReadUtilsTest.java

License:Apache License

@Test
public void testGetCellValueObject() {
    for (final EExcelVersion eVersion : EExcelVersion.values()) {
        final Workbook aWB = eVersion.createWorkbook();
        final Sheet aSheet = aWB.createSheet();
        final Row aRow = aSheet.createRow(0);
        final Cell aCell = aRow.createCell(0);

        // boolean
        aCell.setCellValue(true);//  w  w  w  . j a v  a  2 s. c o  m
        assertEquals(Boolean.TRUE, ExcelReadUtils.getCellValueObject(aCell));

        // int
        aCell.setCellValue(4711);
        assertEquals(Integer.valueOf(4711), ExcelReadUtils.getCellValueObject(aCell));

        // long
        aCell.setCellValue(Long.MAX_VALUE);
        assertEquals(Long.valueOf(Long.MAX_VALUE), ExcelReadUtils.getCellValueObject(aCell));

        // double
        aCell.setCellValue(3.14159);
        assertEquals(Double.valueOf(3.14159), ExcelReadUtils.getCellValueObject(aCell));

        // String
        aCell.setCellValue("Anyhow");
        assertEquals("Anyhow", ExcelReadUtils.getCellValueObject(aCell));

        // Rich text string
        final Font aFont = aWB.createFont();
        aFont.setItalic(true);
        final RichTextString aRTS = eVersion.createRichText("Anyhow");
        aRTS.applyFont(1, 3, aFont);
        aCell.setCellValue(aRTS);
        assertEquals("Anyhow", ExcelReadUtils.getCellValueObject(aCell));
    }
}

From source file:com.hotaviano.tableexporter.xls.XLSExporter.java

License:Open Source License

@Override
public byte[] export(String htmlTable) throws DocumentException {
    Document document = createDocument(htmlTable);

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();

    CellStyle headerStyle = createHeaderStyle(wb);

    Element theadTr = document.getRootElement().getChild("thead").getChildren().get(0);
    Element tbody = document.getRootElement().getChild("tbody");

    createHeader(sheet.createRow(0), theadTr, headerStyle);
    createBody(sheet, tbody);/*from   w  ww. j a  v a 2s . c om*/

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        wb.write(out);
    } catch (IOException ex) {
        throw new DocumentException(ex);
    }

    return out.toByteArray();
}

From source file:com.iqtb.validacion.managedbean.MbCfdisEmitidos.java

private boolean generarReporte(List<Cfdis> lista) {
    logger.info(usuario.getUserid() + ". Inicia Generar Reporte Excel");
    boolean reporte = false;
    try {// w  w w .j  a  v  a2 s  . c  o m
        String ruta = "/work/iqtb/validacionfiles/reportes/" + empresa.getRfc() + "/" + usuario.getUserid()
                + "/";
        DateFormat df = new SimpleDateFormat("ddMMyyyy");
        Date today = new Date();
        String reportDate = df.format(today);
        String strNombreReporte = "EmitidosReporte_" + reportDate + ".xls";
        File dir = new File(ruta);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Workbook libro = new HSSFWorkbook();
        FileOutputStream archivo = new FileOutputStream(ruta + strNombreReporte);
        logger.info(usuario.getUserid() + ". Archivo creado " + ruta + strNombreReporte);
        Sheet hoja = libro.createSheet();
        int aux = 1;
        for (Cfdis var : lista) {
            if (aux == 1) {
                logger.info("Inicia escritura de cabecera");
                Row fila = hoja.createRow((int) 0);
                Cell a = fila.createCell((int) 0);
                a.setCellValue("Sucursal");
                Cell b = fila.createCell((int) 1);
                b.setCellValue("RFC Socio Comercial");
                Cell c = fila.createCell((int) 2);
                c.setCellValue("Serie");
                Cell d = fila.createCell((int) 3);
                d.setCellValue("Folio");
                Cell e = fila.createCell((int) 4);
                e.setCellValue("UUID");
                Cell f = fila.createCell((int) 5);
                f.setCellValue("Fecha");
                Cell g = fila.createCell((int) 6);
                g.setCellValue("Numero Aprobacin");
                Cell h = fila.createCell((int) 7);
                h.setCellValue("Ao Aprobacin");
                Cell i = fila.createCell((int) 8);
                i.setCellValue("SubTotal");
                Cell j = fila.createCell((int) 9);
                j.setCellValue("Descuento");
                Cell k = fila.createCell((int) 10);
                k.setCellValue("Total");
                Cell l = fila.createCell((int) 11);
                l.setCellValue("Tipo Moneda");
                Cell m = fila.createCell((int) 12);
                m.setCellValue("Tipo Cambio");
                Cell n = fila.createCell((int) 13);
                n.setCellValue("IVA");
                Cell nn = fila.createCell((int) 14);
                nn.setCellValue("Estado Fiscal");
                Cell o = fila.createCell((int) 15);
                o.setCellValue("Estado");
                Cell p = fila.createCell((int) 16);
                p.setCellValue("Fecha Cancelacin");
                Cell q = fila.createCell((int) 17);
                q.setCellValue("Fecha Modificacin");
                Cell r = fila.createCell((int) 18);
                r.setCellValue("Estado Impresin");
                Cell s = fila.createCell((int) 19);
                s.setCellValue("Pedimento");
                Cell t = fila.createCell((int) 20);
                t.setCellValue("Fecha Pedimento");
                Cell u = fila.createCell((int) 21);
                u.setCellValue("Aduana");
                Cell v = fila.createCell((int) 22);
                v.setCellValue("Fecha Generacin");
                Cell w = fila.createCell((int) 23);
                w.setCellValue("Estado Contable");
                Cell x = fila.createCell((int) 24);
                x.setCellValue("Fecha Vencimineto");
                Cell y = fila.createCell((int) 25);
                y.setCellValue("RFC Emisor");
                Cell z = fila.createCell((int) 26);
                z.setCellValue("RFC Receptor");
                Cell a1 = fila.createCell((int) 27);
                a1.setCellValue("Cadena Original");
                logger.info("Termina escritura de cabecera");
            }
            Row fila1 = hoja.createRow((int) aux);
            sucursal = daoSucursales.getSucursalByHql(
                    "select new Sucursales(idSucursal, nombre) from Sucursales where idSucursal = "
                            + var.getIdSucursal());
            Cell a = fila1.createCell((int) 0);
            if (sucursal != null) {
                a.setCellValue(sucursal.getNombre());
            } else {
                a.setCellValue(var.getIdSucursal());
            }
            socioComercial = null;
            socioComercial = daoSociosComerciales.getSocioByHql(
                    "select new SociosComerciales(idSocioComercial, rfc) from SociosComerciales where idSocioComercial = "
                            + var.getIdSocioComercial());
            Cell b = fila1.createCell((int) 1);
            if (socioComercial != null) {
                b.setCellValue(socioComercial.getRfc());
            } else {
                b.setCellValue(var.getIdSocioComercial());
            }
            Cell c = fila1.createCell((int) 2);
            c.setCellValue(var.getSerie());
            Cell d = fila1.createCell((int) 3);
            if (var.getFolio() != null) {
                d.setCellValue(var.getFolio());
            } else {
                d.setCellValue("");
            }
            Cell e = fila1.createCell((int) 4);
            e.setCellValue(var.getUuid());
            Cell f = fila1.createCell((int) 5);
            if (var.getFecha() != null) {
                f.setCellValue(var.getFecha().toString());
            } else {
                f.setCellValue("");
            }
            Cell g = fila1.createCell((int) 6);
            if (var.getNumeroAprobacion() != null) {
                g.setCellValue(var.getNumeroAprobacion());
            } else {
                g.setCellValue("");
            }
            Cell h = fila1.createCell((int) 7);
            if (var.getNumeroAprobacion() != null) {
                h.setCellValue(var.getAnioAprobacion());
            } else {
                h.setCellValue("");
            }
            Cell i = fila1.createCell((int) 8);
            if (var.getSubtotal() != null) {
                i.setCellValue(var.getSubtotal().toString());
            } else {
                i.setCellValue("");
            }
            Cell j = fila1.createCell((int) 9);
            if (var.getDescuento() != null) {
                j.setCellValue(var.getDescuento().toString());
            } else {
                j.setCellValue("");
            }
            Cell k = fila1.createCell((int) 10);
            if (var.getTotal() != null) {
                k.setCellValue(var.getTotal().toString());
            } else {
                k.setCellValue("");
            }
            Cell l = fila1.createCell((int) 11);
            l.setCellValue(var.getTipoMoneda());
            Cell m = fila1.createCell((int) 12);
            if (var.getTipoCambio() != null) {
                m.setCellValue(var.getTipoCambio().toString());
            } else {
                m.setCellValue("");
            }
            Cell n = fila1.createCell((int) 13);
            if (var.getIva() != null) {
                n.setCellValue(var.getIva().toString());
            } else {
                n.setCellValue("");
            }
            Cell nn = fila1.createCell((int) 14);
            nn.setCellValue(var.getEstadoFiscal());
            Cell o = fila1.createCell((int) 15);
            o.setCellValue(var.getEstado());
            Cell p = fila1.createCell((int) 16);
            if (var.getFechaVencimiento() != null) {
                p.setCellValue(var.getFechaCancelacion().toString());
            } else {
                p.setCellValue("");
            }
            Cell q = fila1.createCell((int) 17);
            if (var.getFechaVencimiento() != null) {
                q.setCellValue(var.getFechaModificacion().toString());
            } else {
                q.setCellValue("");
            }
            q.setCellValue(var.getFechaModificacion().toString());
            Cell r = fila1.createCell((int) 18);
            r.setCellValue(var.getEstadoImpresion());
            Cell s = fila1.createCell((int) 19);
            s.setCellValue(var.getPedimento());
            Cell t = fila1.createCell((int) 20);
            t.setCellValue(var.getFechaPedimento());
            Cell u = fila1.createCell((int) 21);
            u.setCellValue(var.getAduana());
            Cell v = fila1.createCell((int) 22);
            if (var.getGenerationDate() != null) {
                v.setCellValue(var.getGenerationDate().toString());
            } else {
                v.setCellValue("");
            }
            Cell w = fila1.createCell((int) 23);
            w.setCellValue(var.getEstadoContable());
            Cell x = fila1.createCell((int) 24);
            if (var.getFechaVencimiento() != null) {
                x.setCellValue(var.getFechaVencimiento().toString());
            } else {
                x.setCellValue("");
            }
            Cell y = fila1.createCell((int) 25);
            y.setCellValue(var.getRfcEmisor());
            Cell z = fila1.createCell((int) 26);
            z.setCellValue(var.getRfcReceptor());
            Cell a1 = fila1.createCell((int) 27);
            a1.setCellValue(var.getCadenaOriginal());
            if (aux == 50000) {
                aux = 1;
                hoja = libro.createSheet();
                logger.debug("se ha creado una nueva hoja");
            } else {
                aux++;
            }
        }
        logger.info(usuario.getUserid() + ". Termina escritura de las filas");
        byte[] bytes = new byte[1024];
        int read = 0;
        libro.write(archivo);
        logger.info(usuario.getUserid() + ". Termina de escribir Reporte de excel");
        archivo.close();
        logger.info(usuario.getUserid() + ". Reporte Generado en la ruta " + ruta + strNombreReporte);
        File ficheroXLS = new File(ruta + strNombreReporte);
        FileInputStream fis = new FileInputStream(ficheroXLS);
        FacesContext ctx = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
        response.setContentType("application/vnd.ms-excel");
        String disposition = "attachment; fileName=" + strNombreReporte;
        response.setHeader("Content-Disposition", disposition);
        ServletOutputStream out = response.getOutputStream();
        while ((read = fis.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
        ctx.responseComplete();
        reporte = true;

        logger.info(usuario.getUserid() + ". Termina Generar Reporte Excel");
        new ManejoArchivos().eliminar(ruta);
    } catch (IOException e) {
        descBitacora = "[CFDI_EMITIDO - generarReporte] " + usuario.getUserid() + " IOException ERROR "
                + e.getMessage();
        registrarBitacora(usuario.getIdUsuario(), null, empresa.getIdEmpresa(), descBitacora,
                BitacoraTipo.ERROR.name());
        logger.error(descBitacora);
    } catch (Exception ex) {
        descBitacora = "[CFDI_EMITIDO - generarReporte] " + usuario.getUserid() + " ERROR " + ex.getMessage();
        registrarBitacora(usuario.getIdUsuario(), null, empresa.getIdEmpresa(), descBitacora,
                BitacoraTipo.ERROR.name());
        logger.error(descBitacora);
    }
    return reporte;
}

From source file:com.iqtb.validacion.managedbean.MbCfdisRecibidos.java

private boolean generarReporte(List<CfdisRecibidos> lista) {
    logger.info("[CFDI_RECIBIDO - generarReporte] " + usuario.getUserid() + " Inicia Generar Reporte Excel");
    boolean reporte = false;
    try {//from ww  w.  j a  v a 2  s . c  o m
        String ruta = "/work/iqtb/validacionfiles/reportes/" + empresa.getRfc() + "/" + usuario.getUserid()
                + "/";
        DateFormat df = new SimpleDateFormat("ddMMyyyy");
        Date today = new Date();
        String reportDate = df.format(today);
        String strNombreReporte = "Reporte_" + reportDate + ".xls";
        File dir = new File(ruta);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Workbook libro = new HSSFWorkbook();
        FileOutputStream archivo = new FileOutputStream(ruta + strNombreReporte);
        logger.info("[CFDI_RECIBIDO - generarReporte] " + usuario.getUserid() + " Archivo creado " + ruta
                + strNombreReporte);
        Sheet hoja = libro.createSheet();
        int y = 1;
        for (CfdisRecibidos var : lista) {
            if (y == 1) {
                logger.info("Inicia escritura de cabecera");
                Row fila = hoja.createRow((int) 0);
                Cell a = fila.createCell((int) 0);
                a.setCellValue("Fecha Emisin");
                Cell b = fila.createCell((int) 1);
                b.setCellValue("Serie");
                Cell c = fila.createCell((int) 2);
                c.setCellValue("Folio");
                Cell d = fila.createCell((int) 3);
                d.setCellValue("Fecha Recepcin");
                Cell e = fila.createCell((int) 4);
                e.setCellValue("RFC Socio Comercial");
                Cell f = fila.createCell((int) 5);
                f.setCellValue("Socio Comercial");
                Cell g = fila.createCell((int) 6);
                g.setCellValue("UUID");
                Cell h = fila.createCell((int) 7);
                h.setCellValue("Total");
                Cell i = fila.createCell((int) 8);
                i.setCellValue("Estado");
                Cell j = fila.createCell((int) 9);
                j.setCellValue("Warning");
                Cell k = fila.createCell((int) 10);
                k.setCellValue("Error");
                Cell l = fila.createCell((int) 11);
                l.setCellValue("Nmero Orden de Compra");
                Cell m = fila.createCell((int) 12);
                m.setCellValue("Total Orden de Compra");
                Cell n = fila.createCell((int) 13);
                n.setCellValue("Tipo de Moneda");
                Cell o = fila.createCell((int) 14);
                o.setCellValue("Entrada Almacn");
                Cell p = fila.createCell((int) 15);
                p.setCellValue("Control de Calidad");
                Cell q = fila.createCell((int) 16);
                q.setCellValue("Autorizacin");

                logger.info("Termina escritura de cabecera");
            }
            Row fila1 = hoja.createRow((int) y);
            Cell a = fila1.createCell((int) 0);
            a.setCellValue(var.getFecha().toString());
            Cell b = fila1.createCell((int) 1);
            b.setCellValue(var.getSerie());
            Cell c = fila1.createCell((int) 2);
            if (var.getFolio() == null) {
                c.setCellValue("");
            } else {
                c.setCellValue(var.getFolio());
            }
            Cell d = fila1.createCell((int) 3);
            d.setCellValue(var.getFechaRecepcion().toString());
            Cell e = fila1.createCell((int) 4);
            e.setCellValue(daoSociosComerciales.getRFCSociobyIdSocio(var.getIdSocioComercial()));
            Cell f = fila1.createCell((int) 5);
            f.setCellValue(daoSociosComerciales.getNombreSociobyIdSocio(var.getIdSocioComercial()));
            Cell g = fila1.createCell((int) 6);
            g.setCellValue(var.getUuid());
            Cell h = fila1.createCell((int) 7);
            h.setCellValue(var.getTotal().toString());
            Cell i = fila1.createCell((int) 8);
            i.setCellValue(var.getEstado());
            Cell j = fila1.createCell((int) 9);
            j.setCellValue(var.getTiposWarn());
            Cell k = fila1.createCell((int) 10);
            k.setCellValue(var.getError());
            Cell l = fila1.createCell((int) 11);
            if (var.getIdOrdenCompra() != null) {
                l.setCellValue(daoOrdenCompra.numOrdenCompraById(var.getIdOrdenCompra()));
            } else {
                l.setCellValue("");
            }
            Cell m = fila1.createCell((int) 12);
            if (var.getTotalOc() == null) {
                m.setCellValue("");
            } else {
                m.setCellValue(var.getTotalOc().toString());
            }
            Cell n = fila1.createCell((int) 13);
            n.setCellValue(var.getTipoMoneda());
            Cell o = fila1.createCell((int) 14);
            o.setCellValue(var.getEntradaAlmacen());
            Cell p = fila1.createCell((int) 15);
            p.setCellValue(var.getControlCalidad());
            Cell q = fila1.createCell((int) 16);
            q.setCellValue(var.getAutorizacion());
            if (y == 50000) {
                y = 1;
                hoja = libro.createSheet();
                logger.info("se ha creado una nueva hoja");
            } else {
                y++;
            }
        }
        logger.info(usuario.getUserid() + ". Termina escritura de las filas");
        byte[] bytes = new byte[1024];
        int read = 0;
        libro.write(archivo);
        logger.info(usuario.getUserid() + ". Termina de escribir Reporte de excel");
        archivo.close();
        logger.info(usuario.getUserid() + ". Reporte Generado en la ruta " + ruta + strNombreReporte);
        File ficheroXLS = new File(ruta + strNombreReporte);
        FileInputStream fis = new FileInputStream(ficheroXLS);
        FacesContext ctx = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
        response.setContentType("application/vnd.ms-excel");
        String disposition = "attachment; fileName=" + strNombreReporte;
        response.setHeader("Content-Disposition", disposition);
        ServletOutputStream out = response.getOutputStream();
        while ((read = fis.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
        ctx.responseComplete();
        reporte = true;
        descBitacora = "[CFDI_RECIBIDO - generarReporte] " + usuario.getUserid()
                + " Genero/Descargo Reporte Excel.";
        registrarBitacora(usuario.getIdUsuario(), null, empresa.getIdEmpresa(), descBitacora,
                BitacoraTipo.INFO.name());
        logger.info(descBitacora);
        manejorArchivos.eliminar(ruta);
    } catch (IOException e) {
        descBitacora = "[CFDI_RECIBIDO - generarReporte] " + usuario.getUserid() + " IOException ERROR "
                + e.getMessage();
        registrarBitacora(usuario.getIdUsuario(), null, empresa.getIdEmpresa(), descBitacora,
                BitacoraTipo.ERROR.name());
        logger.error(descBitacora);
    } catch (Exception ex) {
        descBitacora = "[CFDI_RECIBIDO - generarReporte] " + usuario.getUserid() + " ERROR " + ex.getMessage();
        registrarBitacora(usuario.getIdUsuario(), null, empresa.getIdEmpresa(), descBitacora,
                BitacoraTipo.ERROR.name());
        logger.error(descBitacora);
    }
    return reporte;
}

From source file:com.kovtun.WorkTimeMap.UI.TimeReport.java

private Workbook generateData() {
    Workbook book = new HSSFWorkbook();
    Sheet sheet = book.createSheet();
    int rowCount = 1;
    //? /*from   ww w .  j a  va  2s . c  o  m*/
    Row projRow = sheet.createRow(0);
    Cell prjName = projRow.createCell(0);
    prjName.setCellValue(project.getName());

    for (ReportUser user : users) {
        //?
        Row row = sheet.createRow(rowCount);

        Cell nullCell = row.createCell(0);
        nullCell.setCellValue(" ");

        Row nameRow = sheet.createRow(rowCount);

        Cell nameCell = nameRow.createCell(0);
        nameCell.setCellValue(user.getFio());

        Cell userAllTimeCell = nameRow.createCell(1);
        userAllTimeCell.setCellValue((user.getAllTime() / (1000 * 60)) / 60 + " . "
                + (user.getAllTime() / (1000 * 60) % 60 + " ."));

        //
        rowCount++;
        Row aRow = sheet.createRow(rowCount);

        Cell aNumber = aRow.createCell(0);
        aNumber.setCellValue("");

        Cell aName = aRow.createCell(1);
        aName.setCellValue("?");

        Cell aDescription = aRow.createCell(2);
        aDescription.setCellValue("?");

        Cell aComment = aRow.createCell(3);
        aComment.setCellValue("");

        Cell aDate = aRow.createCell(4);
        aDate.setCellValue(" ");

        Cell aTime = aRow.createCell(5);
        aTime.setCellValue("? ?");

        //   
        List<Action> list = user.getActions();
        int k = 1;
        for (Action action : list) {
            rowCount++;
            Row actionRow = sheet.createRow(rowCount);

            Cell actionNumber = actionRow.createCell(0);
            actionNumber.setCellValue(k);
            k++;

            Cell actionName = actionRow.createCell(1);
            actionName.setCellValue(action.getName());

            Cell actionDescription = actionRow.createCell(2);
            actionDescription.setCellValue(action.getDescription());

            Cell actionComment = actionRow.createCell(3);
            actionComment.setCellValue(action.getComment());

            Cell actionDate = actionRow.createCell(4);
            actionDate.setCellValue(action.getStringDate());

            Cell actionTime = actionRow.createCell(5);
            actionTime.setCellValue((action.getStopTime() == null ? "? !"
                    : ((action.getStopTime().getTime() - action.getStartTime().getTime()) / (1000 * 60)) / 60
                            + " . " + ((action.getStopTime().getTime() - action.getStartTime().getTime())
                                    / (1000 * 60) % 60 + " .")));

        }
        rowCount++;

    }

    sheet.autoSizeColumn(0);
    sheet.autoSizeColumn(1);
    sheet.autoSizeColumn(2);
    sheet.autoSizeColumn(3);
    sheet.autoSizeColumn(4);
    sheet.autoSizeColumn(5);

    return book;
}

From source file:com.linus.excel.poi.AligningCells.java

License:Apache License

public static void main(String[] args) throws IOException {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();

    Sheet sheet = wb.createSheet();
    Row row = sheet.createRow((short) 2);
    row.setHeightInPoints(30);// w  w  w.  j  a v a 2s .c o m
    for (int i = 0; i < 8; i++) {
        //column width is set in units of 1/256th of a character width
        sheet.setColumnWidth(i, 256 * 15);
    }

    createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);
    createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);
    createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);
    createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);
    createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);
    createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);
    createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("excel/ss-example-align.xlsx");
    wb.write(fileOut);
    fileOut.close();
    wb.close();
}

From source file:com.maogousoft.wuliu.controller.DriverController.java

public void exportExcel() throws IOException {
    StringBuffer from = new StringBuffer();
    from.append("from logistics_driver where status = 1 ");
    from.append(createOrder());//from   w  ww .  j  av  a 2  s  .c o m
    Page<Record> page = Db.paginate(getPageIndex(), 100000, "select * ", from.toString());
    List<Record> list = page.getList();
    Dict.fillDictToRecords(page.getList());

    String headers = "?|?|??|??|?|??|||?|??||?|??|?|??|?";
    String attributes = "id|phone|name|recommender|plate_number|id_card|car_type_str|car_length|car_weight|gold|regist_time|car_phone|start_province_str|start_city_str|end_province_str|end_city_str";

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();
    Row headerRow = sheet.createRow(0);
    List<String> headerList = WuliuStringUtils.parseVertical(headers);
    for (int j = 0; j < headerList.size(); j++) {
        String attr = headerList.get(j);
        Cell cell = headerRow.createCell(j);
        cell.setCellValue(attr);
    }

    for (int i = 0; i < list.size(); i++) {
        Record record = list.get(i);
        Row row = sheet.createRow(i + 1);

        List<String> attrList = WuliuStringUtils.parseVertical(attributes);
        for (int j = 0; j < attrList.size(); j++) {
            String attr = attrList.get(j);
            Cell cell = row.createCell(j);
            Object value = getValue(record, attr);
            cell.setCellValue(value + "");
        }
    }

    HttpServletResponse resp = getResponse();
    String filename = TimeUtil.format(new Date(), "'?'yyyyMMdd_HHmmss'.xls'");
    resp.addHeader("Content-Disposition",
            "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1"));
    ServletOutputStream out = resp.getOutputStream();
    wb.write(out);
    out.close();
    renderNull();
}

From source file:com.maogousoft.wuliu.controller.DriverController.java

/**
 * /*from  w ww .  j  a va  2s .  c  o m*/
 * @description ? 
 * @author shevliu
 * @email shevliu@gmail.com
 * 201386 ?11:47:19
 * @throws IOException
 */
public void exportPendingAudit() throws IOException {
    StringBuffer from = new StringBuffer();
    from.append("from logistics_driver where status = 0 ");
    from.append(createOrder());
    Page<Record> page = Db.paginate(getPageIndex(), 100000, "select * ", from.toString());
    List<Record> list = page.getList();
    Dict.fillDictToRecords(page.getList());

    String headers = "?|?|??|??|?|??|||?|??||?|??|?|??|?";
    String attributes = "id|phone|name|recommender|plate_number|id_card|car_type_str|car_length|car_weight|gold|regist_time|car_phone|start_province_str|start_city_str|end_province_str|end_city_str";

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();
    Row headerRow = sheet.createRow(0);
    List<String> headerList = WuliuStringUtils.parseVertical(headers);
    for (int j = 0; j < headerList.size(); j++) {
        String attr = headerList.get(j);
        Cell cell = headerRow.createCell(j);
        cell.setCellValue(attr);
    }

    for (int i = 0; i < list.size(); i++) {
        Record record = list.get(i);
        Row row = sheet.createRow(i + 1);
        List<String> attrList = WuliuStringUtils.parseVertical(attributes);
        for (int j = 0; j < attrList.size(); j++) {
            String attr = attrList.get(j);
            Cell cell = row.createCell(j);
            Object value = getValue(record, attr);
            cell.setCellValue(value + "");
        }
    }

    HttpServletResponse resp = getResponse();
    String filename = TimeUtil.format(new Date(), "'?'yyyyMMdd_HHmmss'.xls'");
    resp.addHeader("Content-Disposition",
            "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1"));
    ServletOutputStream out = resp.getOutputStream();
    wb.write(out);
    out.close();
    renderNull();
}

From source file:com.mechatronika.trackmchtr.ExportToExcel.java

private static void writeToExcel(String path) throws FileNotFoundException, IOException {
    new WorkbookFactory();
    Workbook wb = new XSSFWorkbook(); //Excell workbook
    Sheet sheet = wb.createSheet(); //WorkSheet //wb.createSheet("sheetName");
    Row row = sheet.createRow(2); //Row created at line 3
    TableModel model = table.getModel(); //Table model

    Row headerRow = sheet.createRow(0); //Create row at line 0
    for (int headings = 0; headings < model.getColumnCount(); headings++) { //For each column
        headerRow.createCell(headings).setCellValue(model.getColumnName(headings));//Write column name
    }/*from   www . java 2s  .  c om*/

    for (int rows = 0; rows < model.getRowCount(); rows++) { //For each table row
        for (int cols = 0; cols < table.getColumnCount(); cols++) { //For each table column
            row.createCell(cols).setCellValue(model.getValueAt(rows, cols).toString()); //Write value
        }

        //Set the row to the next one in the sequence 
        row = sheet.createRow((rows + 3));
    }
    wb.write(new FileOutputStream(path));//Save the file  
    IJ.showMessage("Excel file created!");
}

From source file:com.rodrigodev.xgen4j_table_generator.model.table.TableWriter.java

License:Open Source License

public void write(InformationWrapper information, OutputStream output) {
    try {/*w w  w .  j  av a2 s .  c  o m*/
        Workbook wb = new XSSFWorkbook();
        Table table = new Table(wb.createSheet());

        writeHeaders(information, table.newRow());
        for (ErrorInfoWrapper errorInfo : information.list()) {
            writeContent(errorInfo, table.newRow());
        }

        wb.write(output);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}