Example usage for org.apache.poi.hssf.usermodel HSSFCell setCellValue

List of usage examples for org.apache.poi.hssf.usermodel HSSFCell setCellValue

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFCell setCellValue.

Prototype

@SuppressWarnings("fallthrough")
public void setCellValue(boolean value) 

Source Link

Document

set a boolean value for the cell

Usage

From source file:de.viaboxx.nlstools.formats.MBExcelPersistencer.java

License:Apache License

private void writeRows(MBBundle bundle, int firstCol) throws IOException {
    List<String> locales = bundleWriter.getLocalesUsed();
    for (MBEntry entry : bundle.getEntries()) {
        HSSFRow row = createRow();/* w  w  w. j  ava  2 s  .c o m*/

        HSSFCell cell = row.createCell(0);
        cell.setCellValue(new HSSFRichTextString(entry.getKey()));

        if (entry.getAliases() != null && !entry.getAliases().isEmpty()) {
            cell = row.createCell(1);
            StringBuilder buf = new StringBuilder();
            boolean comma = false;
            for (String each : entry.getAliases()) {
                if (comma)
                    buf.append(",");
                else
                    comma = each != null && each.length() > 0;
                if (each != null)
                    buf.append(each);
            }
            cell.setCellValue(new HSSFRichTextString(buf.toString()));
        }

        if (entry.getDescription() != null) {
            cell = row.createCell(2);
            cell.setCellValue(new HSSFRichTextString(entry.getDescription()));
        }

        int colNum = firstCol;
        for (String each : locales) {
            MBText text = entry.getText(each);
            if (text != null) {
                cell = row.createCell(colNum);
                cell.setCellValue(new HSSFRichTextString(text.getValue()));
                if (text.getValue() == null || text.getValue().length() == 0) {
                    if (text.isReview()) {
                        comment(cell, each);
                        cell.setCellStyle(styles.get(STYLE_MISSING_REVIEW));
                    } else {
                        comment(cell, each);
                        cell.setCellStyle(styles.get(STYLE_MISSING));
                    }
                } else if (text.isReview()) {
                    comment(cell, each);
                    cell.setCellStyle(styles.get(STYLE_REVIEW));
                }
            }
            colNum++;
        }
    }
}

From source file:demo.admin.controller.UserController.java

@RequestMapping(value = "/user/downloadData")
@VerifyAuthentication(Trader = true, Admin = true, Operation = true)
public HttpEntity<byte[]> downloadUserData(String status, String securephone,
        @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
        @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate)
        throws IOException, DocumentException {
    if (securephone != null && securephone != "") {
        securephone = Where.$like$(securephone);
    }/*from   w w w . j  a  v  a  2  s  .  c om*/
    List<Map<String, Object>> users = userMapper.userExport(status, securephone, startDate, endDate);
    String type = status + "?";
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(type);
    HSSFRow row = sheet.createRow(0);
    CellStyle cellStyle = wb.createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
    cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    sheet.setVerticallyCenter(true);
    sheet.setHorizontallyCenter(true);
    String[] excelHeader = { "??", "???", "??", "", "??" };
    for (int i = 0; i < excelHeader.length; i++) {
        HSSFCell cell = row.createCell(i);
        cell.setCellValue(excelHeader[i]);
        cell.setCellStyle(cellStyle);
        sheet.autoSizeColumn(i, true);
    }
    for (int i = 0; i < users.size(); i++) {
        Map<String, Object> resultSet = users.get(i);
        sheet.autoSizeColumn(i, true);
        row = sheet.createRow(i + 1);
        row.setRowStyle(cellStyle);
        row.createCell(0).setCellValue(i + 1);
        row.createCell(1).setCellValue(String.valueOf(resultSet.get("name")));
        row.createCell(2).setCellValue(String.valueOf(resultSet.get("address")));
        row.createCell(3).setCellValue(String.valueOf(resultSet.get("registertime")));
        row.createCell(4).setCellValue(String.valueOf(resultSet.get("securephone")));

    }
    File file = File.createTempFile(".xls", ".xls");
    OutputStream out = new FileOutputStream(file);
    wb.write(out);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment",
            URLEncoder.encode(type, "UTF-8") + LocalDate.now() + ".xls");
    return new HttpEntity<byte[]>(FileUtils.readFileToByteArray(file), headers);
}

From source file:demo.poi.BigExample.java

License:Apache License

public static void main(String[] args) throws IOException {
    int rownum;// ww  w . j a va 2s. co m

    // create a new file
    FileOutputStream out = new FileOutputStream("target/bigworkbook.xls");
    // create a new workbook
    HSSFWorkbook wb = new HSSFWorkbook();
    // create a new sheet
    HSSFSheet s = wb.createSheet();
    // declare a row object reference
    HSSFRow r = null;
    // declare a cell object reference
    HSSFCell c = null;
    // create 3 cell styles
    HSSFCellStyle cs = wb.createCellStyle();
    HSSFCellStyle cs2 = wb.createCellStyle();
    HSSFCellStyle cs3 = wb.createCellStyle();
    // create 2 fonts objects
    HSSFFont f = wb.createFont();
    HSSFFont f2 = wb.createFont();

    //set font 1 to 12 point type
    f.setFontHeightInPoints((short) 12);
    //make it red
    f.setColor(HSSFColor.RED.index);
    // make it bold
    //arial is the default font
    f.setBoldweight(Font.BOLDWEIGHT_BOLD);

    //set font 2 to 10 point type
    f2.setFontHeightInPoints((short) 10);
    //make it the color at palette index 0xf (white)
    f2.setColor(HSSFColor.WHITE.index);
    //make it bold
    f2.setBoldweight(Font.BOLDWEIGHT_BOLD);

    //set cell stlye
    cs.setFont(f);
    //set the cell format see HSSFDataFromat for a full list
    cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));

    //set a thin border
    cs2.setBorderBottom(CellStyle.BORDER_THIN);
    //fill w fg fill color
    cs2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    // set foreground fill to red
    cs2.setFillForegroundColor(HSSFColor.RED.index);

    // set the font
    cs2.setFont(f2);

    // set the sheet name to HSSF Test
    wb.setSheetName(0, "HSSF Test");
    // create a sheet with 300 rows (0-299)
    for (rownum = 0; rownum < 300; rownum++) {
        // create a row
        r = s.createRow(rownum);
        // on every other row
        if ((rownum % 2) == 0) {
            // make the row height bigger  (in twips - 1/20 of a point)
            r.setHeight((short) 0x249);
        }

        //r.setRowNum(( short ) rownum);
        // create 50 cells (0-49) (the += 2 becomes apparent later
        for (int cellnum = 0; cellnum < 50; cellnum += 2) {
            // create a numeric cell
            c = r.createCell(cellnum);
            // do some goofy math to demonstrate decimals
            c.setCellValue(rownum * 10000 + cellnum + (((double) rownum / 1000) + ((double) cellnum / 10000)));

            // on every other row
            if ((rownum % 2) == 0) {
                // set this cell to the first cell style we defined
                c.setCellStyle(cs);
            }

            // create a string cell (see why += 2 in the
            c = r.createCell(cellnum + 1);

            // set the cell's string value to "TEST"
            c.setCellValue("TEST");
            // make this column a bit wider
            s.setColumnWidth(cellnum + 1, (int) ((50 * 8) / ((double) 1 / 20)));

            // on every other row
            if ((rownum % 2) == 0) {
                // set this to the white on red cell style
                // we defined above
                c.setCellStyle(cs2);
            }

        }
    }

    //draw a thick black border on the row at the bottom using BLANKS
    // advance 2 rows
    rownum++;
    rownum++;

    r = s.createRow(rownum);

    // define the third style to be the default
    // except with a thick black border at the bottom
    cs3.setBorderBottom(CellStyle.BORDER_THICK);

    //create 50 cells
    for (int cellnum = 0; cellnum < 50; cellnum++) {
        //create a blank type cell (no value)
        c = r.createCell(cellnum);
        // set it to the thick black border style
        c.setCellStyle(cs3);
    }

    //end draw thick black border

    // demonstrate adding/naming and deleting a sheet
    // create a sheet, set its title then delete it
    s = wb.createSheet();
    wb.setSheetName(1, "DeletedSheet");
    wb.removeSheetAt(1);
    //end deleted sheet

    // write the workbook to the output stream
    // close our file (don't blow out our file handles
    wb.write(out);
    out.close();
}

From source file:demo.poi.Outlines.java

License:Apache License

private static void createCase1(String filename) throws IOException {
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet1 = wb.createSheet("new sheet");

    sheet1.groupColumn(4, 7);/* ww  w .  j  ava2s  . c om*/

    for (int row = 0; row < 200; row++) {
        HSSFRow r = sheet1.createRow(row);
        for (int column = 0; column < 200; column++) {
            HSSFCell c = r.createCell(column);
            c.setCellValue(column);
        }
    }

    FileOutputStream fileOut = new FileOutputStream(filename);
    wb.write(fileOut);
    fileOut.close();
}

From source file:Directorio.CarDir.java

private void generarXLS() {
    try {//from w  ww.jav  a  2  s  . c  o  m
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Datos");
        for (int i = 0; i < strRuta.size(); i++) {

            File archivoXml = new File(strRuta.get(i));

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(archivoXml);
            NodeList nodeList = document.getElementsByTagName("*");

            HSSFRow rowTag = sheet.createRow(0); //Primera fila imprime Tags
            HSSFRow Row = sheet.createRow(i + 1); //Segunda fila imprime valor de los Tags y sucesivamente a la siguiente

            for (int j = 0; j < strTags.size(); j++) {
                String tagSel = strTags.get(j);
                for (int k = 0; k < nodeList.getLength(); k++) //Nombre de los Nodos
                {
                    String nodo = nodeList.item(k).getNodeName();

                    if (tagSel.equals(nodo)) {
                        HSSFCell Cell = rowTag.createCell(j);
                        Cell.setCellValue(tagSel);
                    }

                    for (int l = 0; l < nodeList.item(k).getChildNodes().getLength(); l++) //Valor de los Nodos
                    {
                        if (tagSel.equals(nodo)) {
                            HSSFCell Cell = Row.createCell(j);
                            Cell.setCellValue(nodeList.item(k).getChildNodes().item(l).getNodeValue());
                        }
                    }

                }

            }
            FileOutputStream output = new FileOutputStream(new File(rutXls.getText() + "\\Sheet.xls"));
            workbook.write(output);
            output.close();
        }

    } catch (IOException e) {
        System.out.println("IOException " + e.getMessage());
    } catch (ParserConfigurationException e) {
        System.out.println("ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
        System.out.println("SAXException " + e.getMessage());
    }
}

From source file:eancode.SearchEanPanelNormal.java

public void exportXLS(JTable table, String path) throws IOException, JRException {

    String headervalue[] = { "ID", "matecode", "Description", "Good", "Dmg", "Leak", "Brkn", "Total", "Origin",
            "Eancode", "Weight", "Remark", "Lotnum", "Doctype", "Docnum", "Grnnum", "Docstatus", "Grnstatus" };
    try {//from  www. java2 s.  com
        HSSFWorkbook fWorkbook = new HSSFWorkbook();
        HSSFSheet fSheet = fWorkbook.createSheet("Pur Sheet");
        HSSFFont sheetTitleFont = fWorkbook.createFont();
        File file = new File(path);
        HSSFCellStyle cellStyle = fWorkbook.createCellStyle();

        sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //sheetTitleFont.setColor();
        TableModel model = table.getModel();

        //                   for (int j = 0; j < model.getColumnCount(); j++) {
        //                             cell = fRow.createCell((short) j);
        //                             cell.setCellValue(model.getColumnName(j));
        //                            cell.setCellStyle(cellStyle);
        //
        //                        }

        for (int i = 0; i < model.getRowCount(); i++) {
            HSSFRow fRow = fSheet.createRow((short) i);
            for (int j = 0; j < model.getColumnCount(); j++) {
                HSSFCell cell = fRow.createCell((short) j);
                if (i == 0) {
                    cell.setCellValue(headervalue[j]);
                    cell.setCellStyle(cellStyle);

                } else {
                    cell.setCellValue(model.getValueAt(i, j).toString());
                    cell.setCellStyle(cellStyle);
                }
            }
        }

        FileOutputStream fileOutputStream;
        fileOutputStream = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
        fWorkbook.write(bos);
        bos.close();
        fileOutputStream.close();
    } catch (Exception e) {

    }

}

From source file:edu.aplic.escuchadores.EjemploExcel.java

/**
 * Crea una hoja Excel y la guarda.// w  w w.j  av a 2  s.  co m
 * 
 * @param args
 */

public static void crearExel(File file) {
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;
    HSSFCell celda = null;

    // Se crea una fila dentro de la hoja
    fila = hoja.createRow(0);

    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("hola mundo"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Celada dos"));

    fila = hoja.createRow(1);

    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);

    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texton = new HSSFRichTextString("value");
    celda.setCellValue(new HSSFRichTextString("value"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texton = new HSSFRichTextString("value");
    //celda.setCellValue(new HSSFRichTextString("20040044.822"));
    celda.setCellValue(20040044.82);

    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        FileOutputStream elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        elFichero.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.aplic.utilerias.GenerarArchivoXlsUtil.java

public static void crearXslVentas(File file, Venta[] aVentas, Usuario oUsuario) throws IOException {
    FileOutputStream elFichero = null;
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;//from w  w  w .  ja  va2s .c om
    HSSFCell celda = null;

    fila = hoja.createRow(0);
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    celda.setCellValue(new HSSFRichTextString("Reporte Ventas"));

    if (oUsuario != null) {
        celda = fila.createCell(1);
        hoja.autoSizeColumn(0);
        celda.setCellValue(new HSSFRichTextString("Usuario: " + oUsuario.getNombreCompleto()));
    }

    // Se crea una fila dentro de la hoja
    fila = hoja.createRow(1);
    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Fecha"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Total"));

    ProductoVendido oProductoVendido = new ProductoVendido();
    ProductoVendido[] aProductoVendido = null;
    double nTotal = 0.0D;
    int rows = 1;
    if (aVentas != null && aVentas.length > 0) {

        for (Venta oVentaTemp : aVentas) {
            ++rows;
            hoja.autoSizeColumn(0);
            fila = hoja.createRow(rows);
            //                Usuario oUsuario = new Usuario();
            //                oUsuario = oVentaTemp.getUsuario();    
            aProductoVendido = oVentaTemp.getProductoVendido();

            // Se crea una celda dentro de la fila
            celda = fila.createCell(0);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha())));
            // Se crea una celda dentro de la fila
            celda = fila.createCell(1);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(formato.format(aProductoVendido[0].getImporte())));
            nTotal += aProductoVendido[0].getImporte();
        }

        ++rows;
        fila = hoja.createRow(rows);
        // Se crea una celda dentro de la fila
        celda = fila.createCell(0);
        // Se crea el contenido de la celda y se mete en ella.
        //HSSFRichTextString texton = new HSSFRichTextString("value");
        celda.setCellValue(new HSSFRichTextString("Total"));
        // Se crea una celda dentro de la fila
        celda = fila.createCell(1);
        // Se crea el contenido de la celda y se mete en ella.
        celda.setCellValue(new HSSFRichTextString(formato.format(nTotal)));
        //this.campoTotal1.setText(formato.format(nTotal));           
    }

    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        JOptionPane.showMessageDialog(null, "Reporte de ventas generado correctamente \n " + file.getPath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        elFichero.close();
    }
}

From source file:edu.aplic.utilerias.GenerarArchivoXlsUtil.java

public static void crearXslVentasPorTipoProducto(File file, Venta[] aVentas, Usuario oUsuario)
        throws IOException {
    FileOutputStream elFichero = null;
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;//  www .java  2  s .  c o  m
    HSSFCell celda = null;

    fila = hoja.createRow(0);
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    celda.setCellValue(new HSSFRichTextString("Reporte Ventas por tipos"));

    if (oUsuario != null) {
        celda = fila.createCell(1);
        hoja.autoSizeColumn(0);
        celda.setCellValue(new HSSFRichTextString("Usuario: " + oUsuario.getNombreCompleto()));
    }

    // Se crea una fila dentro de la hoja
    fila = hoja.createRow(1);
    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Fecha"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Total"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(2);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Tipo"));

    // Style Cell 2B
    HSSFCellStyle cellStyle = libro.createCellStyle();
    cellStyle = libro.createCellStyle();
    cellStyle.setFillForegroundColor(org.apache.poi.hssf.util.HSSFColor.GREY_25_PERCENT.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    cellStyle.setBorderTop((short) 1); // single line border
    cellStyle.setBorderBottom((short) 1); // single line border

    ProductoVendido oProductoVendido = new ProductoVendido();
    ProductoVendido[] aProductoVendido = null;
    double nTotal = 0.0D;
    int rows = 1;
    String sFechaTemp = null;
    boolean bColor = true;
    if (aVentas != null && aVentas.length > 0) {
        boolean bPrimerFecha = true;
        for (Venta oVentaTemp : aVentas) {

            // Contador para inicializar la fecha del primer elemento
            if (bPrimerFecha) {
                sFechaTemp = oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha());
                bPrimerFecha = false;
            } else {
                String sFechaFila = oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha());

                if (!sFechaTemp.equals(sFechaFila)) {
                    bColor = !bColor;
                }

                if (bColor) {
                    cellStyle = libro.createCellStyle();
                    cellStyle.setFillForegroundColor(org.apache.poi.hssf.util.HSSFColor.GREY_25_PERCENT.index);
                    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                    cellStyle.setBorderTop((short) 1); // single line border
                    cellStyle.setBorderBottom((short) 1); // single line border

                } else {
                    cellStyle = libro.createCellStyle();
                    cellStyle.setFillForegroundColor(org.apache.poi.hssf.util.HSSFColor.BLUE_GREY.index);
                    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                    cellStyle.setBorderTop((short) 1); // single line border
                    cellStyle.setBorderBottom((short) 1); // single line border

                }

                sFechaTemp = sFechaFila;

            }

            ++rows;
            hoja.autoSizeColumn(0);
            fila = hoja.createRow(rows);
            //                Usuario oUsuario = new Usuario();
            //                oUsuario = oVentaTemp.getUsuario();    
            aProductoVendido = oVentaTemp.getProductoVendido();

            // Se crea una celda dentro de la fila
            celda = fila.createCell(0);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha())));
            celda.setCellStyle(cellStyle);

            // Se crea una celda dentro de la fila
            celda = fila.createCell(1);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(formato.format(aProductoVendido[0].getImporte())));
            celda.setCellStyle(cellStyle);

            // Se crea una celda dentro de la fila
            celda = fila.createCell(2);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(aProductoVendido[0].getProducto().getTipo()));
            celda.setCellStyle(cellStyle);

            nTotal += aProductoVendido[0].getImporte();
        }

        ++rows;
        fila = hoja.createRow(rows);
        // Se crea una celda dentro de la fila
        celda = fila.createCell(0);
        // Se crea el contenido de la celda y se mete en ella.
        //HSSFRichTextString texton = new HSSFRichTextString("value");
        celda.setCellValue(new HSSFRichTextString("Total"));
        // Se crea una celda dentro de la fila
        celda = fila.createCell(1);
        // Se crea el contenido de la celda y se mete en ella.
        celda.setCellValue(new HSSFRichTextString(formato.format(nTotal)));
        //this.campoTotal1.setText(formato.format(nTotal));           
    }

    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        JOptionPane.showMessageDialog(null, "Reporte de ventas generado correctamente \n " + file.getPath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        elFichero.close();
    }
}

From source file:edu.aplic.utilerias.GenerarArchivoXlsUtil.java

public static void crearXslConsumos(File file, Venta[] aVentas, Usuario oUsuario) throws IOException {
    FileOutputStream elFichero = null;
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;// w w w  .j ava 2s  . com
    HSSFCell celda = null;

    fila = hoja.createRow(0);
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    celda.setCellValue(new HSSFRichTextString("Reporte Consumos"));

    if (oUsuario != null) {
        celda = fila.createCell(1);
        hoja.autoSizeColumn(0);
        celda.setCellValue(new HSSFRichTextString("Usuario: " + oUsuario.getNombreCompleto()));
    }

    // Se crea una fila dentro de la hoja
    fila = hoja.createRow(1);
    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Fecha"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Total"));

    ProductoVendido oProductoVendido = new ProductoVendido();
    ProductoVendido[] aProductoVendido = null;
    double nTotal = 0.0D;
    int rows = 1;
    if (aVentas != null && aVentas.length > 0) {

        for (Venta oVentaTemp : aVentas) {
            ++rows;
            hoja.autoSizeColumn(0);
            fila = hoja.createRow(rows);
            //                Usuario oUsuario = new Usuario();
            //                oUsuario = oVentaTemp.getUsuario();    
            aProductoVendido = oVentaTemp.getProductoVendido();

            // Se crea una celda dentro de la fila
            celda = fila.createCell(0);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha())));
            // Se crea una celda dentro de la fila
            celda = fila.createCell(1);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(formato.format(aProductoVendido[0].getImporte())));
            nTotal += aProductoVendido[0].getImporte();
        }

        ++rows;
        fila = hoja.createRow(rows);
        // Se crea una celda dentro de la fila
        celda = fila.createCell(0);
        // Se crea el contenido de la celda y se mete en ella.
        //HSSFRichTextString texton = new HSSFRichTextString("value");
        celda.setCellValue(new HSSFRichTextString("Total"));
        // Se crea una celda dentro de la fila
        celda = fila.createCell(1);
        // Se crea el contenido de la celda y se mete en ella.
        celda.setCellValue(new HSSFRichTextString(formato.format(nTotal)));
        //this.campoTotal1.setText(formato.format(nTotal));           
    }

    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        JOptionPane.showMessageDialog(null, "Reporte de consumos generado correctamente \n " + file.getPath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        elFichero.close();
    }
}