Example usage for org.apache.poi.hssf.usermodel HSSFFont setFontName

List of usage examples for org.apache.poi.hssf.usermodel HSSFFont setFontName

Introduction

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

Prototype


public void setFontName(String name) 

Source Link

Document

set the name for the font (i.e.

Usage

From source file:com.haulmont.yarg.formatters.impl.xls.hints.CustomCellStyleHint.java

License:Apache License

@Override
public void apply() {
    for (DataObject dataObject : data) {
        HSSFCell templateCell = dataObject.templateCell;
        HSSFCell resultCell = dataObject.resultCell;
        BandData bandData = dataObject.bandData;

        HSSFWorkbook resultWorkbook = resultCell.getSheet().getWorkbook();
        HSSFWorkbook templateWorkbook = templateCell.getSheet().getWorkbook();

        String templateCellValue = templateCell.getStringCellValue();

        Matcher matcher = pattern.matcher(templateCellValue);
        if (matcher.find()) {
            String paramName = matcher.group(1);
            String styleName = (String) bandData.getParameterValue(paramName);
            if (styleName == null)
                continue;

            HSSFCellStyle cellStyle = styleCache.getStyleByName(styleName);
            if (cellStyle == null)
                continue;

            HSSFCellStyle resultStyle = styleCache.getNamedCachedStyle(cellStyle);

            if (resultStyle == null) {
                HSSFCellStyle newStyle = resultWorkbook.createCellStyle();
                // color
                newStyle.setFillBackgroundColor(cellStyle.getFillBackgroundColor());
                newStyle.setFillForegroundColor(cellStyle.getFillForegroundColor());
                newStyle.setFillPattern(cellStyle.getFillPattern());

                // borders
                newStyle.setBorderLeft(cellStyle.getBorderLeft());
                newStyle.setBorderRight(cellStyle.getBorderRight());
                newStyle.setBorderTop(cellStyle.getBorderTop());
                newStyle.setBorderBottom(cellStyle.getBorderBottom());

                // border colors
                newStyle.setLeftBorderColor(cellStyle.getLeftBorderColor());
                newStyle.setRightBorderColor(cellStyle.getRightBorderColor());
                newStyle.setBottomBorderColor(cellStyle.getBottomBorderColor());
                newStyle.setTopBorderColor(cellStyle.getTopBorderColor());

                // alignment
                newStyle.setAlignment(cellStyle.getAlignment());
                newStyle.setVerticalAlignment(cellStyle.getVerticalAlignment());
                // misc
                DataFormat dataFormat = resultWorkbook.getCreationHelper().createDataFormat();
                newStyle.setDataFormat(dataFormat.getFormat(cellStyle.getDataFormatString()));
                newStyle.setHidden(cellStyle.getHidden());
                newStyle.setLocked(cellStyle.getLocked());
                newStyle.setIndention(cellStyle.getIndention());
                newStyle.setRotation(cellStyle.getRotation());
                newStyle.setWrapText(cellStyle.getWrapText());
                // font
                HSSFFont cellFont = cellStyle.getFont(templateWorkbook);
                HSSFFont newFont = fontCache.getFontByTemplate(cellFont);

                if (newFont == null) {
                    newFont = resultWorkbook.createFont();

                    newFont.setFontName(cellFont.getFontName());
                    newFont.setItalic(cellFont.getItalic());
                    newFont.setStrikeout(cellFont.getStrikeout());
                    newFont.setTypeOffset(cellFont.getTypeOffset());
                    newFont.setBoldweight(cellFont.getBoldweight());
                    newFont.setCharSet(cellFont.getCharSet());
                    newFont.setColor(cellFont.getColor());
                    newFont.setUnderline(cellFont.getUnderline());
                    newFont.setFontHeight(cellFont.getFontHeight());
                    newFont.setFontHeightInPoints(cellFont.getFontHeightInPoints());
                    fontCache.addCachedFont(cellFont, newFont);
                }/*from   w w w. java 2s. c o m*/
                newStyle.setFont(newFont);

                resultStyle = newStyle;
                styleCache.addCachedNamedStyle(cellStyle, resultStyle);
            }

            fixNeighbourCellBorders(cellStyle, resultCell);

            resultCell.setCellStyle(resultStyle);

            Sheet sheet = resultCell.getSheet();
            for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
                CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
                if (mergedRegion.isInRange(resultCell.getRowIndex(), resultCell.getColumnIndex())) {

                    int firstRow = mergedRegion.getFirstRow();
                    int lastRow = mergedRegion.getLastRow();
                    int firstCol = mergedRegion.getFirstColumn();
                    int lastCol = mergedRegion.getLastColumn();

                    for (int row = firstRow; row <= lastRow; row++)
                        for (int col = firstCol; col <= lastCol; col++)
                            sheet.getRow(row).getCell(col).setCellStyle(resultStyle);

                    // cell includes only in one merged region
                    break;
                }
            }
        }
    }
}

From source file:com.idega.block.datareport.business.SimpleReportBusinessBean.java

License:Open Source License

public void writeSimpleExcelFile(JRDataSource reportData, String nameOfReport, String filePathAndName,
        ReportDescription description) throws IOException {
    if (nameOfReport == null || "".equals(nameOfReport)) {
        nameOfReport = NAME_OF_REPORT;/*from   ww w  .ja  v  a 2s  .  com*/
    }
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(TextSoap.encodeToValidExcelSheetName(nameOfReport));
    int rowIndex = 0;

    //-- Report Name --//
    // Create a row and put some cells in it. Rows are 0 based.
    HSSFRow row = sheet.createRow((short) rowIndex++);
    // Create a cell and put a value in it.
    HSSFCell cell = row.createCell((short) 0);

    // Create a new font and alter it.
    HSSFFont font = wb.createFont();
    font.setFontHeightInPoints((short) 24);
    font.setFontName(REPORT_FONT);
    font.setItalic(true);
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

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

    // Create a cell and put a value in it.
    cell.setCellValue(nameOfReport);
    cell.setCellStyle(style);

    //-- Report Parameters --//
    rowIndex++;
    HSSFRow row1 = null;
    String parameterString = "";
    List labels = description.getListOfHeaderParameterLabelKeys();
    List parameters = description.getListOfHeaderParameterKeys();
    Iterator labelIter = labels.iterator();
    Iterator parameterIter = parameters.iterator();
    boolean newLineForeEachParameter = description.doCreateNewLineForEachParameter();
    while (labelIter.hasNext() && parameterIter.hasNext()) {
        String label = description.getParameterOrLabelName((String) labelIter.next());
        String parameter = description.getParameterOrLabelName((String) parameterIter.next());
        if (newLineForeEachParameter) {
            row1 = sheet.createRow((short) rowIndex++);
            row1.createCell((short) 0).setCellValue(label + " " + parameter);
        } else {
            parameterString += label + " " + parameter + "      ";
        }
    }
    if (!newLineForeEachParameter) {
        row1 = sheet.createRow((short) rowIndex++);
        row1.createCell((short) 0).setCellValue(parameterString);
    }
    rowIndex++;

    //-- Report ColumnHeader --//
    List fields = description.getListOfFields();
    HSSFRow headerRow = sheet.createRow((short) rowIndex++);

    HSSFCellStyle headerCellStyle = wb.createCellStyle();

    headerCellStyle.setWrapText(true);
    headerCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
    headerCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

    HSSFFont headerCellFont = wb.createFont();
    //headerCellFont.setFontHeightInPoints((short)12);
    headerCellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    headerCellStyle.setFont(headerCellFont);

    int colIndex = 0;
    int columnWithUnit = 256; // the unit is 1/256 of a character
    int numberOfCharactersPerLineInLongTextFields = 60;
    int numberOfCharactersPerLineInRatherLongTextFields = 35;
    int numberOfCharactersPerLineInUndifinedTextFields = 20;

    for (Iterator iter = fields.iterator(); iter.hasNext(); colIndex++) {
        ReportableField field = (ReportableField) iter.next();
        HSSFCell headerCell = headerRow.createCell((short) colIndex);
        headerCell.setCellValue(description.getColumnName(field));
        headerCell.setCellStyle(headerCellStyle);

        //column width
        int fieldsMaxChar = field.getMaxNumberOfCharacters();
        int colWith = numberOfCharactersPerLineInRatherLongTextFields * columnWithUnit; //default, can be rather long text
        if (fieldsMaxChar > 0 && fieldsMaxChar < numberOfCharactersPerLineInRatherLongTextFields) {
            colWith = (fieldsMaxChar + 1) * columnWithUnit; // short fields
        } else if (fieldsMaxChar > 500) { // when the field is set to be able to contain very long text
            colWith = numberOfCharactersPerLineInLongTextFields * columnWithUnit; //can be very long text
        } else if (fieldsMaxChar < 0) {
            colWith = numberOfCharactersPerLineInUndifinedTextFields * columnWithUnit;
        }
        sheet.setColumnWidth((short) colIndex, (short) colWith);

    }

    //-- Report ColumnDetail --//
    try {
        HSSFCellStyle dataCellStyle = wb.createCellStyle();
        dataCellStyle.setWrapText(true);
        dataCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
        sheet.createFreezePane(0, rowIndex);

        while (reportData.next()) {
            HSSFRow dataRow = sheet.createRow((short) rowIndex++);
            colIndex = 0;
            for (Iterator iter = fields.iterator(); iter.hasNext(); colIndex++) {
                ReportableField field = (ReportableField) iter.next();
                HSSFCell dataCell = dataRow.createCell((short) colIndex);
                Object fieldValue = reportData.getFieldValue(field);
                if (fieldValue != null) {
                    dataCell.setCellValue(String.valueOf(fieldValue));
                }
                dataCell.setCellStyle(dataCellStyle);
            }
        }
    } catch (JRException e) {
        //-- Exception fetching data --//
        HSSFRow exceptionRow = sheet.createRow((short) rowIndex++);
        HSSFCell exceptionCell = exceptionRow.createCell((short) 0);

        // Create a new font and alter it.
        HSSFFont exceptionFont = wb.createFont();
        exceptionFont.setFontName(REPORT_FONT);
        exceptionFont.setItalic(true);

        // Fonts are set into a style so create a new one to use.
        HSSFCellStyle exceptionStyle = wb.createCellStyle();
        exceptionStyle.setFont(exceptionFont);

        // Create a cell and put a value in it.
        exceptionCell.setCellValue("Error occurred while getting data. Check log for more details.");
        exceptionCell.setCellStyle(exceptionStyle);

        e.printStackTrace();
    }

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream(filePathAndName);
    wb.write(fileOut);
    fileOut.close();
}

From source file:com.insoul.ti.controller.ContestProjectEntryController.java

@RequestMapping("/download")
public ModelAndView download(HttpServletResponse response) throws Exception {
    HSSFWorkbook workbook = new HSSFWorkbook();// Excel
    HSSFSheet sheet = workbook.createSheet();// ExcelSheet
    sheet.createFreezePane(1, 2);// 
    // // ww w. j  av  a2  s  . c  o m
    sheet.setColumnWidth(0, 1000);
    sheet.setColumnWidth(1, 3500);
    sheet.setColumnWidth(2, 3500);
    sheet.setColumnWidth(3, 6500);
    sheet.setColumnWidth(4, 6500);
    sheet.setColumnWidth(5, 6500);
    sheet.setColumnWidth(6, 6500);
    sheet.setColumnWidth(7, 2500);
    // Sheet?
    //        HSSFCellStyle sheetStyle = workbook.createCellStyle();
    // 
    //        sheetStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
    // ?
    //        sheetStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    // ?
    //        sheetStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);
    // ?
    //        for (int i = 0; i <= 14; i++) {
    //            sheet.setDefaultColumnStyle((short) i, sheetStyle);
    //        }
    // 
    HSSFFont headfont = workbook.createFont();
    headfont.setFontName("");
    headfont.setFontHeightInPoints((short) 22);// ?
    headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 
    // ??
    HSSFCellStyle headstyle = workbook.createCellStyle();
    headstyle.setFont(headfont);
    headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// ?
    headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 
    headstyle.setLocked(true);
    headstyle.setWrapText(true);// ?
    // ??
    HSSFFont columnHeadFont = workbook.createFont();
    columnHeadFont.setFontName("");
    columnHeadFont.setFontHeightInPoints((short) 10);
    columnHeadFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    // ?
    HSSFCellStyle columnHeadStyle = workbook.createCellStyle();
    columnHeadStyle.setFont(columnHeadFont);
    columnHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// ?
    columnHeadStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 
    columnHeadStyle.setLocked(true);
    columnHeadStyle.setWrapText(true);
    columnHeadStyle.setLeftBorderColor(HSSFColor.BLACK.index);// 
    columnHeadStyle.setBorderLeft((short) 1);// ?
    columnHeadStyle.setRightBorderColor(HSSFColor.BLACK.index);// ?
    columnHeadStyle.setBorderRight((short) 1);// ?
    columnHeadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // ?
    columnHeadStyle.setBottomBorderColor(HSSFColor.BLACK.index); // ?
    // ????
    columnHeadStyle.setFillForegroundColor(HSSFColor.WHITE.index);

    HSSFFont font = workbook.createFont();
    font.setFontName("");
    font.setFontHeightInPoints((short) 10);
    // ??
    HSSFCellStyle style = workbook.createCellStyle();
    style.setFont(font);
    style.setAlignment(HSSFCellStyle.ALIGN_LEFT);// ?
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 
    style.setWrapText(true);
    style.setLeftBorderColor(HSSFColor.BLACK.index);
    style.setBorderLeft((short) 1);
    style.setRightBorderColor(HSSFColor.BLACK.index);
    style.setBorderRight((short) 1);
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // ?
    style.setBottomBorderColor(HSSFColor.BLACK.index); // ?
    style.setFillForegroundColor(HSSFColor.WHITE.index);// ?
    // ??
    HSSFCellStyle centerstyle = workbook.createCellStyle();
    centerstyle.setFont(font);
    centerstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// ?
    centerstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 
    centerstyle.setWrapText(true);
    centerstyle.setLeftBorderColor(HSSFColor.BLACK.index);
    centerstyle.setBorderLeft((short) 1);
    centerstyle.setRightBorderColor(HSSFColor.BLACK.index);
    centerstyle.setBorderRight((short) 1);
    centerstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // ?
    centerstyle.setBottomBorderColor(HSSFColor.BLACK.index); // ?
    centerstyle.setFillForegroundColor(HSSFColor.WHITE.index);// ?
    try {
        // 
        HSSFRow row0 = sheet.createRow(0);
        // 
        row0.setHeight((short) 900);
        // 
        HSSFCell cell0 = row0.createCell(0);
        cell0.setCellValue(new HSSFRichTextString("???"));
        cell0.setCellStyle(headstyle);
        /**
         * ?? ??0 ??0 ??0 ??0
         */
        CellRangeAddress range = new CellRangeAddress(0, 0, 0, 14);
        sheet.addMergedRegion(range);
        // 
        HSSFRow row1 = sheet.createRow(1);
        row1.setHeight((short) 750);
        HSSFCell cell = row1.createCell(0);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(1);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(2);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(3);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(4);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(5);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(6);
        cell.setCellValue(new HSSFRichTextString("?"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(7);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(8);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(9);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(10);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(11);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(12);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(13);
        cell.setCellValue(new HSSFRichTextString("?"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(14);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        List<ContestEntry> projectList = contestEntryDAO.findAll();
        int m = 2;
        int len = projectList.size();
        for (int i = 0; i < len; i++) {
            ContestEntry c = projectList.get(i);
            HSSFRow row = sheet.createRow(m + i);
            cell = row.createCell(0);
            cell.setCellValue(new HSSFRichTextString(c.getId() + ""));
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue(new HSSFRichTextString(c.getLocation()));
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue(new HSSFRichTextString(c.getInstance()));
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue(new HSSFRichTextString(c.getIndustry()));
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue(new HSSFRichTextString(c.getLegalFormation()));
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue(new HSSFRichTextString(c.getRegtime()));
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue(new HSSFRichTextString(c.getEmployqty() + ""));
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue(new HSSFRichTextString(c.getLegalPerson()));
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue(new HSSFRichTextString(c.getUserCategory()));
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue(new HSSFRichTextString(c.getContact()));
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue(new HSSFRichTextString(c.getIdNumber()));
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue(new HSSFRichTextString(c.getBankName()));
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue(new HSSFRichTextString(c.getBankUserName()));
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue(new HSSFRichTextString(c.getBankAccount()));
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue(new HSSFRichTextString(c.getSupportMoney()));
            cell.setCellStyle(style);
        }
        String filename = System.nanoTime() + ".xls";// Excel??
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        OutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    } catch (Exception e) {
        log.error("download excel Error.", e);
    }
    return null;
}

From source file:com.joeyturczak.jtscanner.utils.CreateExcelSpreadsheet.java

License:Apache License

public CreateExcelSpreadsheet(List<List> rowLists) {

    mDate = Utility.getTodayDateString();
    mFileName = Utility.getTodayDateAndTimeString();

    mWorkbook = new HSSFWorkbook();
    mSheet = mWorkbook.createSheet(mDate);
    HSSFCellStyle dateRowStyle = mWorkbook.createCellStyle();
    HSSFCellStyle headerRowStyle = mWorkbook.createCellStyle();
    HSSFCellStyle defaultStyle = mWorkbook.createCellStyle();
    HSSFCellStyle defaultAltStyle = mWorkbook.createCellStyle();
    HSSFFont headerFont = mWorkbook.createFont();
    HSSFFont defaultFont = mWorkbook.createFont();

    headerFont.setFontName("Arial");
    headerFont.setFontHeightInPoints((short) 14);
    headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

    defaultFont.setFontName("Arial");
    defaultFont.setFontHeightInPoints((short) 14);

    dateRowStyle.setFont(headerFont);/*  ww w. j av a 2s  .  co  m*/
    headerRowStyle.setFont(headerFont);
    defaultStyle.setFont(defaultFont);
    defaultAltStyle.setFont(defaultFont);

    dateRowStyle.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
    dateRowStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    dateRowStyle.setAlignment(CellStyle.ALIGN_CENTER);

    headerRowStyle.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
    headerRowStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    headerRowStyle.setBorderLeft(HSSFBorderFormatting.BORDER_THIN);
    headerRowStyle.setBorderRight(HSSFBorderFormatting.BORDER_THIN);
    headerRowStyle.setBorderBottom(HSSFBorderFormatting.BORDER_THIN);
    headerRowStyle.setBorderTop(HSSFBorderFormatting.BORDER_THIN);
    headerRowStyle.setAlignment(CellStyle.ALIGN_CENTER);

    defaultStyle.setBorderLeft(HSSFBorderFormatting.BORDER_THIN);
    defaultStyle.setBorderRight(HSSFBorderFormatting.BORDER_THIN);
    defaultStyle.setBorderBottom(HSSFBorderFormatting.BORDER_THIN);
    defaultStyle.setBorderTop(HSSFBorderFormatting.BORDER_THIN);
    defaultStyle.setAlignment(CellStyle.ALIGN_CENTER);

    defaultAltStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    defaultAltStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    defaultAltStyle.setBorderLeft(HSSFBorderFormatting.BORDER_THIN);
    defaultAltStyle.setBorderRight(HSSFBorderFormatting.BORDER_THIN);
    defaultAltStyle.setBorderBottom(HSSFBorderFormatting.BORDER_THIN);
    defaultAltStyle.setBorderTop(HSSFBorderFormatting.BORDER_THIN);
    defaultAltStyle.setAlignment(CellStyle.ALIGN_CENTER);

    try {
        Row dateRow = mSheet.createRow(0);
        dateRow.setHeight((short) 500);
        Cell dateCell = dateRow.createCell(0);
        dateCell.setCellValue(mDate);
        dateCell.setCellStyle(dateRowStyle);
        mSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));

        for (int colIndex = 0; colIndex < rowLists.size(); colIndex++) {
            Row row = mSheet.createRow(mRowNum);
            mSheet.setColumnWidth(0, 1200);

            List<String> nextRowList = rowLists.get(colIndex);

            for (int rowIndex = 0; rowIndex < nextRowList.size(); rowIndex++) {
                Cell cell = row.createCell(rowIndex);
                cell.setCellValue(nextRowList.get(rowIndex));
                row.setHeight((short) 400);
                cell.setCellStyle(defaultStyle);
                if (colIndex % 2 == 0) {
                    cell.setCellStyle(defaultAltStyle);
                }
                if (colIndex == 0) {
                    row.setHeight((short) 500);
                    cell.setCellStyle(headerRowStyle);
                }
                if (rowIndex > 0) {
                    mSheet.setColumnWidth(rowIndex, 4400);
                }
            }

            mRowNum++;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.mss.mirage.employee.general.EmployeeServiceImpl.java

License:Open Source License

public String generateEmployeeList(String loginId) {
    DateUtility dateutility = new DateUtility();
    String filePath = "";
    StringBuffer sb = null;// w  w  w .ja v  a  2s . co m
    Connection connection = null;

    /** callableStatement is a reference variable for CallableStatement . */
    CallableStatement callableStatement = null;

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

    /** The queryString is useful to get  queryString result to the particular jsp page */
    String queryString = "";
    Statement statement = null;

    /** The statement is useful  to execute the above queryString */
    ResultSet resultSet = null;
    String timeSheetStatus = "";
    HashMap map = null;
    HashMap map1 = null;
    List finalList = new ArrayList();
    try {

        String TABLE_EMP_STATE_HISTORY = Properties.getProperty("TABLE_EMP_STATE_HISTORY");

        File file = new File(Properties.getProperty("Emp.StateHistory.Path"));

        if (!file.exists()) {
            file.mkdirs();
        }

        FileOutputStream fileOut = new FileOutputStream(
                file.getAbsolutePath() + File.separator + loginId + "_StateHistory.xls");

        connection = ConnectionProvider.getInstance().getConnection();
        String query = null;

        // query = "SELECT * FROM tblEmpStateHistory WHERE LoginId='"+loginId+"' ORDER BY StartDate DESC";
        query = "SELECT * FROM " + TABLE_EMP_STATE_HISTORY + " WHERE LoginId='" + loginId
                + "' ORDER BY StartDate DESC";

        //  System.out.println("query123-->"+query);
        String reportToName = "";
        List teamList = null;

        int j = 1;
        preStmt = connection.prepareStatement(query);

        resultSet = preStmt.executeQuery();

        while (resultSet.next()) {
            String state = "";
            if (!"".equals(resultSet.getString("State")) && resultSet.getString("State") != null) {
                state = resultSet.getString("State");
            }

            double IntRatePerHour = resultSet.getFloat("IntRatePerHour");

            double InvRatePerHour = resultSet.getFloat("InvRatePerHour");

            String LoginId = resultSet.getString("LoginId");

            String SkillSet = "";
            if (!"".equals(resultSet.getString("SkillSet")) && resultSet.getString("SkillSet") != null) {
                SkillSet = resultSet.getString("SkillSet");
            }

            String EndDate = "";
            if (!"".equals(resultSet.getString("EndDate")) && resultSet.getString("EndDate") != null) {
                EndDate = resultSet.getString("EndDate");
            }

            String StartDate = "";
            if (!"".equals(resultSet.getString("StartDate")) && resultSet.getString("StartDate") != null) {
                StartDate = resultSet.getString("StartDate");
            }

            String CreatedDate = "";
            if (!"".equals(resultSet.getString("CreatedDate")) && resultSet.getString("CreatedDate") != null) {
                CreatedDate = resultSet.getString("CreatedDate");
            }

            String PrjName = "";

            if (!"".equals(resultSet.getString("PrjName")) && resultSet.getString("PrjName") != null) {
                PrjName = resultSet.getString("PrjName");
            }

            String reportsTo = "";

            map = new HashMap();
            map.put("SNO", String.valueOf(j));
            map.put("state", state);
            map.put("IntRatePerHour", IntRatePerHour);
            map.put("InvRatePerHour", InvRatePerHour);
            map.put("LoginId", LoginId);
            map.put("SkillSet", SkillSet);
            map.put("EndDate", EndDate);
            map.put("StartDate", StartDate);
            map.put("CreatedDate", CreatedDate);
            map.put("PrjName", PrjName);
            //System.out.println("map=="+map);

            finalList.add(map);
            j++;

        }

        if (finalList.size() > 0) {
            filePath = file.getAbsolutePath() + File.separator + loginId + "_StateHistory.xls";
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            HSSFSheet sheet = hssfworkbook.createSheet("State History");

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

            HSSFFont timesBoldFont = hssfworkbook.createFont();
            timesBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            timesBoldFont.setColor(HSSFColor.WHITE.index);
            timesBoldFont.setFontName("Arial");
            headercs.setFont(timesBoldFont);

            HSSFFont footerFont = hssfworkbook.createFont();
            footerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            footerFont.setFontName("Arial");

            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);
            HSSFCell cell8 = row.createCell((short) 8);
            cell.setCellValue("SNO");
            cell1.setCellValue("State");
            cell2.setCellValue("StartDate");
            cell3.setCellValue("EndDate");
            cell4.setCellValue("IntRatePerHour");
            cell5.setCellValue("InvRatePerHour");
            cell6.setCellValue("SkillSet");
            cell7.setCellValue("ProjectName");
            cell8.setCellValue("CreatedDate");

            cell.setCellStyle(headercs);
            cell1.setCellStyle(headercs);
            cell2.setCellStyle(headercs);
            cell3.setCellStyle(headercs);
            cell4.setCellStyle(headercs);
            cell5.setCellStyle(headercs);
            cell6.setCellStyle(headercs);
            cell7.setCellStyle(headercs);
            cell8.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);
                    cell8 = row.createCell((short) 8);

                    cell.setCellValue((String) stateHistorylMap.get("SNO"));
                    cell1.setCellValue((String) stateHistorylMap.get("state"));
                    cell2.setCellValue((String) stateHistorylMap.get("StartDate"));
                    cell3.setCellValue((String) stateHistorylMap.get("EndDate"));
                    cell4.setCellValue((Double) stateHistorylMap.get("IntRatePerHour"));
                    cell5.setCellValue((Double) stateHistorylMap.get("InvRatePerHour"));
                    cell6.setCellValue((String) stateHistorylMap.get("SkillSet"));
                    cell7.setCellValue((String) stateHistorylMap.get("PrjName"));
                    cell8.setCellValue((String) stateHistorylMap.get("CreatedDate"));

                    cell.setCellStyle(cs);
                    cell1.setCellStyle(cs);
                    cell2.setCellStyle(cs);
                    cell3.setCellStyle(cs);
                    cell4.setCellStyle(cs);
                    cell5.setCellStyle(cs);
                    cell6.setCellStyle(cs);
                    cell7.setCellStyle(cs);
                    cell8.setCellStyle(cs);
                }
                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);
                cell.setCellValue("");

                cell4.setCellValue("");

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

                cell4.setCellStyle(footercs);
            }
            sheet.autoSizeColumn((int) 0);
            sheet.autoSizeColumn((int) 1);
            sheet.autoSizeColumn((int) 2);
            sheet.autoSizeColumn((int) 3);
            sheet.autoSizeColumn((int) 4);

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

        }

    } catch (FileNotFoundException fne) {

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

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

    } finally {
        System.out.println("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.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  .j  av a2  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.mss.mirage.marketing.MarketingServiceImpl.java

License:Open Source License

public String getCampaignContactsExcel(HttpServletRequest httpServletRequest, MarketingAction marketingAction)
        throws ServiceLocatorException {

    // System.out.println("getCampaignContactsExcel");
    String filePath = "";
    StringBuffer sb = null;//from  w  w  w.j a  v  a 2s.  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
     */
    String queryString = "";
    /**
     * The statement is useful to execute the above queryString
     */
    ResultSet resultSet = null;
    HashMap map = null;

    List finalList = new ArrayList();
    String campaignTitle = "";
    try {
        PreparedStatement preparedStatement = null;
        Statement statement = null;
        ResultSet resultSet1 = null;
        String email = "";
        String phone = "";
        String CompanyName = "";
        String contactName = "";
        int z = 0;
        int n = 1;
        Map<Integer, String> contactIdMap = new TreeMap<Integer, String>();
        // queryString = "SELECT Id,ContactId FROM tblCrmActivity WHERE CampaignId=" + campaignId + " ORDER BY CreatedDate DESC";
        String loginId = httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_USER_ID)
                .toString();
        String roleName = httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_ROLE_NAME).toString();
        campaignTitle = DataSourceDataProvider.getInstance()
                .getCampaignNameByCampaignId(marketingAction.getCampaignId());
        // queryString = "SELECT Id,Title,CreatedBy,CurrStatus FROM tblCrmLeads WHERE AccountId=" + accId;
        // queryString = "SELECT Id,ContactId FROM tblCrmActivity WHERE CampaignId="+campaignId+" ORDER BY CreatedDate DESC";
        queryString = "SELECT Id,ContactId FROM tblCrmActivity WHERE CampaignId="
                + marketingAction.getCampaignId();

        if (marketingAction.getContactStartDate() != null
                && !"".equalsIgnoreCase(marketingAction.getContactStartDate())) {
            queryString = queryString + " AND (DATE(CreatedDate))>='"
                    + DateUtility.getInstance().getMysqlDate(marketingAction.getContactStartDate()) + "' ";
        }
        if (marketingAction.getContactEndDate() != null
                && !"".equalsIgnoreCase(marketingAction.getContactEndDate())) {
            queryString = queryString + " AND (DATE(CreatedDate))<='"
                    + DateUtility.getInstance().getMysqlDate(marketingAction.getContactEndDate()) + "' ";
        }
        if (roleName.equals("Sales")) {
            queryString = queryString + " AND CreatedById='" + loginId + "' ";
        }
        queryString = queryString + " ORDER BY CreatedDate DESC";

        // String contactQuery = "SELECT Id, CONCAT(FirstName,' ',MiddleName,'.',LastName) AS ContactName,Email1,CellPhone FROM tblCrmContact WHERE Id=?";
        String contactQuery = "SELECT tblCrmContact.id AS contactId,tblCrmAccount.Id AS accountId,"
                + "CONCAT(tblCrmContact.FirstName,'.',tblCrmContact.LastName) AS ContactName,"
                + " tblCrmContact.Email1 AS Email1, tblCrmAccount.NAME AS CompanyName,tblCrmContact.CellPhone AS CellPhone"
                + "  FROM tblCrmContact LEFT JOIN  tblCrmAccount ON(tblCrmContact.AccountId=tblCrmAccount.Id) WHERE tblCrmContact.id=?";
        connection = ConnectionProvider.getInstance().getConnection();
        statement = connection.createStatement();
        resultSet = statement.executeQuery(queryString);
        while (resultSet.next()) {
            z++;
            int Id = resultSet.getInt("Id");
            String ContactId = resultSet.getString("ContactId");
            contactIdMap.put(Id, ContactId);
            //totalStream=totalStream+i+"|"+createdDate+"|"+actType+"|"+description+"|"+comments+"|"+assignedToId+"|"+contactName+"|"+datedue+"|"+actid+"|"+"^";
            //  totalActivities=totalActivities+count;
        }
        preparedStatement = connection.prepareStatement(contactQuery);

        for (Map.Entry<Integer, String> entry : contactIdMap.entrySet()) {
            Integer key = entry.getKey();
            String value = entry.getValue();
            String[] parts = value.split("\\,");
            if (parts.length > 0 && !"".equals(value)) {
                for (int j = 0; j < parts.length; j++) {
                    preparedStatement.setInt(1, Integer.parseInt(parts[j]));
                    resultSet1 = preparedStatement.executeQuery();

                    while (resultSet1.next()) {
                        CompanyName = resultSet1.getString("CompanyName");
                        contactName = resultSet1.getString("ContactName");
                        email = resultSet1.getString("Email1");
                        phone = resultSet1.getString("CellPhone");
                        map = new HashMap();
                        map.put("SNO", String.valueOf(n));
                        map.put("contactName", contactName);
                        map.put("CompanyName", CompanyName);
                        map.put("email", email);
                        // map.put("phone", phone);
                        // System.out.println(map);
                        finalList.add(map);
                        n++;
                    }

                }
            }

        }
        //  System.out.println("map" + finalList.size());
        File file = new File(Properties.getProperty("Emp.Qmeet.Path"));

        if (!file.exists()) {
            file.mkdirs();
        }

        FileOutputStream fileOut = new FileOutputStream(
                file.getAbsolutePath() + File.separator + "Contacts.xls");
        filePath = file.getAbsolutePath() + File.separator + "Contacts.xls";
        HSSFRow row1;
        HSSFWorkbook workbook = new HSSFWorkbook();
        System.out.println("filePath " + filePath);
        HSSFSheet worksheet = workbook.createSheet("Campaign Contacts");
        for (int i = 0; i < 4; i++) {
            worksheet.setColumnWidth(i, 10 * 256);

        }

        HSSFFont timesBoldFont = workbook.createFont();
        timesBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        timesBoldFont.setColor(HSSFColor.WHITE.index);

        timesBoldFont.setFontName("Calibri");
        HSSFCellStyle headercs = workbook.createCellStyle();
        headercs.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
        headercs.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        headercs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headercs.setBorderTop((short) 1); // single line border
        headercs.setBorderBottom((short) 1); // single line border
        headercs.setFont(timesBoldFont);

        HSSFFont footerFont = workbook.createFont();
        footerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        footerFont.setFontName("Calibri");

        // HSSFRow row1;
        // LogisticsDocBean logisticsDocBean = null;
        // index from 0,0... cell A1 is cell(0,0)

        // if(list.size()!=0){//
        //System.out.println("list size-->"+list.size());

        HSSFFont font4 = workbook.createFont();
        font4.setColor(HSSFColor.WHITE.index);
        font4.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font4.setFontHeightInPoints((short) 14);
        font4.setFontName("Calibri");

        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setFont(font4);

        HSSFFont font1 = workbook.createFont();
        //font1.setColor(HSSFColor.WHITE.index);
        font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font1.setFontHeightInPoints((short) 14);
        font1.setFontName("Calibri");
        HSSFCellStyle cs = workbook.createCellStyle();
        cs.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        cs.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cs.setBorderTop((short) 1); // single line border
        cs.setBorderBottom((short) 1); // single line border
        cs.setFont(font1);

        HSSFCellStyle cs1 = workbook.createCellStyle();
        cs1.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index);
        cs1.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        cs1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cs1.setFont(font4);
        cs1.setBorderTop((short) 1); // single line border
        cs1.setBorderBottom((short) 1); // single line border

        HSSFCellStyle cs2 = workbook.createCellStyle();

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

        HSSFFont font3 = workbook.createFont();
        //font1.setColor(HSSFColor.WHITE.index);
        //  font3.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font3.setFontHeightInPoints((short) 14);
        font3.setFontName("Calibri");

        HSSFCellStyle cs3 = workbook.createCellStyle();
        cs3.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        cs3.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        cs3.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cs3.setFont(font3);
        cs3.setBorderTop((short) 1); // single line border
        cs3.setBorderBottom((short) 1); // single line border

        HSSFCellStyle cs4 = workbook.createCellStyle();

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

        //start   

        row1 = worksheet.createRow((short) 0);

        HSSFCell cellpo0 = row1.createCell((short) 0);
        // cellpo0.setCellValue("Purchase Order");
        HSSFCell cellpo1 = row1.createCell((short) 1);
        HSSFCell cellpo2 = row1.createCell((short) 2);
        // cellpo2.setCellValue("Created Date");
        HSSFCell cellpo3 = row1.createCell((short) 3);
        //cellpo3.setCellValue((date.getYear()+1900)+"-"+(date.getMonth()+1)+"-"+date.getDate());

        HSSFCell cellpo4 = row1.createCell((short) 4);
        HSSFCell cellpo5 = row1.createCell((short) 5);
        HSSFCell cellpo6 = row1.createCell((short) 6);
        HSSFCell cellpo7 = row1.createCell((short) 7);
        HSSFCell cellpo8 = row1.createCell((short) 8);
        HSSFCell cellpo9 = row1.createCell((short) 9);
        HSSFCell cellpo10 = row1.createCell((short) 10);
        HSSFCell cellpo11 = row1.createCell((short) 11);
        row1 = worksheet.createRow((short) 0);
        Cell cell[] = new Cell[4];
        for (int i = 0; i < 4; i++) {
            cell[i] = row1.createCell((short) i);
        }

        // cell.setCellValue("Logistics Document :-Created Date : "+(date.getYear()+1900)+"-"+(date.getMonth()+1)+"-"+date.getDate());
        cell[0].setCellValue("Contacts Details :" + campaignTitle);
        HSSFCellStyle cellStyleHead = workbook.createCellStyle();
        cellStyleHead.setFont(timesBoldFont);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setFillBackgroundColor(HSSFColor.PALE_BLUE.index);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cell[0].setCellStyle(cellStyle);

        worksheet.addMergedRegion(CellRangeAddress.valueOf("A1:" + "D2"));

        //sno
        row1 = worksheet.createRow((short) 2);
        cell[0] = row1.createCell((short) 0);
        cell[0].setCellValue("SNo");
        // cellStyleHead.setFont(font4);
        cellStyleHead.setFont(timesBoldFont);
        //  cellStyleHead.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //cellStyleHead.setFillBackgroundColor(HSSFColor.PALE_BLUE.index);
        // cellStyleHead.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyleHead.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // cell[0].setCellStyle(cellStyleHead);
        cell[0].setCellStyle(cs1);

        worksheet.addMergedRegion(CellRangeAddress.valueOf("A3:A4"));

        cell[0] = row1.createCell((short) 1);
        cell[0].setCellValue("Contact Name");
        cellStyleHead.setFont(timesBoldFont);
        cellStyleHead.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        //cell[0].setCellStyle(cellStyleHead);
        cell[0].setCellStyle(cs1);
        worksheet.addMergedRegion(CellRangeAddress.valueOf("B3:B4"));

        cell[0] = row1.createCell((short) 2);
        cell[0].setCellValue("Company Name");
        cellStyleHead.setFont(timesBoldFont);
        cellStyleHead.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        //cell[0].setCellStyle(cellStyleHead);
        cell[0].setCellStyle(cs1);
        worksheet.addMergedRegion(CellRangeAddress.valueOf("C3:C4"));

        cell[0] = row1.createCell((short) 3);
        cell[0].setCellValue("E-Mail");
        cellStyleHead.setFont(timesBoldFont);
        cellStyleHead.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // cell[0].setCellStyle(cellStyleHead);
        cell[0].setCellStyle(cs1);
        worksheet.addMergedRegion(CellRangeAddress.valueOf("D3:D4"));

        //            cell[0] = row1.createCell((short) 4);
        //            cell[0].setCellValue("Phone");
        //            cellStyleHead.setFont(timesBoldFont);
        //            cellStyleHead.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        //            //  cell[0].setCellStyle(cellStyleHead);
        //            cell[0].setCellStyle(cs1);
        //            worksheet.addMergedRegion(CellRangeAddress.valueOf("E3:E4"));

        int count = 4;

        int len = finalList.size();
        if (finalList.size() > 0) {

            for (int k = 0; k < finalList.size(); k++) {

                java.util.Map subList = (java.util.Map) finalList.get(k);
                row1 = worksheet.createRow((short) count++);
                for (int j = 0; j < 4; j++) {
                    cell[j] = row1.createCell((short) j);
                }
                //System.out.println("subList-->"+subList);
                cell[0].setCellValue((String) subList.get("SNO"));
                cell[1].setCellValue((String) subList.get("contactName"));
                cell[2].setCellValue((String) subList.get("CompanyName"));
                cell[3].setCellValue((String) subList.get("email").toString());
                // cell[4].setCellValue((String) subList.get("phone").toString());

                for (int h = 0; h < 4; h++) {
                    if (count % 2 == 0) {
                        cell[h].setCellStyle(cs1);
                    } else {
                        cell[h].setCellStyle(cs);
                    }

                }
            }
            // 
            for (int i = 1; i < 4; i++) {

                worksheet.setColumnWidth(i, 40 * 256);

                //
            }
            workbook.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.netxforge.netxstudio.models.export.MasterDataExporterRevenge.java

License:Open Source License

private void _generateID(Sheet sheet) {
    // Generate name.
    {//  w w w .jav  a  2  s.c om
        // Style, cell color.
        CellStyle attributeStyle = workBook.createCellStyle();
        attributeStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        attributeStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

        // Style, font
        HSSFFont attributeFont = workBook.createFont();
        attributeFont.setFontName("Verdana");
        attributeFont.setColor(HSSFColor.BLUE.index);
        attributeStyle.setFont(attributeFont);

        // Style, border.
        attributeStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);

        Row row = sheet.getRow(0);
        if (row == null) {
            row = sheet.createRow(0);
        }
        short lastCellNum = row.getLastCellNum();
        if (lastCellNum == -1) {
            lastCellNum = 0;
        }
        Cell cell = row.createCell(lastCellNum);
        cell.setCellValue("ID");
        cell.setCellStyle(attributeStyle);
    }
    // Generate type
    {

        CellStyle typeStyle = workBook.createCellStyle();
        typeStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);

        Row row = sheet.getRow(1);
        if (row == null) {
            row = sheet.createRow(1);
        }
        short lastCellNum = row.getLastCellNum();
        if (lastCellNum == -1) {
            lastCellNum = 0;
        }
        Cell cell = row.createCell(lastCellNum);
        cell.setCellStyle(typeStyle);
    }
}

From source file:com.netxforge.netxstudio.models.export.MasterDataExporterRevenge.java

License:Open Source License

private void _generateCell(EAttribute eAttribute, Sheet sheet) {

    // Generate name.
    {// ww  w. j ava2  s.co m
        // Style, cell color.
        CellStyle attributeStyle = workBook.createCellStyle();
        attributeStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        attributeStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

        // Style, font
        HSSFFont attributeFont = workBook.createFont();
        attributeFont.setFontName("Verdana");
        attributeFont.setColor(HSSFColor.BLUE.index);
        attributeStyle.setFont(attributeFont);

        // Style, border.
        attributeStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);

        Row row = sheet.getRow(0);
        if (row == null) {
            row = sheet.createRow(0);
        }
        short lastCellNum = row.getLastCellNum();
        if (lastCellNum == -1) {
            lastCellNum = 0;
        }
        Cell cell = row.createCell(lastCellNum);
        cell.setCellValue(StringUtils.capitalize(eAttribute.getName()));
        cell.setCellStyle(attributeStyle);
    }
    // Generate type
    {

        CellStyle typeStyle = workBook.createCellStyle();
        typeStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);

        Row row = sheet.getRow(1);
        if (row == null) {
            row = sheet.createRow(1);
        }
        short lastCellNum = row.getLastCellNum();
        if (lastCellNum == -1) {
            lastCellNum = 0;
        }
        Cell cell = row.createCell(lastCellNum);
        cell.setCellValue(eAttribute.getEType().getName());
        cell.setCellStyle(typeStyle);
    }
}

From source file:com.netxforge.netxstudio.models.export.MasterDataExporterRevenge.java

License:Open Source License

private void _generateCell(EReference eReference, Sheet sheet) {

    // Generate name.
    {/*from  w ww .  ja  v  a 2s. c  o m*/
        // Style, cell color.
        CellStyle referenceStyle = workBook.createCellStyle();
        referenceStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        referenceStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

        // Style, font
        HSSFFont referenceFont = workBook.createFont();
        referenceFont.setFontName("Verdana");
        referenceFont.setColor(HSSFColor.DARK_RED.index);
        referenceStyle.setFont(referenceFont);

        // Style, border.
        referenceStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);

        Row row = sheet.getRow(0);
        if (row == null) {
            row = sheet.createRow(0);
        }
        short lastCellNum = row.getLastCellNum();
        if (lastCellNum == -1) {
            lastCellNum = 0;
        }
        Cell cell = row.createCell(lastCellNum);
        cell.setCellValue(StringUtils.capitalize(eReference.getName()));
        cell.setCellStyle(referenceStyle);
    }
    // Generate type
    {

        CellStyle typeStyle = workBook.createCellStyle();
        typeStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);

        Row row = sheet.getRow(1);
        if (row == null) {
            row = sheet.createRow(1);
        }
        short lastCellNum = row.getLastCellNum();
        if (lastCellNum == -1) {
            lastCellNum = 0;
        }
        Cell cell = row.createCell(lastCellNum);
        cell.setCellValue(eReference.getEType().getName());
        cell.setCellStyle(typeStyle);
    }
}