Example usage for org.apache.poi.hssf.usermodel HSSFDataFormat getFormat

List of usage examples for org.apache.poi.hssf.usermodel HSSFDataFormat getFormat

Introduction

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

Prototype

public String getFormat(short index) 

Source Link

Document

get the format string that matches the given format index

Usage

From source file:br.sp.telesul.service.ExportServiceImpl.java

public void writeExcel(String templateHead, String[] columns, HSSFWorkbook workbook) {
    try {/*w ww.  j a  v  a 2  s  . c  o m*/
        List<Funcionario> funcionarios = funcionarioService.search();

        HSSFSheet sheet = workbook.createSheet(templateHead);

        Row rowHeading = sheet.createRow(0);
        for (int i = 0; i < columns.length; i++) {
            rowHeading.createCell(i).setCellValue(columns[i]);
        }

        for (int i = 0; i < columns.length; i++) {
            CellStyle stylerowHeading = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            font.setFontName(HSSFFont.FONT_ARIAL);
            font.setFontHeightInPoints((short) 11);
            font.setColor(HSSFColor.WHITE.index);
            stylerowHeading.setFont(font);
            stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
            stylerowHeading.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index);
            stylerowHeading.setFillPattern(CellStyle.SOLID_FOREGROUND);
            rowHeading.getCell(i).setCellStyle(stylerowHeading);
        }

        int r = 1;
        for (Funcionario f : funcionarios) {
            Row row = sheet.createRow(r);

            Cell Nome = row.createCell(0);
            Nome.setCellValue(f.getNome());
            Cell cargo = row.createCell(1);
            cargo.setCellValue(f.getCargo());

            Cell dtAdmissao = row.createCell(2);
            dtAdmissao.setCellValue(f.getDtAdmissao());

            CellStyle styleDate = workbook.createCellStyle();
            HSSFDataFormat dfAdmissao = workbook.createDataFormat();
            styleDate.setDataFormat(dfAdmissao.getFormat("dd/mm/yyyy"));
            dtAdmissao.setCellStyle(styleDate);

            Cell area = row.createCell(3);
            area.setCellValue(f.getArea());

            Cell gestor = row.createCell(4);
            gestor.setCellValue(f.getGestor());

            try {
                Cell email = row.createCell(5);
                email.setCellValue(f.getEmail());
            } catch (NullPointerException ne) {

            }
            try {
                Cell telefone = row.createCell(6);
                telefone.setCellValue(f.getTelefone());

            } catch (NullPointerException e) {

            }
            try {
                Cell celular = row.createCell(7);
                celular.setCellValue(f.getCelular());
            } catch (NullPointerException e) {

            }

            r++;
        }

        for (int i = 0; i < columns.length; i++) {
            sheet.autoSizeColumn(i);
        }

    } catch (Exception e) {
        logger.error("Error gerate Report: " + e);
        System.out.println("Error" + e);
    }
}

From source file:br.sp.telesul.service.ExportServiceImpl.java

public void writeExcelCertificacoes(String templateHead, String[] columns, HSSFWorkbook workbook) {
    try {/*  www . ja  v a2 s.c o  m*/
        List<Funcionario> funcionarios = funcionarioService.search();

        HSSFSheet sheet = workbook.createSheet(templateHead);

        Row rowHeading = sheet.createRow(0);
        for (int i = 0; i < columns.length; i++) {
            rowHeading.createCell(i).setCellValue(columns[i]);
        }
        //Estilizar o Cabealho - Stylesheet the heading
        for (int i = 0; i < columns.length; i++) {
            CellStyle stylerowHeading = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            font.setFontName(HSSFFont.FONT_ARIAL);
            font.setFontHeightInPoints((short) 11);
            font.setColor(HSSFColor.WHITE.index);
            stylerowHeading.setFont(font);
            stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
            stylerowHeading.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index);
            stylerowHeading.setFillPattern(CellStyle.SOLID_FOREGROUND);
            rowHeading.getCell(i).setCellStyle(stylerowHeading);
        }
        //Preencher linhas
        int r = 1;
        for (Funcionario f : funcionarios) {

            if (!f.getCertificacoes().isEmpty()) {

                for (Certificacao ct : f.getCertificacoes()) {
                    Row row = sheet.createRow(r);

                    CellStyle styleDate = workbook.createCellStyle();
                    HSSFDataFormat dfExame = workbook.createDataFormat();
                    styleDate.setDataFormat(dfExame.getFormat("dd/mm/yyyy"));
                    try {
                        Cell Nome = row.createCell(0);
                        Nome.setCellValue(f.getNome());

                    } catch (NullPointerException e) {

                    }
                    try {
                        Cell cod = row.createCell(1);
                        cod.setCellValue(ct.getCodigo());
                    } catch (NullPointerException e) {

                    }
                    try {
                        Cell nome = row.createCell(3);
                        nome.setCellValue(ct.getNome());
                    } catch (NullPointerException e) {

                    }
                    try {
                        Cell empresa = row.createCell(2);
                        empresa.setCellValue(ct.getEmpresa());
                    } catch (NullPointerException e) {

                    }
                    try {
                        Cell dtExame = row.createCell(4);
                        dtExame.setCellValue(ct.getDtExame());
                        dtExame.setCellStyle(styleDate);
                    } catch (NullPointerException e) {

                    }
                    try {
                        Cell dtValidade = row.createCell(5);
                        dtValidade.setCellValue(ct.getDtValidade());
                        dtValidade.setCellStyle(styleDate);
                    } catch (NullPointerException e) {

                    }
                    try {

                        Cell copia = row.createCell(6);
                        copia.setCellValue(ct.getCopia());
                    } catch (NullPointerException e) {

                    }

                    r++;
                }

            }

        }

        for (int i = 0; i < columns.length; i++) {
            sheet.autoSizeColumn(i);
        }
        //            String file = "C:/Users/ebranco.TELESULCORP/new.xls";
        //            FileOutputStream out = new FileOutputStream(file);
        //            workbook.write(out);
        //            out.close();
        //            workbook.close();
        //            System.out.println("Excell write succesfully");
    } catch (Exception e) {
        System.out.println("Error" + e);
    }
}

From source file:br.sp.telesul.service.ExportServiceImpl.java

public void writeExcelSingle(Long id, HSSFWorkbook workbook) {
    String[] columns = { "Nome", "Cargo", "Data de Admissao", "?rea", "Gestor", "Email", "Telefone",
            "Celular" };
    String[] colFormacao = { "Formao", "Curso", "Instituio", "Cpia de Certificao" };
    String[] colIdioma = { "Idioma", "Nvel" };
    String[] colCertificacao = { "Certificadora", "Exame", "Cdigo", "Data de Exame", "Data de Validade",
            "Cpia de Certificado" };
    try {/*www . j  ava  2s  .  c  o  m*/
        Funcionario funcionario = this.funcionarioService.searchById(id);

        HSSFSheet sheet = workbook.createSheet("Funcionrio");

        Row rowHeading = sheet.createRow(0);
        for (int i = 0; i < columns.length; i++) {
            rowHeading.createCell(i).setCellValue(columns[i]);
        }
        stylizeHeader(rowHeading, workbook, columns);

        int r = 1;

        Row row = sheet.createRow(r);

        Cell Nome = row.createCell(0);
        Nome.setCellValue(funcionario.getNome());
        Cell cargo = row.createCell(1);
        cargo.setCellValue(funcionario.getCargo());

        Cell dtAdmissao = row.createCell(2);
        dtAdmissao.setCellValue(funcionario.getDtAdmissao());

        CellStyle styleDate = workbook.createCellStyle();
        HSSFDataFormat dfAdmissao = workbook.createDataFormat();
        styleDate.setDataFormat(dfAdmissao.getFormat("dd/mm/yyyy"));
        dtAdmissao.setCellStyle(styleDate);

        Cell area = row.createCell(3);
        area.setCellValue(funcionario.getArea());

        Cell gestor = row.createCell(4);
        gestor.setCellValue(funcionario.getGestor());

        try {
            Cell email = row.createCell(5);
            email.setCellValue(funcionario.getEmail());

        } catch (NullPointerException ne) {

        }
        try {
            Cell telefone = row.createCell(6);
            telefone.setCellValue(funcionario.getTelefone());

        } catch (NullPointerException ne) {

        }
        try {
            Cell celular = row.createCell(7);
            celular.setCellValue(funcionario.getCelular());
        } catch (NullPointerException ne) {

        }

        int auxRow = 12;
        for (Formacao form : funcionario.getFormacoes()) {
            if (!form.getCurso().isEmpty() || !form.getNivel().isEmpty() || !form.getInstituicao().isEmpty()) {
                int headerFormacao = 11;
                Row rowHeadingForm = sheet.createRow(headerFormacao);
                for (int i = 0; i < colFormacao.length; i++) {
                    rowHeadingForm.createCell(i).setCellValue(colFormacao[i]);
                }
                stylizeHeader(rowHeadingForm, workbook, colFormacao);
                int rowFormacao = 12;
                Row rowFormacaoDatas = sheet.createRow(rowFormacao);
                Cell formacao = rowFormacaoDatas.createCell(0);
                Cell curso = rowFormacaoDatas.createCell(1);
                Cell instituicao = rowFormacaoDatas.createCell(2);
                Cell copy = rowFormacaoDatas.createCell(3);
                for (Formacao f : funcionario.getFormacoes()) {
                    try {
                        formacao.setCellValue(f.getNivel());
                    } catch (NullPointerException e) {

                    }
                    try {
                        curso.setCellValue(f.getCurso());
                    } catch (NullPointerException e) {

                    }
                    try {
                        instituicao.setCellValue(f.getInstituicao());
                    } catch (NullPointerException e) {

                    }
                    try {
                        copy.setCellValue(f.getCopiaCertificado());
                    } catch (NullPointerException e) {

                    }

                    rowFormacao++;
                    auxRow = rowFormacao;
                }
                autoSizeColum(sheet, colFormacao);
            }
        }
        for (Idioma i : funcionario.getIdiomas()) {
            try {
                if (!i.getNome().toString().isEmpty() && !i.getNivel().toString().isEmpty()) {
                    int headerIdiomas = auxRow + 9;
                    Row rowHeadingIdioma = sheet.createRow(headerIdiomas);
                    for (int j = 0; j < colIdioma.length; j++) {
                        rowHeadingIdioma.createCell(j).setCellValue(colIdioma[j]);
                    }
                    stylizeHeader(rowHeadingIdioma, workbook, colIdioma);
                    int rowIdioma = headerIdiomas + 1;
                    Row rowIdiomasDatas = sheet.createRow(rowIdioma);
                    Cell nivelIdm = rowIdiomasDatas.createCell(0);
                    Cell language = rowIdiomasDatas.createCell(1);
                    for (Idioma j : funcionario.getIdiomas()) {
                        nivelIdm.setCellValue(j.getNivel().toString());
                        language.setCellValue(j.getNome().toString());
                        rowIdioma++;
                        auxRow = rowIdioma;
                    }
                    autoSizeColum(sheet, colIdioma);
                }
            } catch (NullPointerException ne) {
                logger.error("Idiomas" + ne);
                break;
            }

        }

        if (funcionario.getCertificacoes().size() > 0) {
            int headerCertificacao = auxRow + 9;
            Row rowHeadingCert = sheet.createRow(headerCertificacao);
            for (int j = 0; j < colCertificacao.length; j++) {
                rowHeadingCert.createCell(j).setCellValue(colCertificacao[j]);
            }
            stylizeHeader(rowHeadingCert, workbook, colCertificacao);
            int rowCert = headerCertificacao + 1;

            for (Certificacao c : funcionario.getCertificacoes()) {
                Row rowCertDatas = sheet.createRow(rowCert);
                Cell certificadora = rowCertDatas.createCell(0);
                Cell exame = rowCertDatas.createCell(1);
                Cell codigo = rowCertDatas.createCell(2);
                Cell dtExame = rowCertDatas.createCell(3);
                dtExame.setCellStyle(styleDate);
                Cell dtValidade = rowCertDatas.createCell(4);
                dtValidade.setCellStyle(styleDate);
                Cell copia = rowCertDatas.createCell(5);
                try {
                    certificadora.setCellValue(c.getEmpresa());
                } catch (NullPointerException e) {

                }
                try {
                    exame.setCellValue(c.getNome());
                } catch (NullPointerException e) {

                }
                try {
                    codigo.setCellValue(c.getCodigo());
                } catch (NullPointerException e) {

                }
                try {
                    dtExame.setCellValue(c.getDtExame());
                } catch (NullPointerException e) {

                }
                try {
                    dtValidade.setCellValue(c.getDtValidade());
                } catch (NullPointerException e) {

                }
                try {
                    copia.setCellValue(c.getCopia());
                } catch (NullPointerException e) {

                }

                rowCert++;
            }
            autoSizeColum(sheet, colCertificacao);
        }

        //r++;
    } catch (Exception e) {
        logger.error("Error Writing Single Report: " + e);
        System.out.println("rror Writing Single Report: " + e);
    }
}

From source file:com.accenture.control.GerenciaPlanilhaTS.java

public void geraNovaPlanilhaTS(String dir, List<TesteCaseTSBean> listTS)
        throws FileNotFoundException, IOException {

    FileInputStream arquivo = new FileInputStream(new File(dir));
    HSSFWorkbook workbook = new HSSFWorkbook(arquivo);
    HSSFSheet sheetTS = workbook.getSheetAt(0);

    HSSFDataFormat format = workbook.createDataFormat();
    HSSFCellStyle estilo = workbook.createCellStyle();
    String formatData = "aaaa-mm-dd\"T12:00:00-03:00\"";

    int linha = 1;

    Row row = sheetTS.getRow(linha);/*w  ww . ja v a  2s  . c  o m*/

    Cell descriptionPlan = row.getCell(0);
    Cell prj = row.getCell(1);
    Cell fase = row.getCell(2);
    Cell testPhase = row.getCell(3);
    Cell testScriptName = row.getCell(4);
    Cell testScriptDescription = row.getCell(5);
    Cell stepNo = row.getCell(6);
    Cell stepDescription = row.getCell(7);
    Cell expectedResults = row.getCell(8);
    Cell product = row.getCell(9);
    Cell dataPlanejada = row.getCell(10);

    for (int i = 0; i < listTS.size(); i++) {

        estilo.setDataFormat(format.getFormat(formatData));
        estilo.setFillBackgroundColor(HSSFColor.GREEN.index);

        row = sheetTS.getRow(linha);

        descriptionPlan = row.getCell(0);
        prj = row.getCell(1);
        fase = row.getCell(2);
        testPhase = row.getCell(3);
        testScriptName = row.getCell(4);
        testScriptDescription = row.getCell(5);
        stepNo = row.getCell(6);
        stepDescription = row.getCell(7);
        expectedResults = row.getCell(8);
        product = row.getCell(9);
        dataPlanejada = row.getCell(10);

        descriptionPlan.setCellValue(listTS.get(i).getTestPlan());
        prj.setCellValue(listTS.get(i).getSTIPRJ());
        fase.setCellValue(listTS.get(i).getFASE());
        testPhase.setCellValue(listTS.get(i).getTestPhase());
        testScriptName.setCellValue(listTS.get(i).getTestScriptName());
        testScriptDescription.setCellValue(listTS.get(i).getTestScriptDescription());
        stepNo.setCellValue(listTS.get(i).getSTEP_NUMERO());
        stepDescription.setCellValue(listTS.get(i).getStepDescription());
        expectedResults.setCellValue(listTS.get(i).getExpectedResults());
        product.setCellValue(listTS.get(i).getProduct());
        dataPlanejada.setCellValue(listTS.get(i).getDataPlanejada());

        dataPlanejada.setCellStyle(estilo);

        linha = linha + 2;

    }

    FileOutputStream fileOut = new FileOutputStream(new File(dir));
    workbook.write(fileOut);
    fileOut.close();
    arquivo.close();

}

From source file:com.brick.customer.util.CustomerInfoExcel.java

@SuppressWarnings("unchecked")
public HSSFWorkbook createReport(Map<String, Object> params, Context context) throws Exception {

    ExcelFileWriter efw = new ExcelFileWriter();
    HSSFSheet sheet = efw.createSheet(context.contextMap.get("sheetName") == null ? "summary"
            : (String) context.contextMap.get("sheetName"));
    List<HashMap<String, Object>> list = (List<HashMap<String, Object>>) params.get("cusInfo");

    sheet.setColumnWidth(0, 5000);/*  w  ww  .j  ava  2  s .c o m*/
    sheet.setColumnWidth(1, 3000);
    sheet.setColumnWidth(2, 5300);
    sheet.setColumnWidth(3, 3600);
    sheet.setColumnWidth(4, 4600);
    sheet.setColumnWidth(5, 10000);
    sheet.setColumnWidth(6, 6000);
    sheet.setColumnWidth(7, 4000);
    sheet.setColumnWidth(8, 3500);
    sheet.setColumnWidth(9, 3500);
    sheet.setColumnWidth(10, 3500);
    sheet.setColumnWidth(11, 4200);
    sheet.setColumnWidth(12, 4200);
    sheet.setColumnWidth(13, 4200);
    sheet.setColumnWidth(14, 4800);
    sheet.setColumnWidth(15, 5000);
    sheet.setColumnWidth(16, 5000);
    sheet.setColumnWidth(17, 3000);
    sheet.setColumnWidth(18, 4500);
    sheet.setColumnWidth(19, 4500);
    sheet.setColumnWidth(20, 3000);
    sheet.setColumnWidth(21, 4300);
    sheet.setColumnWidth(22, 4000);
    sheet.setColumnWidth(23, 7000);
    sheet.setColumnWidth(24, 10000);

    HSSFFont headFont0 = null;
    HSSFCellStyle headStyle0 = null;

    headFont0 = efw.getWorkbook().createFont();
    headFont0.setFontHeightInPoints((short) 13); //?
    headFont0.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //    

    headStyle0 = efw.getWorkbook().createCellStyle(); //?
    headStyle0.setAlignment(HSSFCellStyle.ALIGN_CENTER); // ?   
    headStyle0.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //     
    headStyle0.setWrapText(true); // ?  
    headStyle0.setFillBackgroundColor((short) 59);
    headStyle0.setFont(headFont0);

    //??
    HSSFCellStyle cellMoney = efw.getWorkbook().createCellStyle();
    HSSFDataFormat format = efw.getWorkbook().createDataFormat();
    cellMoney.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    cellMoney.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    cellMoney.setDataFormat(format.getFormat("#,###,##0"));

    HSSFRow row0 = sheet.createRow(0);
    HSSFCell cell0 = row0.createCell(0);
    cell0.setCellValue("?");
    cell0.setCellStyle(headStyle0);

    HSSFCell cell1 = row0.createCell(1);
    cell1.setCellValue("??");
    cell1.setCellStyle(headStyle0);

    HSSFCell cell2 = row0.createCell(2);
    cell2.setCellValue("???");
    cell2.setCellStyle(headStyle0);

    HSSFCell cell3 = row0.createCell(3);
    cell3.setCellValue("??");
    cell3.setCellStyle(headStyle0);

    HSSFCell cell4 = row0.createCell(4);
    cell4.setCellValue("?");
    cell4.setCellStyle(headStyle0);

    HSSFCell cell5 = row0.createCell(5);
    cell5.setCellValue("??");
    cell5.setCellStyle(headStyle0);

    HSSFCell cell6 = row0.createCell(6);
    cell6.setCellValue("??");
    cell6.setCellStyle(headStyle0);

    HSSFCell cell7 = row0.createCell(7);
    cell7.setCellValue("?");
    cell7.setCellStyle(headStyle0);

    HSSFCell cell8 = row0.createCell(8);
    cell8.setCellValue("?");
    cell8.setCellStyle(headStyle0);

    HSSFCell cell9 = row0.createCell(9);
    cell9.setCellValue("");
    cell9.setCellStyle(headStyle0);

    HSSFCell cell10 = row0.createCell(10);
    cell10.setCellValue("");
    cell10.setCellStyle(headStyle0);

    HSSFCell cell11 = row0.createCell(11);
    cell11.setCellValue("??");
    cell11.setCellStyle(headStyle0);

    HSSFCell cell12 = row0.createCell(12);
    cell12.setCellValue("?");
    cell12.setCellStyle(headStyle0);

    HSSFCell cell13 = row0.createCell(13);
    cell13.setCellValue("?");
    cell13.setCellStyle(headStyle0);

    HSSFCell cell14 = row0.createCell(14);
    cell14.setCellValue("");
    cell14.setCellStyle(headStyle0);

    HSSFCell cell15 = row0.createCell(15);
    cell15.setCellValue("?");
    cell15.setCellStyle(headStyle0);

    HSSFCell cell16 = row0.createCell(16);
    cell16.setCellValue("??");
    cell16.setCellStyle(headStyle0);

    HSSFCell cell17 = row0.createCell(17);
    cell17.setCellValue("?");
    cell17.setCellStyle(headStyle0);

    HSSFCell cell18 = row0.createCell(18);
    cell18.setCellValue("??");
    cell18.setCellStyle(headStyle0);

    HSSFCell cell19 = row0.createCell(19);
    cell19.setCellValue("?");
    cell19.setCellStyle(headStyle0);

    HSSFCell cell20 = row0.createCell(20);
    cell20.setCellValue("");
    cell20.setCellStyle(headStyle0);

    HSSFCell cell21 = row0.createCell(21);
    cell21.setCellValue("???");
    cell21.setCellStyle(headStyle0);

    HSSFCell cell22 = row0.createCell(22);
    cell22.setCellValue("??");
    cell22.setCellStyle(headStyle0);

    HSSFCell cell23 = row0.createCell(23);
    cell23.setCellValue("??");
    cell23.setCellStyle(headStyle0);

    HSSFCell cell24 = row0.createCell(24);
    cell24.setCellValue("");
    cell24.setCellStyle(headStyle0);

    for (int i = 0; i < list.size(); i++) {
        HSSFRow row1 = sheet.createRow(i + 1);

        HSSFCell cellr0 = row1.createCell(0);
        cellr0.setCellValue((String) list.get(i).get("CUST_CODE"));

        HSSFCell cellr1 = row1.createCell(1);
        cellr1.setCellValue((String) list.get(i).get("NAME"));

        HSSFCell cellr2 = row1.createCell(2);
        cellr2.setCellValue((String) list.get(i).get("CUST_NAME"));

        HSSFCell cellr3 = row1.createCell(3);
        cellr3.setCellValue((String) list.get(i).get("CORP_ORAGNIZATION_CODE"));

        HSSFCell cellr4 = row1.createCell(4);
        cellr4.setCellValue((String) list.get(i).get("CUST_AREA"));

        HSSFCell cellr5 = row1.createCell(5);
        cellr5.setCellValue((String) list.get(i).get("CORP_WORK_ADDRESS"));

        HSSFCell cellr6 = row1.createCell(6);
        cellr6.setCellValue((String) list.get(i).get("VIRTUAL_CODE"));

        HSSFCell cellr7 = row1.createCell(7);
        String s = null;
        int type = Integer.parseInt(list.get(i).get("STATETYPE").toString());
        switch (type) {
        case 0:
            s = "";
            break;
        case 1:
            s = "";
            break;
        case 2:
            s = "??";
            break;
        case 3:
            s = "";
            break;
        case 4:
            s = "";
            break;
        }
        cellr7.setCellValue(s);

        HSSFCell cellr8 = row1.createCell(8);
        cellr8.setCellValue((String) list.get(i).get("CORP_SETUP_DATE"));

        HSSFCell cellr9 = row1.createCell(9);
        double n = list.get(i).get("CORP_REGISTE_CAPITAL") == null ? 0
                : (Double) list.get(i).get("CORP_REGISTE_CAPITAL");
        cellr9.setCellValue(n);
        cellr9.setCellStyle(cellMoney);

        HSSFCell cellr10 = row1.createCell(10);
        double m = list.get(i).get("CORP_PAICLUP_CAPITAL") == null ? 0
                : (Double) list.get(i).get("CORP_PAICLUP_CAPITAL");
        cellr10.setCellValue(m);
        cellr10.setCellStyle(cellMoney);

        HSSFCell cellr11 = row1.createCell(11);
        cellr11.setCellValue((String) list.get(i).get("CORP_BUSINESS_LICENSE"));

        HSSFCell cellr12 = row1.createCell(12);
        cellr12.setCellValue((String) list.get(i).get("TAX_CODE"));

        HSSFCell cellr13 = row1.createCell(13);
        cellr13.setCellValue((String) list.get(i).get("CORP_TAX_CODE"));

        HSSFCell cellr14 = row1.createCell(14);
        cellr14.setCellValue((String) list.get(i).get("CORP_PERIOD_VALIDITY"));

        HSSFCell cellr15 = row1.createCell(15);
        cellr15.setCellValue((String) list.get(i).get("CORP_WORK_ADDRESS"));

        HSSFCell cellr16 = row1.createCell(16);
        cellr16.setCellValue((String) list.get(i).get("CORP_BUSINESS_RANGE"));

        HSSFCell cellr17 = row1.createCell(17);
        cellr17.setCellValue((String) list.get(i).get("CORP_COMPANY_ZIP"));

        HSSFCell cellr18 = row1.createCell(18);
        cellr18.setCellValue((String) list.get(i).get("CORP_COMPANY_WEBSITE"));

        HSSFCell cellr19 = row1.createCell(19);
        cellr19.setCellValue((String) list.get(i).get("CORP_COMPANY_EMAIL"));

        HSSFCell cellr20 = row1.createCell(20);
        cellr20.setCellValue((String) list.get(i).get("CORP_HEAD_SIGNATURE"));

        HSSFCell cellr21 = row1.createCell(21);
        cellr21.setCellValue((String) list.get(i).get("CORP_HS_IDCARD"));

        HSSFCell cellr22 = row1.createCell(22);
        cellr22.setCellValue((String) list.get(i).get("CORP_HS_LINK_MODE"));

        HSSFCell cellr23 = row1.createCell(23);
        cellr23.setCellValue((String) list.get(i).get("CORP_HS_HOME_ADDRESS"));

        HSSFCell cellr24 = row1.createCell(24);
        cellr24.setCellValue((String) list.get(i).get("REMARK"));
    }
    return efw.getWorkbook();
}

From source file:com.demo.common.extreme.view.XlsView.java

License:Apache License

private Map initStyles(HSSFWorkbook wb, short fontHeight) {
    Map result = new HashMap();
    HSSFCellStyle titleStyle = wb.createCellStyle();
    HSSFCellStyle textStyle = wb.createCellStyle();
    HSSFCellStyle boldStyle = wb.createCellStyle();
    HSSFCellStyle numericStyle = wb.createCellStyle();
    HSSFCellStyle numericStyleBold = wb.createCellStyle();
    HSSFCellStyle moneyStyle = wb.createCellStyle();
    HSSFCellStyle moneyStyleBold = wb.createCellStyle();
    HSSFCellStyle percentStyle = wb.createCellStyle();
    HSSFCellStyle percentStyleBold = wb.createCellStyle();

    // Add to export totals
    HSSFCellStyle moneyStyle_Totals = wb.createCellStyle();
    HSSFCellStyle naStyle_Totals = wb.createCellStyle();
    HSSFCellStyle numericStyle_Totals = wb.createCellStyle();
    HSSFCellStyle percentStyle_Totals = wb.createCellStyle();
    HSSFCellStyle textStyle_Totals = wb.createCellStyle();

    result.put("titleStyle", titleStyle);
    result.put("textStyle", textStyle);
    result.put("boldStyle", boldStyle);
    result.put("numericStyle", numericStyle);
    result.put("numericStyleBold", numericStyleBold);
    result.put("moneyStyle", moneyStyle);
    result.put("moneyStyleBold", moneyStyleBold);
    result.put("percentStyle", percentStyle);
    result.put("percentStyleBold", percentStyleBold);

    // Add to export totals
    result.put("moneyStyle_Totals", moneyStyle_Totals);
    result.put("naStyle_Totals", naStyle_Totals);
    result.put("numericStyle_Totals", numericStyle_Totals);
    result.put("percentStyle_Totals", percentStyle_Totals);
    result.put("textStyle_Totals", textStyle_Totals);

    HSSFDataFormat format = wb.createDataFormat();

    // Global fonts
    HSSFFont font = wb.createFont();//from  w  ww  .  j a  va2 s. c  o  m
    font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
    font.setColor(HSSFColor.BLACK.index);
    font.setFontName(HSSFFont.FONT_ARIAL);
    font.setFontHeightInPoints(fontHeight);

    HSSFFont fontBold = wb.createFont();
    fontBold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    fontBold.setColor(HSSFColor.BLACK.index);
    fontBold.setFontName(HSSFFont.FONT_ARIAL);
    fontBold.setFontHeightInPoints(fontHeight);

    // Money Style
    moneyStyle.setFont(font);
    moneyStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    moneyStyle.setDataFormat(format.getFormat(moneyFormat));

    // Money Style Bold
    moneyStyleBold.setFont(fontBold);
    moneyStyleBold.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    moneyStyleBold.setDataFormat(format.getFormat(moneyFormat));

    // Percent Style
    percentStyle.setFont(font);
    percentStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    percentStyle.setDataFormat(format.getFormat(percentFormat));

    // Percent Style Bold
    percentStyleBold.setFont(fontBold);
    percentStyleBold.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    percentStyleBold.setDataFormat(format.getFormat(percentFormat));

    // Standard Numeric Style
    numericStyle.setFont(font);
    numericStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);

    // Standard Numeric Style Bold
    numericStyleBold.setFont(fontBold);
    numericStyleBold.setAlignment(HSSFCellStyle.ALIGN_RIGHT);

    // Title Style
    titleStyle.setFont(font);
    titleStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    titleStyle.setBottomBorderColor(HSSFColor.BLACK.index);
    titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    titleStyle.setLeftBorderColor(HSSFColor.BLACK.index);
    titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
    titleStyle.setRightBorderColor(HSSFColor.BLACK.index);
    titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
    titleStyle.setTopBorderColor(HSSFColor.BLACK.index);
    titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

    // Standard Text Style
    textStyle.setFont(font);
    textStyle.setWrapText(true);

    // Standard Text Style
    boldStyle.setFont(fontBold);
    boldStyle.setWrapText(true);

    // Money Style Total
    moneyStyle_Totals.setFont(fontBold);
    moneyStyle_Totals.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    moneyStyle_Totals.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    moneyStyle_Totals.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    moneyStyle_Totals.setBottomBorderColor(HSSFColor.BLACK.index);
    moneyStyle_Totals.setBorderTop(HSSFCellStyle.BORDER_THIN);
    moneyStyle_Totals.setTopBorderColor(HSSFColor.BLACK.index);
    moneyStyle_Totals.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    moneyStyle_Totals.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    moneyStyle_Totals.setDataFormat(format.getFormat(moneyFormat));

    // n/a Style Total
    naStyle_Totals.setFont(fontBold);
    naStyle_Totals.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    naStyle_Totals.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    naStyle_Totals.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    naStyle_Totals.setBottomBorderColor(HSSFColor.BLACK.index);
    naStyle_Totals.setBorderTop(HSSFCellStyle.BORDER_THIN);
    naStyle_Totals.setTopBorderColor(HSSFColor.BLACK.index);
    naStyle_Totals.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    naStyle_Totals.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

    // Numeric Style Total
    numericStyle_Totals.setFont(fontBold);
    numericStyle_Totals.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    numericStyle_Totals.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    numericStyle_Totals.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    numericStyle_Totals.setBottomBorderColor(HSSFColor.BLACK.index);
    numericStyle_Totals.setBorderTop(HSSFCellStyle.BORDER_THIN);
    numericStyle_Totals.setTopBorderColor(HSSFColor.BLACK.index);
    numericStyle_Totals.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    numericStyle_Totals.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

    // Percent Style Total
    percentStyle_Totals.setFont(fontBold);
    percentStyle_Totals.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    percentStyle_Totals.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    percentStyle_Totals.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    percentStyle_Totals.setBottomBorderColor(HSSFColor.BLACK.index);
    percentStyle_Totals.setBorderTop(HSSFCellStyle.BORDER_THIN);
    percentStyle_Totals.setTopBorderColor(HSSFColor.BLACK.index);
    percentStyle_Totals.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    percentStyle_Totals.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    percentStyle_Totals.setDataFormat(format.getFormat(percentFormat));

    // Text Style Total
    textStyle_Totals.setFont(fontBold);
    textStyle_Totals.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    textStyle_Totals.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    textStyle_Totals.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    textStyle_Totals.setBottomBorderColor(HSSFColor.BLACK.index);
    textStyle_Totals.setBorderTop(HSSFCellStyle.BORDER_THIN);
    textStyle_Totals.setTopBorderColor(HSSFColor.BLACK.index);
    textStyle_Totals.setAlignment(HSSFCellStyle.ALIGN_LEFT);
    textStyle_Totals.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

    return result;
}

From source file:com.github.gaborfeher.grantmaster.framework.base.ExcelExporter.java

License:Open Source License

private void setExcelCell(HSSFWorkbook workbook, Object cellValue, Cell excelCell) {
    if (cellValue instanceof BigDecimal) {
        double doubleValue = ((BigDecimal) cellValue).doubleValue();
        excelCell.setCellValue(doubleValue);
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        HSSFDataFormat hssfDataFormat = workbook.createDataFormat();
        cellStyle.setDataFormat(hssfDataFormat.getFormat("#,##0.00"));
        excelCell.setCellStyle(cellStyle);
        excelCell.setCellType(Cell.CELL_TYPE_NUMERIC);
    } else if (cellValue instanceof LocalDate) {
        LocalDate localDate = (LocalDate) cellValue;
        Calendar calendar = Calendar.getInstance();
        calendar.set(localDate.getYear(), localDate.getMonthValue() - 1, localDate.getDayOfMonth());
        excelCell.setCellValue(calendar);

        String excelFormatPattern = DateFormatConverter.convert(Locale.US, "yyyy-MM-DD");
        CellStyle cellStyle = workbook.createCellStyle();
        DataFormat poiFormat = workbook.createDataFormat();
        cellStyle.setDataFormat(poiFormat.getFormat(excelFormatPattern));
        excelCell.setCellStyle(cellStyle);
    } else if (cellValue != null) {
        excelCell.setCellValue(cellValue.toString());
    }/*from w w  w .ja  v a  2s .  c  o m*/
}

From source file:com.github.gujou.deerbelling.sonarqube.service.XlsTasksGenerator.java

License:Open Source License

public static File generateFile(Project sonarProject, FileSystem sonarFileSystem, String sonarUrl,
        String sonarLogin, String sonarPassword) {

    short formatIndex;
    HSSFDataFormat dataFormat = null;
    FileOutputStream out = null;//from  www. ja  v  a  2 s  .  com
    HSSFWorkbook workbook = null;

    String filePath = sonarFileSystem.workDir().getAbsolutePath() + File.separator + "tasks_report_"
            + sonarProject.getEffectiveKey().replace(':', '-') + "."
            + ReportsKeys.TASKS_REPORT_TYPE_XLS_EXTENSION;

    File resultFile = new File(filePath);

    try {
        out = new FileOutputStream(resultFile);

        workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Tasks list");

        // Date format.
        dataFormat = workbook.createDataFormat();
        formatIndex = dataFormat.getFormat("yyyy-MM-ddTHH:mm:ss");
        HSSFCellStyle dateStyle = workbook.createCellStyle();
        dateStyle.setDataFormat(formatIndex);

        Issues rootIssue = IssueGateway.getOpenIssues(sonarProject.getEffectiveKey(), sonarUrl, sonarLogin,
                sonarPassword);

        if (rootIssue == null) {
            return null;
        }

        DataValidationHelper validationHelper = new HSSFDataValidationHelper(sheet);
        DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(
                new String[] { "OPENED", "CONFIRMED", "REOPENED", "RESOLVED", "CLOSE" });
        CellRangeAddressList addressList = new CellRangeAddressList(1, rootIssue.getIssues().size() + 1,
                STATUS_COLUMN_INDEX, STATUS_COLUMN_INDEX);
        DataValidation dataValidation = validationHelper.createValidation(constraint, addressList);
        dataValidation.setSuppressDropDownArrow(false);
        sheet.addValidationData(dataValidation);

        int rownum = 0;

        Row row = sheet.createRow(rownum++);
        row.createCell(STATUS_COLUMN_INDEX).setCellValue("Status");
        row.createCell(SEVERITY_COLUMN_INDEX).setCellValue("Severity");
        row.createCell(COMPONENT_COLUMN_INDEX).setCellValue("Component");
        row.createCell(LINE_COLUMN_INDEX).setCellValue("Line");
        row.createCell(MESSAGE_COLUMN_INDEX).setCellValue("Message");
        row.createCell(AUTHOR_COLUMN_INDEX).setCellValue("Author");
        row.createCell(ASSIGNED_COLUMN_INDEX).setCellValue("Assigned");
        row.createCell(CREATION_DATE_COLUMN_INDEX).setCellValue("CreationDate");
        row.createCell(UPDATE_DATE_COLUMN_INDEX).setCellValue("UpdateDate");
        row.createCell(COMPONENT_PATH_COLUMN_INDEX).setCellValue("Path");

        for (Issue issue : rootIssue.getIssues()) {
            if (issue != null) {
                row = sheet.createRow(rownum++);
                int componentIndex = 0;
                if (issue.getComponent() != null) {
                    componentIndex = issue.getComponent().lastIndexOf('/');
                }
                String component;
                String path;
                if (componentIndex > 0) {
                    component = issue.getComponent().substring(componentIndex + 1);
                    path = issue.getComponent().substring(0, componentIndex);
                } else {
                    component = issue.getComponent();
                    path = "";
                }

                // Set values.
                row.createCell(STATUS_COLUMN_INDEX).setCellValue(issue.getStatus());
                row.createCell(SEVERITY_COLUMN_INDEX).setCellValue(issue.getSeverity());
                row.createCell(COMPONENT_COLUMN_INDEX).setCellValue(component);
                row.createCell(LINE_COLUMN_INDEX).setCellValue(issue.getLine());
                row.createCell(MESSAGE_COLUMN_INDEX).setCellValue(issue.getMessage());
                row.createCell(AUTHOR_COLUMN_INDEX).setCellValue(issue.getAuthor());
                row.createCell(ASSIGNED_COLUMN_INDEX).setCellValue(issue.getAssignee());
                row.createCell(CREATION_DATE_COLUMN_INDEX).setCellValue(issue.getCreationDate());
                row.createCell(UPDATE_DATE_COLUMN_INDEX).setCellValue(issue.getUpdateDate());
                row.createCell(COMPONENT_PATH_COLUMN_INDEX).setCellValue(path);

                // Set date style to date column.
                row.getCell(CREATION_DATE_COLUMN_INDEX).setCellStyle(dateStyle);
                row.getCell(UPDATE_DATE_COLUMN_INDEX).setCellStyle(dateStyle);
            }
        }

        // Auto-size sheet columns.
        sheet.autoSizeColumn(STATUS_COLUMN_INDEX);
        sheet.autoSizeColumn(STATUS_COLUMN_INDEX);
        sheet.autoSizeColumn(COMPONENT_COLUMN_INDEX);
        sheet.autoSizeColumn(LINE_COLUMN_INDEX);
        sheet.autoSizeColumn(MESSAGE_COLUMN_INDEX);
        sheet.autoSizeColumn(AUTHOR_COLUMN_INDEX);
        sheet.autoSizeColumn(ASSIGNED_COLUMN_INDEX);
        sheet.autoSizeColumn(CREATION_DATE_COLUMN_INDEX);
        sheet.autoSizeColumn(UPDATE_DATE_COLUMN_INDEX);
        sheet.autoSizeColumn(COMPONENT_PATH_COLUMN_INDEX);

        workbook.write(out);

    } catch (FileNotFoundException e) {

        // TODO manage error.
        e.printStackTrace();
    } catch (IOException e) {

        // TODO manage error.
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(workbook);
        IOUtils.closeQuietly(out);
    }

    return resultFile;
}

From source file:com.mss.mirage.marketing.MarketingServiceImpl.java

License:Open Source License

public String generateInvestmentXls(String queryString) throws ServiceLocatorException {
    String filePath = "";
    StringBuffer sb = null;//from  w  w  w  .ja  va2  s  . c  o m

    Connection connection = null;
    /**
     * preStmt,preStmtTemp are reference variable for PreparedStatement .
     */
    PreparedStatement preStmt = null;

    /**
     * The queryString is useful to get queryString result to the particular
     * jsp page
     */
    /**
     * The statement is useful to execute the above queryString
     */
    ResultSet resultSet = null;
    HashMap map = null;
    double totalAmount = 0.0;
    double totalOpprtunity = 0.0;
    double floortotalsum = 0.0;
    String generatedPath = "";
    List finalList = new ArrayList();
    try {
        generatedPath = com.mss.mirage.util.Properties.getProperty("Marketing.Investment.Path");
        File file = new File(generatedPath);
        if (!file.exists()) {
            file.mkdirs();
        }

        FileOutputStream fileOut = new FileOutputStream(file.getAbsolutePath() + "/Investment.xls");
        connection = ConnectionProvider.getInstance().getConnection();
        String query = null;
        if (!"".equals(queryString)) {
            query = queryString;
        } else {
            query = "SELECT * from vwInvestments WHERE STATUS='Active' ORDER BY createdDate DESC";
        }
        String reportToName = "";
        List teamList = null;
        int j = 1;
        //  System.out.println("query...."+query);
        preStmt = connection.prepareStatement(query);
        resultSet = preStmt.executeQuery();
        while (resultSet.next()) {
            String InvestmentName = resultSet.getString("Inv_Name");
            String TotalExpenses = resultSet.getString("TotalExpenses");
            String StartDate = resultSet.getString("StartDate");
            String EndDate = resultSet.getString("EndDate");
            String Location = resultSet.getString("Location");
            String InvestmentType = resultSet.getString("InvestmentType");
            String TotalOpprtunity = resultSet.getString("TotalOpprtunity");
            totalAmount = totalAmount + resultSet.getDouble("TotalExpenses");
            totalOpprtunity = totalOpprtunity + resultSet.getDouble("TotalOpprtunity");
            map = new HashMap();
            map.put("SNO", String.valueOf(j));
            map.put("InvestmentName", InvestmentName);
            map.put("TotalExpenses", TotalExpenses);
            map.put("StartDate", StartDate);
            map.put("EndDate", EndDate);
            map.put("Location", Location);
            if ("S".equalsIgnoreCase(InvestmentType)) {
                map.put("InvestmentType", "Lead Source");
            } else if ("P".equalsIgnoreCase(InvestmentType)) {
                map.put("InvestmentType", "Lead Pass");
            }
            map.put("TotalOpprtunity", TotalOpprtunity);
            map.put("Sum", totalAmount);
            map.put("SumOpp", totalOpprtunity);

            finalList.add(map);
            j++;

        }

        if (finalList.size() > 0) {
            filePath = file.getAbsolutePath() + "/Investment.xls";
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            HSSFSheet sheet = hssfworkbook.createSheet("Investment Sheet");

            HSSFFont timesBoldFont1 = hssfworkbook.createFont();
            timesBoldFont1.setFontHeightInPoints((short) 13);
            timesBoldFont1.setColor(HSSFColor.BLACK.index);
            timesBoldFont1.setFontName("Arial");

            HSSFCellStyle cellColor = hssfworkbook.createCellStyle();
            cellColor.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
            cellColor.setAlignment(HSSFCellStyle.ALIGN_LEFT);
            cellColor.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellColor.setBorderTop((short) 1); // single line border
            cellColor.setBorderBottom((short) 1); // single line border
            cellColor.setFont(timesBoldFont1);

            HSSFCellStyle cellColor1 = hssfworkbook.createCellStyle();

            cellColor1.setFillForegroundColor(HSSFColor.WHITE.index);
            cellColor1.setAlignment(HSSFCellStyle.ALIGN_LEFT);
            cellColor1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellColor1.setBorderTop((short) 1); // single line border
            cellColor1.setBorderBottom((short) 1); // single line border
            cellColor1.setFont(timesBoldFont1);

            HSSFCellStyle cs = hssfworkbook.createCellStyle();

            HSSFCellStyle headercs = hssfworkbook.createCellStyle();
            headercs.setFillForegroundColor(HSSFColor.BLUE.index);
            headercs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            headercs.setBorderTop((short) 1); // single line border
            headercs.setBorderBottom((short) 1); // single line border
            // cs.setFont(timesBoldFont1);

            HSSFFont timesBoldFont = hssfworkbook.createFont();
            timesBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            timesBoldFont.setFontHeightInPoints((short) 13);
            timesBoldFont.setColor(HSSFColor.WHITE.index);
            timesBoldFont.setFontName("Calibri");
            headercs.setFont(timesBoldFont);
            // cs.setFont(timesBoldFont);
            HSSFFont footerFont = hssfworkbook.createFont();
            footerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            timesBoldFont.setFontHeightInPoints((short) 13);
            footerFont.setFontName("Calibri");

            HSSFCellStyle footercs = hssfworkbook.createCellStyle();
            footercs.setFont(footerFont);

            HSSFDataFormat df = hssfworkbook.createDataFormat();
            HSSFRow row = sheet.createRow((short) 0);
            HSSFCell cell = row.createCell((short) 0);

            HSSFCell cell1 = row.createCell((short) 1);

            HSSFCell cell2 = row.createCell((short) 2);
            HSSFCell cell3 = row.createCell((short) 3);

            HSSFCell cell4 = row.createCell((short) 4);
            HSSFCell cell5 = row.createCell((short) 5);
            HSSFCell cell6 = row.createCell((short) 6);
            HSSFCell cell7 = row.createCell((short) 7);

            cell.setCellValue("SNO");
            cell1.setCellValue("InvestmentName");
            cell2.setCellValue("TotalExpenses");
            cell3.setCellValue("StartDate");
            cell4.setCellValue("EndDate");
            cell5.setCellValue("Location");
            cell6.setCellValue("InvestmentType");
            cell7.setCellValue("TotalOpprtunity");

            cell.setCellStyle(headercs);
            cell1.setCellStyle(headercs);
            cell2.setCellStyle(headercs);
            cell3.setCellStyle(headercs);
            cell4.setCellStyle(headercs);
            cell5.setCellStyle(headercs);
            cell6.setCellStyle(headercs);
            cell7.setCellStyle(headercs);

            int count = 1;

            if (finalList.size() > 0) {
                Map stateHistorylMap = null;
                for (int i = 0; i < finalList.size(); i++) {
                    stateHistorylMap = (Map) finalList.get(i);
                    row = sheet.createRow((short) count++);
                    cell = row.createCell((short) 0);

                    cell1 = row.createCell((short) 1);
                    cell2 = row.createCell((short) 2);
                    cell3 = row.createCell((short) 3);
                    cell4 = row.createCell((short) 4);
                    cell5 = row.createCell((short) 5);
                    cell6 = row.createCell((short) 6);
                    cell7 = row.createCell((short) 7);

                    cell.setCellValue((String) stateHistorylMap.get("SNO"));
                    cell1.setCellValue((String) stateHistorylMap.get("InvestmentName"));
                    HSSFCellStyle css1 = hssfworkbook.createCellStyle();
                    HSSFCellStyle css2 = hssfworkbook.createCellStyle();
                    css1.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
                    css1.setAlignment(HSSFCellStyle.ALIGN_LEFT);
                    css1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                    css1.setBorderTop((short) 1); // single line border
                    css1.setBorderBottom((short) 1); // single line border
                    css1.setFont(timesBoldFont1);

                    HSSFDataFormat df1 = hssfworkbook.createDataFormat();
                    css1.setDataFormat(df1.getFormat("#,##0.0"));
                    css2.setDataFormat(df1.getFormat("#,##0.0"));
                    css2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
                    css2.setFont(timesBoldFont1);
                    cell2.setCellValue(Convert.toDouble(stateHistorylMap.get("TotalExpenses")));
                    cell3.setCellValue((String) stateHistorylMap.get("StartDate"));
                    cell4.setCellValue((String) stateHistorylMap.get("EndDate"));
                    cell5.setCellValue((String) stateHistorylMap.get("Location"));
                    cell6.setCellValue((String) stateHistorylMap.get("InvestmentType"));
                    cell7.setCellValue((String) stateHistorylMap.get("TotalOpprtunity"));

                    if (count % 2 == 0) {
                        cell.setCellStyle(cellColor1);
                        cell1.setCellStyle(cellColor1);
                        cell2.setCellStyle(css2);
                        cell3.setCellStyle(cellColor1);
                        cell4.setCellStyle(cellColor1);
                        cell5.setCellStyle(cellColor1);
                        cell6.setCellStyle(cellColor1);
                        cell7.setCellStyle(cellColor1);

                    } else {
                        cell.setCellStyle(cellColor);
                        cell1.setCellStyle(cellColor);
                        cell2.setCellStyle(css1);
                        cell3.setCellStyle(cellColor);
                        cell4.setCellStyle(cellColor);
                        cell5.setCellStyle(cellColor);
                        cell6.setCellStyle(cellColor);
                        cell7.setCellStyle(cellColor);
                    }
                }
                row = sheet.createRow((short) count++);
                cell = row.createCell((short) 0);

                cell1 = row.createCell((short) 1);
                cell2 = row.createCell((short) 2);
                cell3 = row.createCell((short) 3);
                cell4 = row.createCell((short) 4);
                cell5 = row.createCell((short) 5);
                cell6 = row.createCell((short) 6);
                cell7 = row.createCell((short) 7);
                cell.setCellValue("");
                cell7.setCellValue("");

                cell.setCellStyle(footercs);
                cell1.setCellStyle(footercs);
                cell2.setCellStyle(footercs);
                cell3.setCellStyle(footercs);

                cell4.setCellStyle(footercs);
                cell5.setCellStyle(footercs);
                cell6.setCellStyle(footercs);
                cell7.setCellStyle(footercs);
            }
            HSSFCellStyle totalSum = hssfworkbook.createCellStyle();
            totalSum.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
            totalSum.setAlignment(HSSFCellStyle.ALIGN_LEFT);
            totalSum.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            totalSum.setBorderTop((short) 1); // single line border
            totalSum.setBorderBottom((short) 1); // single line border
            totalSum.setFont(timesBoldFont1);
            HSSFCellStyle totalSum1 = hssfworkbook.createCellStyle();
            totalSum1.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
            totalSum1.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
            totalSum1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            totalSum1.setBorderTop((short) 1); // single line border
            totalSum1.setBorderBottom((short) 1); // single line border
            totalSum1.setFont(timesBoldFont1);

            HSSFDataFormat totalSumdf1 = hssfworkbook.createDataFormat();

            totalSum.setDataFormat((short) 7);
            HSSFCellStyle test = hssfworkbook.createCellStyle();
            HSSFDataFormat testdf = hssfworkbook.createDataFormat();

            sheet.autoSizeColumn((int) 0);
            sheet.autoSizeColumn((int) 3);
            sheet.autoSizeColumn((int) 4);
            sheet.setColumnWidth(1, 50 * 256);
            sheet.setColumnWidth(2, 35 * 256);
            sheet.setColumnWidth(5, 25 * 256);
            sheet.setColumnWidth(6, 25 * 256);
            sheet.setColumnWidth(7, 25 * 256);
            BigDecimal bb, bc, cc, cd;
            bb = new BigDecimal(totalAmount);
            bc = bb.setScale(2, RoundingMode.CEILING);
            cc = new BigDecimal(totalOpprtunity);
            cd = cc.setScale(2, RoundingMode.CEILING);
            totalSum.setDataFormat(testdf.getFormat("#,##0.0"));

            cell.setCellStyle(totalSum);

            cell1.setCellValue("Sum ");
            cell1.setCellStyle(totalSum1);
            cell2.setCellValue(bc.longValue());

            cell2.setCellStyle(totalSum);
            cell3.setCellStyle(totalSum);
            cell4.setCellStyle(totalSum);
            cell5.setCellStyle(totalSum);

            cell6.setCellStyle(totalSum);
            cell7.setCellValue(cd.longValue());

            cell7.setCellStyle(totalSum);

            hssfworkbook.write(fileOut);
            fileOut.flush();
            fileOut.close();

        }

    } catch (FileNotFoundException fne) {

        fne.printStackTrace();
    } catch (IOException ioe) {

        ioe.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
                resultSet = null;
            }
            if (preStmt != null) {
                preStmt.close();
                preStmt = null;
            }
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (Exception se) {
            se.printStackTrace();
        }
    }

    return filePath;

}

From source file:com.openitech.util.HSSFWrapper.java

License:Apache License

public static final HSSFWorkbook getWorkbook(JTable source, boolean countRows) {
    HSSFWorkbook xls_workbook = new HSSFWorkbook();
    HSSFSheet xls_sheet = xls_workbook.createSheet("Pregled podatkov");
    HSSFPrintSetup xls_sheet_printsetup = xls_sheet.getPrintSetup();
    xls_sheet_printsetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
    xls_sheet_printsetup.setFitWidth((short) 1);

    TableColumnModel columnModel = source.getColumnModel();
    Enumeration<TableColumn> columns = columnModel.getColumns();

    HSSFRow xls_row = xls_sheet.createRow(0);
    short cell = 1;
    HSSFCellStyle xls_header_cell_style = xls_workbook.createCellStyle();
    HSSFFont xls_header_font = xls_workbook.createFont();

    xls_header_font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

    xls_header_cell_style.setFont(xls_header_font);
    xls_header_cell_style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    xls_header_cell_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    xls_header_cell_style.setFillForegroundColor(new HSSFColor.GREY_25_PERCENT().getIndex());
    //xls_header_cell_style.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);

    java.util.Map<String, HSSFCellStyle> cellStyles = new java.util.HashMap<String, HSSFCellStyle>();

    HSSFDataFormat xls_data_format = xls_workbook.createDataFormat();

    HSSFCellStyle xls_date_cell_style = xls_workbook.createCellStyle();
    xls_date_cell_style.setDataFormat(xls_data_format.getFormat("d.m.yyyy"));
    cellStyles.put("d.m.yyyy", xls_date_cell_style);

    HSSFCellStyle xls_double_cell_style = xls_workbook.createCellStyle();
    xls_double_cell_style.setDataFormat(xls_data_format.getFormat("#,##0.00"));
    cellStyles.put("#,##0.00", xls_double_cell_style);

    while (columns.hasMoreElements()) {
        TableColumn column = columns.nextElement();

        HSSFCell xls_cell = xls_row.createCell(cell++);
        xls_cell.setCellValue(new HSSFRichTextString(column.getHeaderValue().toString()));
        xls_cell.setCellStyle(xls_header_cell_style);
    }/*from   w w  w .  ja va  2s  .c o m*/

    TableModel tableModel = source.getModel();
    DbTableModel dbTableModel = (tableModel instanceof DbTableModel) ? (DbTableModel) tableModel : null;
    Integer fetchSize = null;

    if (dbTableModel != null) {
        try {
            fetchSize = dbTableModel.getDataSource().getFetchSize();
            dbTableModel.getDataSource().setFetchSize(2000);
        } catch (SQLException ex) {
            Logger.getLogger(HSSFWrapper.class.getName()).log(Level.WARNING, null, ex);
            fetchSize = null;
        }
    }

    short row = 1;

    JWProgressMonitor progress = new JWProgressMonitor((java.awt.Frame) null);

    progress.setTitle("Izvoz podatkov v Excel");
    progress.setMax(tableModel.getRowCount());

    progress.setVisible(true);

    try {
        while (row <= tableModel.getRowCount()) {
            xls_row = xls_sheet.createRow(row);
            cell = 0;

            HSSFCell xls_cell = xls_row.createCell(cell++);
            if (countRows) {
                xls_cell.setCellValue(new HSSFRichTextString(Short.toString(row)));
            }

            while (cell <= columnModel.getColumnCount()) {
                Object value = tableModel.getValueAt(source.convertRowIndexToModel(row - 1),
                        source.convertColumnIndexToModel(cell - 1));
                if (value != null) {
                    if (value instanceof DbTableModel.ColumnDescriptor.ValueMethod) {
                        DbTableModel.ColumnDescriptor.ValueMethod vm = (DbTableModel.ColumnDescriptor.ValueMethod) value;

                        if (vm.getColumnNames().size() == 1) {
                            java.util.List<Object> values = vm.getValues();
                            java.util.List<String> cellFormats = vm.getCellFormats();

                            for (String cellFormat : cellFormats) {
                                if (cellFormat != null) {
                                    if (!cellStyles.containsKey(cellFormat)) {
                                        HSSFCellStyle xls_cell_style = xls_workbook.createCellStyle();
                                        xls_cell_style.setDataFormat(xls_data_format.getFormat(cellFormat));
                                        cellStyles.put(cellFormat, xls_cell_style);
                                    }
                                }
                            }

                            Object vm_value = values.get(0);
                            HSSFCellStyle xls_cell_style = cellFormats.get(0) == null ? null
                                    : cellStyles.get(cellFormats.get(0));

                            if (vm_value != null) {
                                xls_cell = xls_row.createCell(cell);

                                if (vm_value instanceof java.util.Date) {
                                    xls_cell.setCellValue((java.util.Date) vm_value);
                                    xls_cell.setCellStyle(
                                            xls_cell_style == null ? xls_date_cell_style : xls_cell_style);
                                } else if (vm_value instanceof java.lang.Number) {
                                    xls_cell.setCellValue(((java.lang.Number) vm_value).doubleValue());
                                    if ((vm_value instanceof java.math.BigDecimal)
                                            || (vm_value instanceof java.lang.Double)
                                            || (vm_value instanceof java.lang.Float)) {
                                        xls_cell.setCellStyle(xls_cell_style == null ? xls_double_cell_style
                                                : xls_cell_style);
                                    }
                                } else if (vm_value instanceof java.lang.Boolean) {
                                    xls_cell.setCellValue(((java.lang.Boolean) vm_value).booleanValue());
                                } else {
                                    xls_cell.setCellValue(new HSSFRichTextString(value.toString()));
                                }
                            }
                        } else {
                            xls_cell = xls_row.createCell(cell);
                            xls_cell.setCellValue(new HSSFRichTextString(value.toString()));
                        }
                    } else {
                        xls_cell = xls_row.createCell(cell);
                        xls_cell.setCellValue(new HSSFRichTextString(value.toString()));
                    }
                }
                cell++;
            }

            row++;
            progress.next();
        }

        for (cell = 0; cell <= columnModel.getColumnCount(); cell++) {
            xls_sheet.autoSizeColumn(cell);
        }

        xls_sheet.createFreezePane(1, 1);
    } finally {
        progress.setVisible(false);

        if (fetchSize != null) {
            try {
                dbTableModel.getDataSource().setFetchSize(fetchSize);
            } catch (SQLException ex) {
                Logger.getLogger(HSSFWrapper.class.getName()).log(Level.WARNING, null, ex);
            }
        }
    }

    return xls_workbook;
}