Example usage for org.apache.poi.ss.usermodel Font setBold

List of usage examples for org.apache.poi.ss.usermodel Font setBold

Introduction

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

Prototype

public void setBold(boolean bold);

Source Link

Usage

From source file:com.shiyq.poi.HSSFTest.java

public static boolean createExcel(String excelName) {
    boolean created = false;
    Workbook wb = new HSSFWorkbook();
    Font font = wb.createFont();
    font.setBold(true);
    CellStyle headStyle = wb.createCellStyle();
    headStyle.setFont(font);//from   ww  w  .  j  a  v  a  2 s  .  c  o  m

    Sheet sheet = wb.createSheet("20165???");
    String[] head = { "??", "?", "??", "???", "????",
            "????", "?", "??", "", "",
            "??" };
    String[] code = { "card_no", "card_type", "spread_time", "spread_emp_no", "spread_emp_name", "owner_name",
            "plate", "blance", "start_time", "end_time", "month_money" };

    List<Map<String, Object>> list = setList();
    setSheet(sheet, list, head, headStyle, code);
    //
    int startRow = 4;
    int endRow = 8;
    int startColumn = head.length + 4;
    int endColumn = head.length + 8;

    String describe = "1?" + (new Date().toString()) + "\n";
    describe += "2.\n";
    describe += "3.?2016-4-42016-5-4";
    CellStyle descStyle = wb.createCellStyle();
    descStyle.setAlignment(CellStyle.ALIGN_LEFT);
    descStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    setSheet(sheet, startRow, endRow, startColumn, endColumn, describe, descStyle);

    Sheet sheet1 = wb.createSheet("20166???");
    setSheet(sheet1, list, head, headStyle, code);
    setSheet(sheet1, startRow, endRow, startColumn, endColumn, describe, descStyle);
    try {
        try (FileOutputStream fileOut = new FileOutputStream(excelName)) {
            wb.write(fileOut);
            created = true;
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(HSSFTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HSSFTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return created;
}

From source file:com.tm.hiber.service.util.DatabaseUtil.java

/**
 *
 * @param objFile/*from  ww w .  j ava2  s  . com*/
 * @param objJTable
 * @return number of records exported
 */
public int exportData(File objFile, JTable objJTable) throws FileNotFoundException, IOException {
    int response = 0;

    if (objFile == null) {
        return response;
    }

    DefaultTableModel tm = (DefaultTableModel) objJTable.getModel();
    Object[] rows = tm.getDataVector().toArray();

    JTableHeader columnNames = objJTable.getTableHeader();
    TableColumnModel columnModel = columnNames.getColumnModel();
    int columnCount = columnModel.getColumnCount();
    Vector<String> vecColumnNames = new Vector<String>();
    for (int c = 0; c < columnCount; c++) {
        vecColumnNames.add(columnModel.getColumn(c).getHeaderValue().toString());
    }

    HSSFWorkbook exportReadyWorkbook = new HSSFWorkbook();
    HSSFSheet dataSheet = exportReadyWorkbook.createSheet(getExportSheetName());

    if (vecColumnNames.size() > 0) {
        int columnCounter = 0;
        Row objHSSFColumnName = dataSheet.createRow(0);

        for (String strColumnName : vecColumnNames) {
            /* Set Header CSS */

            Cell objHSSFCell = objHSSFColumnName.createCell(columnCounter);
            objHSSFCell.setCellValue(strColumnName);
            CellStyle csll = exportReadyWorkbook.createCellStyle();
            Font objFont = exportReadyWorkbook.createFont();
            objFont.setFontName("Calibri");
            objFont.setColor(IndexedColors.BLACK.index);
            objFont.setBold(true);
            csll.setFont(objFont);
            csll.setFillBackgroundColor(HSSFColor.YELLOW.index);
            csll.setFillForegroundColor(HSSFColor.YELLOW.index);
            csll.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            csll.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            //csll.setWrapText(true);
            objHSSFCell.setCellStyle(csll);
            columnCounter++;
        }
    }

    if (rows != null && rows.length > 0) {
        /* Set Data into Sheet */
        for (int i = 0; i < rows.length; i++) {
            Vector objCellsData = (Vector) rows[i];
            Row objHSSFRow = dataSheet.createRow(i + 1);
            if (objCellsData != null && objCellsData.size() > 0) {
                for (int j = 0; j < objCellsData.size(); j++) {

                    /* Set Cell Data CSS */

                    Cell objHSSFCell = objHSSFRow.createCell(j);
                    CellStyle csll = exportReadyWorkbook.createCellStyle();
                    Font objFont = exportReadyWorkbook.createFont();
                    objFont.setColor(IndexedColors.BLACK.index);
                    objFont.setBold(false);
                    objFont.setFontName("Calibri");
                    csll.setFont(objFont);
                    csll.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                    csll.setFillBackgroundColor(IndexedColors.WHITE.index);
                    csll.setFillForegroundColor(IndexedColors.WHITE.index);

                    csll.setAlignment(HSSFCellStyle.ALIGN_CENTER);

                    //csll.setWrapText(true);
                    csll.setBorderBottom(CellStyle.BORDER_THIN);
                    csll.setBorderTop(CellStyle.BORDER_THIN);

                    csll.setBottomBorderColor(HSSFColor.GREY_25_PERCENT.index);
                    csll.setTopBorderColor(HSSFColor.GREY_50_PERCENT.index);

                    objHSSFCell.setCellStyle(csll);
                    Object cellData = objCellsData.get(j);
                    objHSSFCell.setCellValue((String) cellData);
                }
            }
        }

        for (int i = 0; i < columnCount; i++) {
            if (i == 2) {
                dataSheet.setColumnWidth(i, 30 * 256);
            } else {
                dataSheet.autoSizeColumn(i);
            }
        }

        /* Write File */
        FileOutputStream objFileOutputStream = new FileOutputStream(objFile);
        exportReadyWorkbook.write(objFileOutputStream);
        objFileOutputStream.flush();
        objFileOutputStream.close();
        response = rows.length;
    }

    return response;
}

From source file:com.tremolosecurity.scale.ui.reports.GenerateSpreadsheet.java

License:Apache License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
    resp.setHeader("Pragma", "no-cache");

    ReportViewer scaleReport = (ReportViewer) req.getSession().getAttribute("scaleReportCached");

    Workbook wb = new XSSFWorkbook();

    Font font = wb.createFont();
    font.setBold(true);

    Font titleFont = wb.createFont();
    titleFont.setBold(true);/*ww  w .ja  v  a2s.  c  o  m*/
    titleFont.setFontHeightInPoints((short) 16);

    Sheet sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(scaleReport.getReportInfo().getName()));

    //Create a header
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);

    RichTextString title = new XSSFRichTextString(scaleReport.getReportInfo().getName());
    title.applyFont(titleFont);

    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));

    cell.setCellValue(title);

    row = sheet.createRow(1);
    cell = row.createCell(0);
    cell.setCellValue(scaleReport.getReportInfo().getDescription());

    sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3));

    row = sheet.createRow(2);
    cell = row.createCell(0);
    cell.setCellValue(scaleReport.getRunDateTime());

    sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 3));

    row = sheet.createRow(3);

    int rowNum = 4;

    if (scaleReport.getResults().getGrouping().isEmpty()) {
        row = sheet.createRow(rowNum);
        cell = row.createCell(0);
        cell.setCellValue("There is no data for this report");
    } else {

        for (ReportGrouping group : scaleReport.getResults().getGrouping()) {
            for (String colHeader : scaleReport.getResults().getHeaderFields()) {
                row = sheet.createRow(rowNum);
                cell = row.createCell(0);

                RichTextString rcolHeader = new XSSFRichTextString(colHeader);
                rcolHeader.applyFont(font);

                cell.setCellValue(rcolHeader);
                cell = row.createCell(1);
                cell.setCellValue(group.getHeader().get(colHeader));

                rowNum++;
            }

            row = sheet.createRow(rowNum);

            int cellNum = 0;
            for (String colHeader : scaleReport.getResults().getDataFields()) {
                cell = row.createCell(cellNum);

                RichTextString rcolHeader = new XSSFRichTextString(colHeader);
                rcolHeader.applyFont(font);
                cell.setCellValue(rcolHeader);
                cellNum++;
            }

            rowNum++;

            for (Map<String, String> dataRow : group.getData()) {
                cellNum = 0;
                row = sheet.createRow(rowNum);
                for (String colHeader : scaleReport.getResults().getDataFields()) {
                    cell = row.createCell(cellNum);
                    cell.setCellValue(dataRow.get(colHeader));
                    cellNum++;
                }
                rowNum++;
            }

            row = sheet.createRow(rowNum);
            rowNum++;
        }

    }

    resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    wb.write(resp.getOutputStream());

}

From source file:com.tremolosecurity.scalejs.ws.ScaleMain.java

License:Apache License

private void exportToExcel(HttpFilterRequest request, HttpFilterResponse response, Gson gson)
        throws IOException {
    int lastslash = request.getRequestURI().lastIndexOf('/');
    int secondlastslash = request.getRequestURI().lastIndexOf('/', lastslash - 1);

    String id = request.getRequestURI().substring(secondlastslash + 1, lastslash);

    ReportResults res = (ReportResults) request.getSession().getAttribute(id);

    if (res == null) {
        response.setStatus(404);// w w w  .  j av a 2s .  c o  m
        ScaleError error = new ScaleError();
        error.getErrors().add("Report no longer available");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().print(gson.toJson(error).trim());
        response.getWriter().flush();
    } else {

        response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");

        Workbook wb = new XSSFWorkbook();

        Font font = wb.createFont();
        font.setBold(true);

        Font titleFont = wb.createFont();
        titleFont.setBold(true);
        titleFont.setFontHeightInPoints((short) 16);

        Sheet sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(res.getName()));

        //Create a header
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);

        RichTextString title = new XSSFRichTextString(res.getName());
        title.applyFont(titleFont);

        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));

        cell.setCellValue(title);

        row = sheet.createRow(1);
        cell = row.createCell(0);
        cell.setCellValue(res.getDescription());

        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3));

        row = sheet.createRow(2);
        cell = row.createCell(0);
        //cell.setCellValue(new DateTime().toString("MMMM Do, YYYY h:mm:ss a"));

        sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 3));

        row = sheet.createRow(3);

        int rowNum = 4;

        if (res.getGrouping().isEmpty()) {
            row = sheet.createRow(rowNum);
            cell = row.createCell(0);
            cell.setCellValue("There is no data for this report");
        } else {

            for (ReportGrouping group : res.getGrouping()) {
                for (String colHeader : res.getHeaderFields()) {
                    row = sheet.createRow(rowNum);
                    cell = row.createCell(0);

                    RichTextString rcolHeader = new XSSFRichTextString(colHeader);
                    rcolHeader.applyFont(font);

                    cell.setCellValue(rcolHeader);
                    cell = row.createCell(1);
                    cell.setCellValue(group.getHeader().get(colHeader));

                    rowNum++;
                }

                row = sheet.createRow(rowNum);

                int cellNum = 0;
                for (String colHeader : res.getDataFields()) {
                    cell = row.createCell(cellNum);

                    RichTextString rcolHeader = new XSSFRichTextString(colHeader);
                    rcolHeader.applyFont(font);
                    cell.setCellValue(rcolHeader);
                    cellNum++;
                }

                rowNum++;

                for (Map<String, String> dataRow : group.getData()) {
                    cellNum = 0;
                    row = sheet.createRow(rowNum);
                    for (String colHeader : res.getDataFields()) {
                        cell = row.createCell(cellNum);
                        cell.setCellValue(dataRow.get(colHeader));
                        cellNum++;
                    }
                    rowNum++;
                }

                row = sheet.createRow(rowNum);
                rowNum++;
            }

        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        wb.write(response.getOutputStream());
    }
}

From source file:com.validation.manager.core.tool.requirement.importer.RequirementImporter.java

License:Apache License

public static File exportTemplate() throws FileNotFoundException, IOException, InvalidFormatException {
    File template = new File("Template.xls");
    template.createNewFile();//from   www.  ja va 2 s .c  om
    org.apache.poi.ss.usermodel.Workbook wb = new HSSFWorkbook();
    org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet();
    wb.setSheetName(0, "Requirements");
    int column = 0;
    CellStyle cs = wb.createCellStyle();
    cs.setDataFormat(getBuiltinFormat("text"));
    Font f = wb.createFont();
    f.setFontHeightInPoints((short) 12);
    f.setBold(true);
    f.setColor((short) Font.COLOR_NORMAL);
    cs.setFont(f);
    Row newRow = sheet.createRow(0);
    for (String label : COLUMNS) {
        Cell newCell = newRow.createCell(column);
        newCell.setCellStyle(cs);
        newCell.setCellValue(label);
        column++;
    }

    try (FileOutputStream out = new FileOutputStream(template)) {
        wb.write(out);
        out.close();
    } catch (FileNotFoundException e) {
        LOG.log(Level.SEVERE, null, e);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, null, e);
    }
    return template;
}

From source file:com.validation.manager.core.tool.step.importer.StepImporter.java

License:Apache License

public static File exportTemplate() throws FileNotFoundException, IOException, InvalidFormatException {
    File template = new File("Template.xls");
    template.createNewFile();//  w w  w. j ava  2 s.  c  o m
    org.apache.poi.ss.usermodel.Workbook wb = new HSSFWorkbook();
    org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet();
    wb.setSheetName(0, "Steps");
    int column = 0;
    CellStyle cs = wb.createCellStyle();
    cs.setDataFormat(getBuiltinFormat("text"));
    Font f = wb.createFont();
    f.setFontHeightInPoints((short) 12);
    f.setBold(true);
    f.setColor((short) Font.COLOR_NORMAL);
    cs.setFont(f);
    Row newRow = sheet.createRow(0);
    for (String label : COLUMNS) {
        Cell newCell = newRow.createCell(column);
        newCell.setCellStyle(cs);
        newCell.setCellValue(label);
        column++;
    }

    try (FileOutputStream out = new FileOutputStream(template)) {
        wb.write(out);
        out.close();
    } catch (FileNotFoundException e) {
        LOG.log(Level.SEVERE, null, e);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, null, e);
    }
    return template;
}

From source file:com.ykun.commons.utils.excel.ExcelUtils.java

License:Apache License

/**
 * ??//from   w w  w. j  av a 2s  .c o  m
 *
 * @param workbook Workbook
 * @return CellStyle
 */
private static CellStyle createHeaderStyle(Workbook workbook) {
    CellStyle style = workbook.createCellStyle();
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    Font headerFont = workbook.createFont();
    headerFont.setBold(Boolean.TRUE);
    headerFont.setColor(IndexedColors.BLACK.getIndex());
    style.setFont(headerFont);
    return style;
}

From source file:com.zxy.commons.poi.excel.ExcelUtils.java

License:Apache License

/**
 * export excel//  w ww .j a v  a  2s  .  co  m
 * 
 * @param sheetName sheet name
 * @param table table
 * @return Workbook
*/
@SuppressWarnings("PMD.ShortVariable")
private static Workbook exportExcel(String sheetName, Table<Integer, String, String> table) {
    Set<Integer> tableRows = table.rowKeySet();
    Set<String> tableColumns = table.columnKeySet();
    // excel
    Workbook wb = new HSSFWorkbook();

    // sheet??
    Sheet sheet = wb.createSheet(sheetName);
    // ???n?
    /*for (int i = 0; i < keys.length; i++) {
    sheet.setColumnWidth((short) i, (short) (35.7 * 150));
    }*/

    // 
    Row row = sheet.createRow((short) 0);

    // ???
    CellStyle cs = wb.createCellStyle();
    CellStyle cs2 = wb.createCellStyle();

    // ?
    Font f1 = wb.createFont();
    Font f2 = wb.createFont();

    // ????
    f1.setFontHeightInPoints((short) 10);
    f1.setColor(IndexedColors.BLACK.getIndex());
    f1.setBold(true);

    // ??
    f2.setFontHeightInPoints((short) 10);
    f2.setColor(IndexedColors.BLACK.getIndex());

    // Font f3=wb.createFont();
    // f3.setFontHeightInPoints((short) 10);
    // f3.setColor(IndexedColors.RED.getIndex());

    // ?????
    cs.setFont(f1);
    cs.setBorderLeft(BorderStyle.THIN);
    cs.setBorderRight(BorderStyle.THIN);
    cs.setBorderTop(BorderStyle.THIN);
    cs.setBorderBottom(BorderStyle.THIN);
    cs.setAlignment(HorizontalAlignment.CENTER);

    // ???
    cs2.setFont(f2);
    cs2.setBorderLeft(BorderStyle.THIN);
    cs2.setBorderRight(BorderStyle.THIN);
    cs2.setBorderTop(BorderStyle.THIN);
    cs2.setBorderBottom(BorderStyle.THIN);
    cs2.setAlignment(HorizontalAlignment.CENTER);
    // ??
    int i = 0;
    for (String tableColumn : tableColumns) {
        Cell cell = row.createCell(i);
        cell.setCellValue(tableColumn);
        cell.setCellStyle(cs);
        i++;
    }
    // ??
    for (Integer tableRow : tableRows) {
        // Row ,Cell  , Row  Cell 0
        // sheet
        checkArgument(tableRow > 0, "Row index must be greater than zero!");
        Row row1 = sheet.createRow(tableRow);
        // row
        Map<String, String> item = table.row(tableRow);
        int j = 0;
        for (Map.Entry<String, String> entry : item.entrySet()) {
            //            for(String v:item.keySet()){
            //                System.out.println(tableRow + "-" + v + "-" + item.get(v));
            Cell cell = row1.createCell(j);
            cell.setCellValue(entry.getValue());
            cell.setCellStyle(cs2);
            j++;
        }
    }
    return wb;
}

From source file:Compras.avanceSurtido.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
     // TODO add your handling code here:
     h = new Herramientas(this.user, 0);
     h.session(sessionPrograma);/*from w  ww.  j a v  a 2  s  .c  om*/
     File archivoXLS = null;
     javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
     jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
     String ruta = null;
     if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
         ruta = jF1.getSelectedFile().getAbsolutePath();
         if (ruta != null) {
             archivoXLS = new File(ruta + ".xls");
             try {
                 if (archivoXLS.exists())
                     archivoXLS.delete();
                 archivoXLS.createNewFile();
                 Workbook libro = new HSSFWorkbook();
                 FileOutputStream archivo = new FileOutputStream(archivoXLS);
                 Sheet hoja = libro.createSheet("Avance de pedidos");
                 Font font = libro.createFont();
                 font.setFontHeightInPoints((short) 24);
                 font.setFontName("Arial");
                 font.setItalic(false);
                 font.setBold(true);

                 // Fonts are set into a style so create a new one to use.
                 CellStyle style = libro.createCellStyle();
                 style.setFont(font);

                 Session session = HibernateUtil.getSessionFactory().openSession();
                 session.beginTransaction().begin();
                 Orden ord = (Orden) session.get(Orden.class, Integer.parseInt(orden));

                 Configuracion con = (Configuracion) session.get(Configuracion.class, 1);
                 hoja.setColumnWidth(2, 15000);
                 Row r0 = hoja.createRow(0);
                 Cell celdaTitulo = r0.createCell(0);
                 celdaTitulo.setCellValue(con.getEmpresa());
                 celdaTitulo.setCellStyle(style);

                 Row r1 = hoja.createRow(1);
                 r1.createCell(6).setCellValue("Orden de Taller:");
                 r1.createCell(7).setCellValue(orden);

                 Row r2 = hoja.createRow(2);
                 r2.createCell(0).setCellValue("Marca:");
                 r2.createCell(1).setCellValue(ord.getMarca().getMarcaNombre());
                 r2.createCell(6).setCellValue("N Serie:");
                 r2.createCell(7).setCellValue(ord.getNoSerie());

                 Row r3 = hoja.createRow(3);
                 r3.createCell(0).setCellValue("Tipo:");
                 r3.createCell(1).setCellValue(ord.getTipo().getTipoNombre());
                 r3.createCell(6).setCellValue("N Motor:");
                 r3.createCell(7).setCellValue(ord.getNoMotor());

                 Row r4 = hoja.createRow(4);
                 r4.createCell(0).setCellValue("Modelo:");
                 r4.createCell(1).setCellValue("" + ord.getModelo());

                 hoja.createRow(5).createCell(0).setCellValue(
                         "**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************");

                 Row r6 = hoja.createRow(6);
                 r6.createCell(0).setCellValue("Partida");
                 r6.createCell(1).setCellValue("sub");
                 r6.createCell(2).setCellValue("Descripcion");
                 r6.createCell(3).setCellValue("Hoj");
                 r6.createCell(4).setCellValue("Mec");
                 r6.createCell(5).setCellValue("Sus");
                 r6.createCell(6).setCellValue("Ele");
                 r6.createCell(7).setCellValue("Can");
                 r6.createCell(8).setCellValue("Med");
                 r6.createCell(9).setCellValue("Folio");
                 r6.createCell(10).setCellValue("Codigo");
                 r6.createCell(11).setCellValue("Origen");
                 r6.createCell(12).setCellValue("Proveedor");
                 r6.createCell(13).setCellValue("Cant C.");
                 r6.createCell(14).setCellValue("C/U Comprado");
                 r6.createCell(15).setCellValue("Plazo");
                 r6.createCell(16).setCellValue("Pedido");
                 r6.createCell(17).setCellValue("F. Pedido");
                 r6.createCell(18).setCellValue("Entradas");
                 r6.createCell(19).setCellValue("Devoluciones");
                 r6.createCell(20).setCellValue("Pendientes");
                 r6.createCell(21).setCellValue("No Factura");

                 hoja.createRow(7).createCell(0).setCellValue(
                         "**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************");

                 session.close();
                 if (t_datos.getRowCount() > 0) {
                     for (int i = 0; i < t_datos.getRowCount(); i++) {

                         Row fila = hoja.createRow(i + 8);
                         for (int j = 1; j < t_datos.getColumnCount(); j++) {
                             if (j > 3 && j < 8) {
                                 if ((boolean) t_datos.getValueAt(i, j) == true)
                                     fila.createCell(j - 1).setCellValue("");
                                 else
                                     fila.createCell(j - 1).setCellValue("");
                             } else {
                                 if (t_datos.getValueAt(i, j) != null)
                                     fila.createCell(j - 1).setCellValue("" + t_datos.getValueAt(i, j));
                                 else
                                     fila.createCell(j - 1).setCellValue("");
                             }
                         }
                     }
                 }

                 libro.write(archivo);
                 archivo.close();
                 Desktop.getDesktop().open(archivoXLS);
             } catch (Exception e) {
                 System.out.println(e);
                 e.printStackTrace();
                 JOptionPane.showMessageDialog(this,
                         "No se pudo realizar el reporte si el archivo esta abierto");
             }
         }
     }
 }

From source file:Compras.generaCotizacion.java

void exel() {
     h = new Herramientas(this.user, 0);
     h.session(sessionPrograma);/*  w  w w.j av a2 s . c o m*/
     javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
     jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
     String ruta = null;
     if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
         ruta = jF1.getSelectedFile().getAbsolutePath();
         if (ruta != null) {
             if (ruta.endsWith(".xls") == true)
                 archivoXLS = new File(ruta);
             else
                 archivoXLS = new File(ruta + ".xls");
             try {
                 if (archivoXLS.exists())
                     archivoXLS.delete();
                 archivoXLS.createNewFile();
                 Workbook libro = new HSSFWorkbook();
                 FileOutputStream archivo = new FileOutputStream(archivoXLS);
                 Sheet hoja = libro.createSheet("Cotizacion");
                 Font font = libro.createFont();
                 font.setFontHeightInPoints((short) 24);
                 font.setFontName("Arial");
                 font.setItalic(false);
                 font.setBold(true);

                 Font font10 = libro.createFont();
                 font10.setFontHeightInPoints((short) 10);
                 font10.setFontName("Arial");
                 font10.setItalic(false);
                 font10.setBold(false);
                 font10.setColor(new HSSFColor.YELLOW().getIndex());

                 Font font11 = libro.createFont();
                 font11.setFontHeightInPoints((short) 10);
                 font11.setFontName("Arial");
                 font10.setItalic(false);
                 font10.setBold(false);
                 font11.setColor(new HSSFColor.BLACK().getIndex());

                 // Fonts are set into a style so create a new one to use.
                 CellStyle style = libro.createCellStyle();
                 CellStyle desBloqueo = libro.createCellStyle();
                 CellStyle desBloqueo1 = libro.createCellStyle();
                 CellStyle desBloqueoFecha = libro.createCellStyle();

                 style.setFont(font);

                 desBloqueo.setFont(font10);
                 desBloqueo.setLocked(false);
                 desBloqueo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                 desBloqueo.setFillBackgroundColor(new HSSFColor.GREEN().getIndex());

                 desBloqueo1.setFont(font11);
                 desBloqueo1.setLocked(false);
                 desBloqueo1.setFillBackgroundColor(new HSSFColor.WHITE().getIndex());

                 desBloqueoFecha.setFont(font10);
                 desBloqueoFecha.setLocked(false);
                 desBloqueoFecha.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                 desBloqueoFecha.setFillBackgroundColor(new HSSFColor.GREEN().getIndex());
                 desBloqueoFecha.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));

                 Session session = HibernateUtil.getSessionFactory().openSession();
                 session.beginTransaction().begin();
                 Orden ord = (Orden) session.get(Orden.class, Integer.parseInt(orden));
                 Configuracion con = (Configuracion) session.get(Configuracion.class, 1);

                 hoja.setColumnWidth(5, 15000);
                 Row r0 = hoja.createRow(0);
                 Cell celdaTitulo = r0.createCell(0);
                 celdaTitulo.setCellValue(con.getEmpresa());
                 celdaTitulo.setCellStyle(style);

                 Row r1 = hoja.createRow(1);
                 r1.createCell(6).setCellValue("Orden de Taller:");
                 r1.createCell(7).setCellValue(orden);

                 Row r2 = hoja.createRow(2);
                 r2.createCell(0).setCellValue("Marca:");
                 r2.createCell(1).setCellValue(ord.getMarca().getMarcaNombre());
                 r2.createCell(6).setCellValue("N Serie:");
                 r2.createCell(7).setCellValue(ord.getNoSerie());

                 Row r3 = hoja.createRow(3);
                 r3.createCell(0).setCellValue("Tipo:");
                 r3.createCell(1).setCellValue(ord.getTipo().getTipoNombre());
                 r3.createCell(6).setCellValue("N Motor:");
                 r3.createCell(7).setCellValue(ord.getNoMotor());

                 Row r4 = hoja.createRow(4);
                 r4.createCell(0).setCellValue("NP:");
                 r4.createCell(1).setCellValue(t_datos1.getValueAt(t_datos1.getSelectedRow(), 1).toString());
                 r4.createCell(2).setCellValue("Proveedor:");
                 r4.createCell(3).setCellValue(t_datos1.getValueAt(t_datos1.getSelectedRow(), 2).toString());
                 r4.createCell(6).setCellValue("Modelo:");
                 r4.createCell(7).setCellValue("" + ord.getModelo());

                 Row r5 = hoja.createRow(5);
                 r5.createCell(0).setCellValue(
                         "**********************************************************************************[Nota:  Solo puedes editar las celdas de color]*******************************************************************************");

                 Row r6 = hoja.createRow(6);
                 r6.createCell(0).setCellValue("Partida");
                 r6.createCell(1).setCellValue("sub");
                 r6.createCell(2).setCellValue("Cantidad");
                 r6.createCell(3).setCellValue("U/Medida");
                 r6.createCell(4).setCellValue("N Parte");
                 r6.createCell(5).setCellValue("Descripcion");
                 r6.createCell(6).setCellValue("Instruccin");
                 r6.createCell(7).setCellValue("Precio c/u");
                 r6.createCell(8).setCellValue("T o t a l");
                 r6.createCell(9).setCellValue("Origen");
                 r6.createCell(10).setCellValue("Pazo");

                 Row r7 = hoja.createRow(7);
                 r7.createCell(0).setCellValue(
                         "**********************************************************************************************************************************************************************************************************************");

                 List misCotizaciones = null;

                 Query query = session.createQuery("SELECT DISTINCT par FROM Partida par "
                         + "RIGHT JOIN FETCH par.partidaCotizacions partC " + "RIGHT JOIN partC.cotizacion cot "
                         + "where cot.idCotizacion="
                         + t_datos1.getValueAt(t_datos1.getSelectedRow(), 0).toString()
                         + " order by par.idEvaluacion asc, par.subPartida asc");
                 //misCotizaciones=c.addOrder(Order.asc("idCotizacion")).list();
                 misCotizaciones = query.list();

                 if (misCotizaciones.size() > 0) {

                     for (int i = 0; i < misCotizaciones.size(); i++) {
                         Partida Part = (Partida) misCotizaciones.get(i);
                         Row fila = hoja.createRow(i + 8);

                         fila.createCell(0).setCellValue(Part.getIdEvaluacion());
                         fila.createCell(1).setCellValue(Part.getSubPartida());
                         fila.createCell(2).setCellValue(Part.getCant());
                         fila.createCell(3).setCellValue(Part.getMed());

                         Cell aux = fila.createCell(4);
                         aux.setCellStyle(desBloqueo);
                         if (Part.getEjemplar() != null)
                             aux.setCellValue(Part.getEjemplar().getIdParte());
                         else
                             aux.setCellValue("");

                         fila.createCell(5).setCellValue(Part.getCatalogo().getNombre());
                         int fil = i + 9;
                         Cell a10 = fila.createCell(6);
                         a10.setCellStyle(desBloqueo1);
                         a10.setCellValue(Part.getInstruccion());

                         Cell a6 = fila.createCell(7);
                         a6.setCellStyle(desBloqueo);
                         a6.setCellValue("");
                         Cell celForm = fila.createCell(8);
                         celForm.setCellType(HSSFCell.CELL_TYPE_FORMULA);
                         celForm.setCellFormula("H" + fil + "*C" + fil);

                         if (Part.isOri() == true)
                             fila.createCell(9).setCellValue("Ori");
                         else if (Part.isNal() == true)
                             fila.createCell(9).setCellValue("Nal");
                         else if (Part.isDesm() == true)
                             fila.createCell(9).setCellValue("Des");
                         else
                             fila.createCell(9).setCellValue("");
                         Cell a9 = fila.createCell(10);
                         a9.setCellValue("");
                         a9.setCellStyle(desBloqueo);
                     }
                 }

                 hoja.protectSheet("04650077");
                 libro.write(archivo);
                 archivo.close();
                 Desktop.getDesktop().open(archivoXLS);
                 if (session != null)
                     if (session.isOpen())
                         session.close();
             } catch (Exception e) {
                 System.out.println(e);
                 e.printStackTrace();
                 JOptionPane.showMessageDialog(this,
                         "No se pudo realizar el reporte si el archivo esta abierto");
             }
         }
     }
 }