Example usage for org.apache.poi.ss.util CellRangeAddress valueOf

List of usage examples for org.apache.poi.ss.util CellRangeAddress valueOf

Introduction

In this page you can find the example usage for org.apache.poi.ss.util CellRangeAddress valueOf.

Prototype

public static CellRangeAddress valueOf(String ref) 

Source Link

Document

Creates a CellRangeAddress from a cell range reference string.

Usage

From source file:com.miraisolutions.xlconnect.Workbook.java

License:Open Source License

public void mergeCells(String sheetName, String reference) {
    getSheet(sheetName).addMergedRegion(CellRangeAddress.valueOf(reference));
}

From source file:com.miraisolutions.xlconnect.Workbook.java

License:Open Source License

public void setAutoFilter(int sheetIndex, String reference) {
    getSheet(sheetIndex).setAutoFilter(CellRangeAddress.valueOf(reference));
}

From source file:com.miraisolutions.xlconnect.Workbook.java

License:Open Source License

public void setAutoFilter(String sheetName, String reference) {
    getSheet(sheetName).setAutoFilter(CellRangeAddress.valueOf(reference));
}

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;/*w w  w .j  a  v  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
     */
    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.mycompany.excelreadandwrite.WritetoExcel.java

public void writeSongsListToExcel(List<Song> songList) {

    /*/* w  w w  .  j  a v  a 2 s.c o m*/
    Use XSSF for xlsx format and for xls use HSSF
    */
    Workbook workbook = new XSSFWorkbook();

    /*
    create new sheet 
    */
    Sheet songsSheet = workbook.createSheet("Albums");

    XSSFCellStyle my_style = (XSSFCellStyle) workbook.createCellStyle();
    /* Create XSSFFont object from the workbook */
    XSSFFont my_font = (XSSFFont) workbook.createFont();

    /*
    setting cell color
    */
    CellStyle style = workbook.createCellStyle();
    style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);

    /*
     setting Header color
    */
    CellStyle style2 = workbook.createCellStyle();
    style2.setFillForegroundColor(IndexedColors.DARK_RED.getIndex());
    style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

    Row rowName = songsSheet.createRow(1);

    /*
    Merging the cells
    */
    songsSheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));

    /*
    Applying style to attribute name
    */
    int nameCellIndex = 1;
    Cell namecell = rowName.createCell(nameCellIndex++);
    namecell.setCellValue("Name");
    namecell.setCellStyle(style);

    Cell cel = rowName.createCell(nameCellIndex++);
    cel.setCellValue("Lastname, Firstname");

    /*
    Applying underline to Name
    */
    my_font.setUnderline(XSSFFont.U_SINGLE);
    my_style.setFont(my_font);
    /* Attaching the style to the cell */
    CellStyle combined = workbook.createCellStyle();
    combined.cloneStyleFrom(my_style);
    combined.cloneStyleFrom(style);
    cel.setCellStyle(combined);

    /*
    Applying  colors to header 
    */

    Row rowMain = songsSheet.createRow(3);
    SheetConditionalFormatting sheetCF = songsSheet.getSheetConditionalFormatting();
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("3");
    PatternFormatting fill1 = rule1.createPatternFormatting();
    fill1.setFillBackgroundColor(IndexedColors.CORNFLOWER_BLUE.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A4:G4") };

    sheetCF.addConditionalFormatting(regions, rule1);

    /*
    setting new rule to apply alternate colors to cells having same Genre
    */
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill2 = rule2.createPatternFormatting();
    fill2.setFillBackgroundColor(IndexedColors.LEMON_CHIFFON.index);
    fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAction = { CellRangeAddress.valueOf("A5:G5"), CellRangeAddress.valueOf("A6:G6"),
            CellRangeAddress.valueOf("A7:G7"), CellRangeAddress.valueOf("A8:G8"),
            CellRangeAddress.valueOf("A13:G13"), CellRangeAddress.valueOf("A14:G14"),
            CellRangeAddress.valueOf("A15:G15"), CellRangeAddress.valueOf("A16:G16"),
            CellRangeAddress.valueOf("A23:G23"), CellRangeAddress.valueOf("A24:G24"),
            CellRangeAddress.valueOf("A25:G25"), CellRangeAddress.valueOf("A26:G26")

    };

    /*        
    setting new rule to apply alternate colors to cells having same Genre
     */
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill3 = rule3.createPatternFormatting();
    fill3.setFillBackgroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.index);
    fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAdv = { CellRangeAddress.valueOf("A9:G9"), CellRangeAddress.valueOf("A10:G10"),
            CellRangeAddress.valueOf("A11:G11"), CellRangeAddress.valueOf("A12:G12"),
            CellRangeAddress.valueOf("A17:G17"), CellRangeAddress.valueOf("A18:G18"),
            CellRangeAddress.valueOf("A19:G19"), CellRangeAddress.valueOf("A20:G20"),
            CellRangeAddress.valueOf("A21:G21"), CellRangeAddress.valueOf("A22:G22"),
            CellRangeAddress.valueOf("A27:G27"), CellRangeAddress.valueOf("A28:G28"),
            CellRangeAddress.valueOf("A29:G29") };

    /*
    Applying above created rule formatting to cells
    */
    sheetCF.addConditionalFormatting(regionsAction, rule2);
    sheetCF.addConditionalFormatting(regionsAdv, rule3);

    /*
     Setting coloumn header values
    */
    int mainCellIndex = 0;

    rowMain.createCell(mainCellIndex++).setCellValue("SNO");
    rowMain.createCell(mainCellIndex++).setCellValue("Genre");
    rowMain.createCell(mainCellIndex++).setCellValue("Rating");
    rowMain.createCell(mainCellIndex++).setCellValue("Movie Name");
    rowMain.createCell(mainCellIndex++).setCellValue("Director");
    rowMain.createCell(mainCellIndex++).setCellValue("Release Date");
    rowMain.createCell(mainCellIndex++).setCellValue("Budget");

    /*
    populating cell values
    */
    int rowIndex = 4;
    int sno = 1;
    for (Song song : songList) {
        if (song.getSno() != 0) {

            Row row = songsSheet.createRow(rowIndex++);
            int cellIndex = 0;

            /*
            first place in row is Sno
            */
            row.createCell(cellIndex++).setCellValue(sno++);

            /*
            second place in row is  Genre
            */
            row.createCell(cellIndex++).setCellValue(song.getGenre());

            /*
            third place in row is Critic score
            */
            row.createCell(cellIndex++).setCellValue(song.getCriticscore());

            /*
            fourth place in row is Album name
            */
            row.createCell(cellIndex++).setCellValue(song.getAlbumname());

            /*
            fifth place in row is Artist
            */
            row.createCell(cellIndex++).setCellValue(song.getArtist());

            /*
            sixth place in row is marks in date
            */
            if (song.getReleasedate() != null) {

                Cell date = row.createCell(cellIndex++);

                DataFormat format = workbook.createDataFormat();
                CellStyle dateStyle = workbook.createCellStyle();
                dateStyle.setDataFormat(format.getFormat("dd-MMM-yyyy"));
                date.setCellStyle(dateStyle);

                date.setCellValue(song.getReleasedate());

                /*
                auto-resizing columns
                */
                songsSheet.autoSizeColumn(6);
                songsSheet.autoSizeColumn(5);
                songsSheet.autoSizeColumn(4);
                songsSheet.autoSizeColumn(3);
                songsSheet.autoSizeColumn(2);
            }

        }
    }

    /*
    writing this workbook to excel file.
    */
    try {
        FileOutputStream fos = new FileOutputStream(FILE_PATH);
        workbook.write(fos);
        fos.close();

        System.out.println(FILE_PATH + " is successfully written");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.mycompany.gannaraputakehomeexam.WritingToExcel.java

public void writeSongsToExcel(List<SongsList> songList) {

    /*// w w w  .  j a v  a2 s  . com
    Use XSSF for xlsx format and for xls use HSSF
    */
    Workbook workbook = new XSSFWorkbook();

    /*
    create new sheet 
    */
    Sheet songsSheet = workbook.createSheet("Gannarapu_Output");

    XSSFCellStyle my_style = (XSSFCellStyle) workbook.createCellStyle();
    /* Create XSSFFont object from the workbook */
    XSSFFont my_font = (XSSFFont) workbook.createFont();
    XSSFFont font = (XSSFFont) workbook.createFont();

    /*
    setting cell color
    */
    CellStyle style = workbook.createCellStyle();
    style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);

    /*
     setting Header color
    */
    CellStyle style2 = workbook.createCellStyle();
    font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
    style2.setFont(font);
    style2.setAlignment(CellStyle.ALIGN_CENTER);
    //   style2.setFillForegroundColor(IndexedColors.DARK_RED.getIndex());
    //   style2.setFillPattern(CellStyle.SOLID_FOREGROUND);
    //            

    Row rowName = songsSheet.createRow(1);

    /*
    Merging the cells
    */
    songsSheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));

    /*
    Applying style to attribute name
    */
    int nameCellIndex = 1;
    Cell namecell = rowName.createCell(nameCellIndex++);
    namecell.setCellValue("Name");
    namecell.setCellStyle(style);

    Cell cel = rowName.createCell(nameCellIndex++);
    cel.setCellValue("Gannarapu, Anirudh");

    /*
    Applying underline to Name
    */
    my_font.setUnderline(XSSFFont.U_DOUBLE);
    my_style.setFont(my_font);
    /* Attaching the style to the cell */
    CellStyle combined = workbook.createCellStyle();
    combined.cloneStyleFrom(my_style);
    combined.cloneStyleFrom(style);
    cel.setCellStyle(combined);

    /*
    Applying  colors to header 
    */

    Row rowMain = songsSheet.createRow(3);
    SheetConditionalFormatting sheetCF = songsSheet.getSheetConditionalFormatting();
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("5");
    PatternFormatting fill1 = rule1.createPatternFormatting();
    fill1.setFillBackgroundColor(IndexedColors.RED.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A4:F4") };

    sheetCF.addConditionalFormatting(regions, rule1);

    /*
    setting new rule to apply alternate colors to cells having same Genre
    */
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill2 = rule2.createPatternFormatting();
    fill2.setFillBackgroundColor(IndexedColors.LEMON_CHIFFON.index);
    fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAction = { CellRangeAddress.valueOf("A5:F5"), CellRangeAddress.valueOf("A6:F6"),
            CellRangeAddress.valueOf("A7:F7"), CellRangeAddress.valueOf("A8:F8"),
            CellRangeAddress.valueOf("A13:F13"), CellRangeAddress.valueOf("A14:F14"),
            CellRangeAddress.valueOf("A15:F15"), CellRangeAddress.valueOf("A16:F16"),
            CellRangeAddress.valueOf("A23:F23"), CellRangeAddress.valueOf("A24:F24"),
            CellRangeAddress.valueOf("A25:F25"), CellRangeAddress.valueOf("A26:F26")

    };

    /*        
    setting new rule to apply alternate colors to cells having same Genre
     */
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill3 = rule3.createPatternFormatting();
    fill3.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
    fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAdv = { CellRangeAddress.valueOf("A9:F9"), CellRangeAddress.valueOf("A10:F10"),
            CellRangeAddress.valueOf("A11:F11"), CellRangeAddress.valueOf("A12:F12"),
            CellRangeAddress.valueOf("A17:F17"), CellRangeAddress.valueOf("A18:F18"),
            CellRangeAddress.valueOf("A19:F19"), CellRangeAddress.valueOf("A20:F20"),
            CellRangeAddress.valueOf("A21:F21"), CellRangeAddress.valueOf("A22:F22"),
            CellRangeAddress.valueOf("A27:F27"), CellRangeAddress.valueOf("A28:F28"),
            CellRangeAddress.valueOf("A29:F29") };

    /*
    Applying above created rule formatting to cells
    */
    sheetCF.addConditionalFormatting(regionsAction, rule2);
    sheetCF.addConditionalFormatting(regionsAdv, rule3);

    /*
     Setting coloumn header values
    */
    int mainCellIndex = 0;

    Cell SNO = rowMain.createCell(mainCellIndex++);
    SNO.setCellValue("SNO");
    SNO.setCellStyle(style2);
    Cell gen = rowMain.createCell(mainCellIndex++);
    gen.setCellValue("Genre");
    gen.setCellStyle(style2);
    Cell credit = rowMain.createCell(mainCellIndex++);
    credit.setCellValue("Credit Score");
    credit.setCellStyle(style2);
    Cell name = rowMain.createCell(mainCellIndex++);
    name.setCellValue("Album Name");
    name.setCellStyle(style2);
    Cell art = rowMain.createCell(mainCellIndex++);
    art.setCellValue("Artist");
    art.setCellStyle(style2);
    Cell release = rowMain.createCell(mainCellIndex++);
    release.setCellValue("Release Date");
    release.setCellStyle(style2);

    /*
    populating cell values
    */
    int rowIndex = 4;
    int sno = 1;
    for (SongsList song : songList) {
        if (song.getSno() != 0) {

            Row row = songsSheet.createRow(rowIndex++);
            int cellIndex = 0;

            /*
            first place in row is Sno
            */
            row.createCell(cellIndex++).setCellValue(sno++);

            /*
            second place in row is  Genre
            */
            row.createCell(cellIndex++).setCellValue(song.getGenre());

            /*
            third place in row is Critic score
            */
            row.createCell(cellIndex++).setCellValue(song.getCriticscore());

            /*
            fourth place in row is Album name
            */
            row.createCell(cellIndex++).setCellValue(song.getAlbumname());

            /*
            fifth place in row is Artist
            */
            row.createCell(cellIndex++).setCellValue(song.getArtist());

            /*
            sixth place in row is marks in date
            */
            if (song.getReleasedate() != null) {

                Cell date = row.createCell(cellIndex++);

                DataFormat format = workbook.createDataFormat();
                CellStyle dateStyle = workbook.createCellStyle();
                dateStyle.setDataFormat(format.getFormat("dd-MMM-yyyy"));
                date.setCellStyle(dateStyle);

                date.setCellValue(song.getReleasedate());

                /*
                auto-resizing columns
                */
                songsSheet.autoSizeColumn(6);
                songsSheet.autoSizeColumn(5);
                songsSheet.autoSizeColumn(4);
                songsSheet.autoSizeColumn(3);
                songsSheet.autoSizeColumn(2);
            }

        }
    }

    /*
    writing this workbook to excel file.
    */
    try {
        FileOutputStream fos = new FileOutputStream(FILE_PATH);
        workbook.write(fos);
        fos.close();

        System.out.println(FILE_PATH + " is successfully written");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.mycompany.gayamtakehomeexam.WritetoExcel.java

public void writeSongsListToExcel(List<Song> songList) {

    /*//  w  w  w. java 2s  .c  om
    Use XSSF for xlsx format and for xls use HSSF
    */
    Workbook workbook = new XSSFWorkbook();

    /*
    create new sheet
    */
    Sheet songsSheet = workbook.createSheet("Albums");

    XSSFCellStyle my_style = (XSSFCellStyle) workbook.createCellStyle();
    /* Create XSSFFont object from the workbook */
    XSSFFont my_font = (XSSFFont) workbook.createFont();

    /*
    setting cell color
    */
    CellStyle style = workbook.createCellStyle();
    style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);

    CellStyle style1 = workbook.createCellStyle();//Create style
    Font font = workbook.createFont();//Create font
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);//Make font bold
    style1.setFont(font);//set it to bold
    style1.setAlignment(CellStyle.ALIGN_CENTER);

    CellStyle style13 = workbook.createCellStyle();//Create style
    Font font13 = workbook.createFont();//Create font
    style13.setAlignment(CellStyle.ALIGN_LEFT);

    CellStyle style14 = workbook.createCellStyle();//Create style
    Font font14 = workbook.createFont();//Create font
    style14.setAlignment(CellStyle.ALIGN_RIGHT);
    /*
     setting Header color
    */
    CellStyle style2 = workbook.createCellStyle();
    style2.setFillForegroundColor(IndexedColors.LIGHT_ORANGE.getIndex());
    style2.setFillBackgroundColor(IndexedColors.LIGHT_ORANGE.getIndex());
    style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

    Row rowName = songsSheet.createRow(1);

    /*
    Merging the cells
    */
    songsSheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));

    /*
    Applying style to attribute name
    */
    int nameCellIndex = 1;
    Cell namecell = rowName.createCell(nameCellIndex++);
    namecell.setCellValue("Name");
    namecell.setCellStyle(style);

    Cell cel = rowName.createCell(nameCellIndex++);

    /*
    Applying underline to Name
    */
    Font underlineFont = workbook.createFont();
    underlineFont.setUnderline(HSSFFont.U_SINGLE);

    /* Attaching the style to the cell */
    CellStyle combined = workbook.createCellStyle();
    combined.setFont(underlineFont);
    cel.setCellStyle(combined);
    cel.setCellValue("Gayam, Prathibha");

    /*
    Applying  colors to header
    */
    Row rowMain = songsSheet.createRow(3);
    SheetConditionalFormatting sheetCF = songsSheet.getSheetConditionalFormatting();
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("3");
    PatternFormatting fill1 = rule1.createPatternFormatting();
    fill1.setFillBackgroundColor(IndexedColors.LIGHT_ORANGE.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A4:G4") };

    sheetCF.addConditionalFormatting(regions, rule1);

    /*
    setting new rule to apply alternate colors to cells having same Genre
    */
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill2 = rule2.createPatternFormatting();
    fill2.setFillBackgroundColor(IndexedColors.LEMON_CHIFFON.index);
    fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAction = { CellRangeAddress.valueOf("A5:G5"), CellRangeAddress.valueOf("A6:G6"),
            CellRangeAddress.valueOf("A7:G7"), CellRangeAddress.valueOf("A8:G8"),
            CellRangeAddress.valueOf("A13:G13"), CellRangeAddress.valueOf("A14:G14"),
            CellRangeAddress.valueOf("A15:G15"), CellRangeAddress.valueOf("A16:G16"),
            CellRangeAddress.valueOf("A23:G23"), CellRangeAddress.valueOf("A24:G24"),
            CellRangeAddress.valueOf("A25:G25"), CellRangeAddress.valueOf("A26:G26")

    };

    /*        
    setting new rule to apply alternate colors to cells having same Genre
     */
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill3 = rule3.createPatternFormatting();
    fill3.setFillBackgroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.index);
    fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAdv = { CellRangeAddress.valueOf("A9:G9"), CellRangeAddress.valueOf("A10:G10"),
            CellRangeAddress.valueOf("A11:G11"), CellRangeAddress.valueOf("A12:G12"),
            CellRangeAddress.valueOf("A17:G17"), CellRangeAddress.valueOf("A18:G18"),
            CellRangeAddress.valueOf("A19:G19"), CellRangeAddress.valueOf("A20:G20"),
            CellRangeAddress.valueOf("A21:G21"), CellRangeAddress.valueOf("A22:G22"),
            CellRangeAddress.valueOf("A27:G27"), CellRangeAddress.valueOf("A28:G28"),
            CellRangeAddress.valueOf("A29:G29") };

    /*
    Applying above created rule formatting to cells
    */
    sheetCF.addConditionalFormatting(regionsAction, rule2);
    sheetCF.addConditionalFormatting(regionsAdv, rule3);

    /*
     Setting coloumn header values
    */
    int mainCellIndex = 0;

    Cell cell0 = rowMain.createCell(mainCellIndex++);
    cell0.setCellValue("SNO");
    cell0.setCellStyle(style1);
    Cell cell1 = rowMain.createCell(mainCellIndex++);
    cell1.setCellValue("Genre");
    cell1.setCellStyle(style1);
    Cell cell2 = rowMain.createCell(mainCellIndex++);
    cell2.setCellValue("Credit Score");
    cell2.setCellStyle(style1);
    Cell cell3 = rowMain.createCell(mainCellIndex++);
    cell3.setCellValue("Album Name");
    cell3.setCellStyle(style1);
    Cell cell4 = rowMain.createCell(mainCellIndex++);
    cell4.setCellValue("Artist");
    cell4.setCellStyle(style1);
    Cell cell5 = rowMain.createCell(mainCellIndex++);
    cell5.setCellValue("Release Date");
    cell5.setCellStyle(style1);

    /*
    populating cell values
    */
    int rowIndex = 4;
    int sno = 1;
    for (Song song : songList) {
        if (song.getSno() != 0) {

            Row row = songsSheet.createRow(rowIndex++);
            int cellIndex = 0;

            /*
            first place in row is Sno
            */

            Cell cell20 = row.createCell(cellIndex++);
            cell20.setCellValue(sno++);
            cell20.setCellStyle(style14);

            /*
            second place in row is  Genre
            */
            Cell cell21 = row.createCell(cellIndex++);
            cell21.setCellValue(song.getGenre());
            cell21.setCellStyle(style13);

            /*
            third place in row is Critic score
            */
            Cell cell22 = row.createCell(cellIndex++);
            cell22.setCellValue(song.getCriticscore());
            cell22.setCellStyle(style14);

            /*
            fourth place in row is Album name
            */
            Cell cell23 = row.createCell(cellIndex++);
            cell23.setCellValue(song.getAlbumname());
            cell23.setCellStyle(style13);

            /*
            fifth place in row is Artist
            */
            Cell cell24 = row.createCell(cellIndex++);
            cell24.setCellValue(song.getArtist());
            cell24.setCellStyle(style13);

            /*
            sixth place in row is marks in date
            */
            if (song.getReleasedate() != null) {

                Cell date = row.createCell(cellIndex++);

                DataFormat format = workbook.createDataFormat();
                CellStyle dateStyle = workbook.createCellStyle();
                dateStyle.setDataFormat(format.getFormat("dd-MMM-yyyy"));
                date.setCellStyle(dateStyle);

                date.setCellValue(song.getReleasedate());

                /*
                auto-resizing columns
                */
                songsSheet.autoSizeColumn(6);
                songsSheet.autoSizeColumn(5);
                songsSheet.autoSizeColumn(4);
                songsSheet.autoSizeColumn(3);
                songsSheet.autoSizeColumn(2);
            }

        }
    }

    /*
    writing this workbook to excel file.
    */
    try {
        FileOutputStream fos = new FileOutputStream(FILE_PATH);
        workbook.write(fos);
        fos.close();

        System.out.println(FILE_PATH + " is successfully written");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.report.template.LoanCalculator.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;/*ww  w . jav  a  2 s  .co m*/

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else
        wb = new XSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);
    Sheet sheet = wb.createSheet("Loan Calculator");
    sheet.setPrintGridlines(false);
    sheet.setDisplayGridlines(false);

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    sheet.setColumnWidth(0, 3 * 256);
    sheet.setColumnWidth(1, 3 * 256);
    sheet.setColumnWidth(2, 11 * 256);
    sheet.setColumnWidth(3, 14 * 256);
    sheet.setColumnWidth(4, 14 * 256);
    sheet.setColumnWidth(5, 14 * 256);
    sheet.setColumnWidth(6, 14 * 256);

    createNames(wb);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(35);
    for (int i = 1; i <= 7; i++) {
        titleRow.createCell(i).setCellStyle(styles.get("title"));
    }
    Cell titleCell = titleRow.getCell(2);
    titleCell.setCellValue("Simple Loan Calculator");
    sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1"));

    Row row = sheet.createRow(2);
    Cell cell = row.createCell(4);
    cell.setCellValue("Enter values");
    cell.setCellStyle(styles.get("item_right"));

    row = sheet.createRow(3);
    cell = row.createCell(2);
    cell.setCellValue("Loan amount");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellValue("123123");
    cell.setCellStyle(styles.get("input_$"));
    cell.setAsActiveCell();

    row = sheet.createRow(4);
    cell = row.createCell(2);
    cell.setCellValue("Annual interest rate");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_%"));

    row = sheet.createRow(5);
    cell = row.createCell(2);
    cell.setCellValue("Loan period in years");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_i"));

    row = sheet.createRow(6);
    cell = row.createCell(2);
    cell.setCellValue("Start date of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_d"));

    row = sheet.createRow(8);
    cell = row.createCell(2);
    cell.setCellValue("Monthly payment");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(9);
    cell = row.createCell(2);
    cell.setCellValue("Number of payments");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")");
    cell.setCellStyle(styles.get("formula_i"));

    row = sheet.createRow(10);
    cell = row.createCell(2);
    cell.setCellValue("Total interest");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(11);
    cell = row.createCell(2);
    cell.setCellValue("Total cost of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    // Write the output to a file
    String file = "loan-calculator.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:com.saba.CalendarDemo.java

License:Apache License

private static void prepareContactDetailsTableAndData(Map<String, Object> data, XSSFSheet sheet,
        Map<String, CellStyle> styles) {
    XSSFRow titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(16);//from ww w .  j a v  a  2 s.co m
    for (int i = 0; i <= 1; i++) {
        titleRow.createCell(i).setCellStyle(styles.get("title"));
    }
    XSSFCell titleCell = titleRow.getCell(0);
    titleCell.setCellValue(awardHeaders[0].toString());
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$B$1"));

    for (int i = 0; i < contactDetails.length; i++) {
        XSSFRow row = sheet.createRow(i + 1);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue(contactDetails[i].toString());
        cell.setCellStyle(styles.get("item_left"));
        cell = row.createCell(1);
        populateDynamicObject(cell, data.get(contactDetails[i]));
        cell.setCellStyle(styles.get("item_right"));
    }
}

From source file:com.saba.CalendarDemo.java

License:Apache License

private static void prepareAwardBidDetailsTableAndData(Map<String, Object> data, XSSFSheet sheet,
        Map<String, CellStyle> styles, int contactdetrow) {
    XSSFRow titleRow;//from  ww w. ja va 2  s .c  om
    XSSFCell titleCell;
    titleRow = sheet.createRow(contactdetrow);
    titleRow.setHeightInPoints(16);
    for (int i = 0; i <= 1; i++) {
        titleRow.createCell(i).setCellStyle(styles.get("title"));
    }
    titleCell = titleRow.getCell(0);
    titleCell.setCellValue(awardHeaders[1].toString());
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$" + (contactdetrow + 1) + ":$B$" + (contactdetrow + 1)));
    for (int i = 0; i < awardedBidDetails.length; i++) {
        XSSFRow row = sheet.createRow(contactdetrow + i + 1);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue(awardedBidDetails[i]);
        cell.setCellStyle(styles.get("item_left"));
        cell = row.createCell(1);
        populateDynamicObject(cell, data.get(awardedBidDetails[i]));
        cell.setCellStyle(styles.get("item_right"));
    }
}