Example usage for org.apache.poi.ss.usermodel WorkbookFactory create

List of usage examples for org.apache.poi.ss.usermodel WorkbookFactory create

Introduction

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

Prototype

public static Workbook create(File file) throws IOException, EncryptedDocumentException 

Source Link

Document

Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given File, which must exist and be readable.

Usage

From source file:Formatter.java

public Formatter(File file) {
    FileInputStream ins = null;/*w  ww.jav  a 2 s  .c  om*/
    try {
        ins = new FileInputStream(file);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Formatter.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        wb = WorkbookFactory.create(ins);
    } catch (IOException | InvalidFormatException | EncryptedDocumentException ex) {
        Logger.getLogger(Formatter.class.getName()).log(Level.SEVERE, null, ex);
    }

    worksheet = wb.getSheetAt(0);
}

From source file:Report_PRCR_New_ETF_Excel_File_Generator.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {/*from w  w w  .ja  v  a2s .c om*/

        DatabaseManager dbm = DatabaseManager.getDbCon();
        Date_Handler dt = new Date_Handler();

        String year = yearfield.getText();
        String month = dt.return_month_as_num(monthfield.getText());
        String employee_detail_file_location;

        if (mv.SoftwareVersion() == 1) {
            employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "13", "location") + "/"
                    + year + month + ".xls";
            System.out.println(employee_detail_file_location);
            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "12", "location")),
                    new File(employee_detail_file_location));
        } else if (mv.SoftwareVersion() == 2) {
            employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "14", "location") + "/"
                    + year + month + ".xls";
            System.out.println(employee_detail_file_location);
            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "13", "location")),
                    new File(employee_detail_file_location));
        } else {
            employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "13", "location") + "/"
                    + year + month + ".xls";
            System.out.println(employee_detail_file_location);
            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "12", "location")),
                    new File(employee_detail_file_location));
        }

        InputStream inp = new FileInputStream(employee_detail_file_location);

        Workbook wb = WorkbookFactory.create(inp);

        org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);

        String payment_date_year_month_date = null;

        String table_name = "pr_workdata_" + year + "_" + month;

        String previous_table_name = null;

        if (Integer.parseInt(month) == 1) {
            previous_table_name = "pr_workdata_" + (Integer.parseInt(year) - 1) + "_" + 12;
        } else {
            if ((Integer.parseInt(month) - 1) < 10) {
                previous_table_name = "pr_workdata_" + year + "_0" + (Integer.parseInt(month) - 1);
            } else {
                previous_table_name = "pr_workdata_" + year + "_" + (Integer.parseInt(month) - 1);
            }
        }

        double employee_contribution_percentage = Math
                .round(Double.parseDouble(
                        dbm.checknReturnData("prcr_new_epf_details", "name", "etf_rate", "value")) * 100.0)
                / 100.0;

        String nic = null;
        String surname = null;
        String initials = null;
        int member_no = 0;
        /*double tot_contribution = 0;
        double employers_contribution = 0;*/
        double member_contribution = 0;
        double tot_earnings = 0;
        /*String member_status = null;
        String zone = null;
        int employer_number = 0;
        int contribution_period = 0;
        int data_submission_no = 0;
        double no_of_days_worked = 0;
        int occupation_classification_grade = 0;
                
        int payment_mode = 0;
        int payment_date = 0;
        String payment_reference = null;
        int d_o_code = 0;
                
        member_status = "E";
        zone = dbm.checknReturnData("prcr_new_epf_details", "name", "zone", "value");
        employer_number = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "employer_number", "value"));
        contribution_period = Integer.parseInt(year + month);
        data_submission_no = 1;
        occupation_classification_grade = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "occupation_classification_grade", "value"));
                
        int normal_days = 0;
        int sundays = 0;
                
        double ot_before = 0;
        double ot_after = 0;
        double hours_as_decimal = 0;
                
        int count = 0;
        double total_member_contribution = 0;
        int need_both_reports = 1;
        if (chk.isSelected()) {
        need_both_reports = 0;
        } else {
        need_both_reports = 1;
        }
        */
        int count = 0;
        ResultSet query = dbm
                .query("SELECT * FROM `" + table_name + "` WHERE `register_or_casual` = 1 AND `total_pay` > 0");
        while (query.next()) {
            ResultSet query1 = dbm
                    .query("SELECT * FROM `personal_info` WHERE `code` = '" + query.getInt("code") + "' ");
            while (query1.next()) {

                nic = query1.getString("nic").replaceAll("\\s+", "");

                surname = split_name(query1.getString("name"))[1];
                initials = split_name(query1.getString("name"))[0];

                member_no = Integer.parseInt(query1.getString("code"));
                //occupation_classification_grade = Integer.parseInt(query1.getString("occupation_grade"));
                //d_o_code = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "d_o_code", "value"));

                tot_earnings = Math.round(query.getDouble("total_pay") * 100.0) / 100.0;
                //employers_contribution = Math.round(tot_earnings * employer_contribution_percentage * 100.0) / 100.0;
                //member_contribution = Math.round(tot_earnings * employee_contribution_percentage * 100.0) / 100.0;
                //tot_contribution = employers_contribution + member_contribution;
                //total_member_contribution = total_member_contribution + tot_contribution;
                member_contribution = Math.round(tot_earnings * employee_contribution_percentage * 100.0)
                        / 100.0;
                //normal_days = query.getInt("normal_days");
                //sundays = query.getInt("sundays");
                /* ot_before = query.getDouble("ot_before_hours");
                 ot_after = query.getDouble("ot_after_hours");
                 if ((ot_before + ot_after) > 0) {
                 hours_as_decimal = (ot_before + ot_after) / 100;
                 } else {
                 hours_as_decimal = 0;
                 }
                 if ((normal_days + sundays + hours_as_decimal) > 0) {
                 no_of_days_worked = Math.round((normal_days + sundays + hours_as_decimal) * 100.0) / 100.0;
                 } else {
                 no_of_days_worked = 0;
                 } */
                // no_of_days_worked = normal_days + sundays;

                /*  if (dbm.checkWhetherDataExists(previous_table_name, "code", query1.getString("code")) == 1) {
                member_status = "E";
                  } else {
                member_status = "N";
                  }
                   */

                Row row = sheet.getRow(1 + count);
                if (row == null) {
                    row = sheet.createRow(1 + count);
                }

                for (int k = 0; k < 5; k++) {

                    Cell cell = row.getCell(k);

                    switch (k) {
                    case 0:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(member_no);
                        break;
                    case 1:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(initials);
                        break;
                    case 2:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(surname);
                        break;
                    case 3:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(nic);
                        break;
                    case 4:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(member_contribution);
                        break;
                    default:
                        break;
                    }

                }
                count++;
            }
            query1.close();
        }
        query.close();

        FileOutputStream fileOut = new FileOutputStream(employee_detail_file_location);
        wb.write(fileOut);
        fileOut.close();

        Desktop.getDesktop().open(new File(employee_detail_file_location));

    } catch (Exception ex) {
        System.out.println(ex);

        msg.showMessage(
                "Problem Occured.Check whether the Excel file is alredy opened.Please close it and try again..",
                "Error", "error");

    }
}

From source file:Report_PRCR_New_EPF_Excel_File_Generator.java

private void view1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_view1ActionPerformed
    try {/*  w  w  w  .j  ava2  s.co m*/

        DatabaseManager dbm = DatabaseManager.getDbCon();
        Date_Handler dt = new Date_Handler();

        String year = yearfield.getText();
        String month = dt.return_month_as_num(monthfield.getText());

        String employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "7", "location")
                + "/" + year + month + ".xls";
        System.out.println(employee_detail_file_location);
        copyFileUsingApacheCommonsIO(new File(dbm.checknReturnData("file_locations", "id", "6", "location")),
                new File(employee_detail_file_location));

        InputStream inp = new FileInputStream(employee_detail_file_location);

        Workbook wb = WorkbookFactory.create(inp);

        org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);

        String payment_date_year_month_date = null;

        String table_name = "pr_workdata_" + year + "_" + month;

        String epf_backup_year_month = year + "_" + month;

        String previous_table_name = null;

        if (Integer.parseInt(month) == 1) {
            previous_table_name = "pr_workdata_" + (Integer.parseInt(year) - 1) + "_" + 12;
        } else {
            if ((Integer.parseInt(month) - 1) < 10) {
                previous_table_name = "pr_workdata_" + year + "_0" + (Integer.parseInt(month) - 1);
            } else {
                previous_table_name = "pr_workdata_" + year + "_" + (Integer.parseInt(month) - 1);
            }
        }

        double employee_contribution_percentage = Math.round(Double.parseDouble(
                dbm.checknReturnData("prcr_new_epf_details", "name", "employee_contribution", "value")) * 100.0)
                / 100.0;
        double employer_contribution_percentage = Math.round(Double.parseDouble(
                dbm.checknReturnData("prcr_new_epf_details", "name", "employer_contribution", "value")) * 100.0)
                / 100.0;

        String nic = null;
        String surname = null;
        String initials = null;
        int member_no = 0;
        double tot_contribution = 0;
        double employers_contribution = 0;
        double member_contribution = 0;
        double tot_earnings = 0;
        String member_status = null;
        String zone = null;
        int employer_number = 0;
        int contribution_period = 0;
        int data_submission_no = 0;
        double no_of_days_worked = 0;
        int occupation_classification_grade = 0;

        int payment_mode = 0;
        int payment_date = 0;
        String payment_reference = null;
        int d_o_code = 0;

        member_status = "E";
        zone = dbm.checknReturnData("prcr_new_epf_details", "name", "zone", "value");
        employer_number = Integer
                .parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "employer_number", "value"));
        contribution_period = Integer.parseInt(year + month);
        data_submission_no = 1;
        occupation_classification_grade = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name",
                "occupation_classification_grade", "value"));

        int normal_days = 0;
        int sundays = 0;

        double ot_before = 0;
        double ot_after = 0;
        double hours_as_decimal = 0;

        int count = 0;
        double total_member_contribution = 0;
        int need_both_reports = 1;
        if (chk.isSelected()) {
            need_both_reports = 0;
        } else {
            need_both_reports = 1;
        }

        ResultSet query = dbm
                .query("SELECT * FROM `" + table_name + "` WHERE `register_or_casual` = 1 AND `total_pay` > 0");
        while (query.next()) {
            ResultSet query1 = dbm
                    .query("SELECT * FROM `personal_info` WHERE `code` = '" + query.getInt("code") + "' ");
            while (query1.next()) {

                nic = query1.getString("nic").replaceAll("\\s+", "");

                surname = split_name(query1.getString("name"))[1];
                initials = split_name(query1.getString("name"))[0];

                member_no = Integer.parseInt(query1.getString("code"));
                occupation_classification_grade = Integer.parseInt(query1.getString("occupation_grade"));

                tot_earnings = Math.round(query.getDouble("total_pay") * 100.0) / 100.0;

                if (dbm.checkWhetherDataExistsTwoColumns("prcr_epf_etf_backup", "month", epf_backup_year_month,
                        "code", member_no) == 1) {
                    tot_earnings = tot_earnings
                            + Double.parseDouble(dbm.checknReturnDatafor2checks("prcr_epf_etf_backup", "month",
                                    epf_backup_year_month, "code", member_no, "total_pay"));
                }

                employers_contribution = Math.round(tot_earnings * employer_contribution_percentage * 100.0)
                        / 100.0;
                member_contribution = Math.round(tot_earnings * employee_contribution_percentage * 100.0)
                        / 100.0;
                tot_contribution = employers_contribution + member_contribution;
                total_member_contribution = total_member_contribution + tot_contribution;

                normal_days = query.getInt("normal_days");
                sundays = query.getInt("sundays");
                ot_before = query.getDouble("ot_before_hours");
                ot_after = query.getDouble("ot_after_hours");
                if ((ot_before + ot_after) > 0) {
                    hours_as_decimal = (ot_before + ot_after) / 100;
                } else {
                    hours_as_decimal = 0;
                }
                if ((normal_days + sundays + hours_as_decimal) > 0) {
                    no_of_days_worked = Math.round((normal_days + sundays + hours_as_decimal) * 100.0) / 100.0;
                } else {
                    no_of_days_worked = 0;
                }

                if (dbm.checkWhetherDataExists(previous_table_name, "code", query1.getString("code")) == 1) {
                    member_status = "E";
                } else {
                    member_status = "N";
                }

                Row row = sheet.getRow(4 + count);
                if (row == null) {
                    row = sheet.createRow(4 + count);
                }

                for (int k = 0; k < 15; k++) {

                    Cell cell = row.getCell(k);

                    switch (k) {
                    case 0:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(nic);
                        break;
                    case 1:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(surname);
                        break;
                    case 2:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(initials);
                        break;
                    case 3:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(member_no);
                        break;
                    case 4:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(tot_contribution);
                        break;
                    case 5:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(employers_contribution);
                        break;
                    case 6:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(member_contribution);
                        break;
                    case 7:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(tot_earnings);
                        break;
                    case 8:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(member_status);
                        break;
                    case 9:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(zone);
                        break;
                    case 10:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(employer_number);
                        break;
                    case 11:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(contribution_period);
                        break;
                    case 12:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(data_submission_no);
                        break;
                    case 13:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(no_of_days_worked);
                        break;
                    case 14:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(occupation_classification_grade);
                        break;
                    default:
                        break;
                    }

                }
                count++;
            }
            query1.close();
        }
        query.close();

        FileOutputStream fileOut = new FileOutputStream(employee_detail_file_location);
        wb.write(fileOut);
        fileOut.close();

        Desktop.getDesktop().open(new File(employee_detail_file_location));

        if (need_both_reports == 1) {

            if (Integer.parseInt(dayfield.getText()) < 10) {
                payment_date_year_month_date = yearfield1.getText()
                        + dt.return_month_as_num(monthfield1.getText()) + "0" + dayfield.getText();
            } else {
                payment_date_year_month_date = yearfield1.getText()
                        + dt.return_month_as_num(monthfield1.getText()) + dayfield.getText();
            }
            payment_date = Integer.parseInt(payment_date_year_month_date);
            payment_mode = payment_mode_combo.getSelectedIndex() + 1;

            payment_reference = payment_referrence_textFiield.getText();

            d_o_code = Integer
                    .parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "d_o_code", "value"));

            String total_contribution_file_location = dbm.checknReturnData("file_locations", "id", "9",
                    "location") + "/" + year + month + "_total_contribution.xls";

            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "8", "location")),
                    new File(total_contribution_file_location));

            InputStream inp2 = new FileInputStream(total_contribution_file_location);

            Workbook wb2 = WorkbookFactory.create(inp2);

            org.apache.poi.ss.usermodel.Sheet sheet2 = wb2.getSheetAt(0);

            Row row = sheet2.getRow(17);
            if (row == null) {
                row = sheet.createRow(17);
            }

            for (int k = 0; k < 10; k++) {

                Cell cell = row.getCell(k);

                switch (k) {
                case 0:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue(zone);
                    break;
                case 1:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(employer_number);
                    break;
                case 2:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(contribution_period);
                    break;
                case 3:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(data_submission_no);
                    break;
                case 4:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(total_member_contribution);
                    break;
                case 5:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(count);
                    break;
                case 6:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(payment_mode);
                    break;
                case 7:
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue(payment_reference);
                    break;
                case 8:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(payment_date);
                    break;
                case 9:
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(d_o_code);
                    break;
                default:
                    break;
                }

            }

            FileOutputStream fileOut2 = new FileOutputStream(total_contribution_file_location);
            wb2.write(fileOut2);
            fileOut2.close();

            Desktop.getDesktop().open(new File(total_contribution_file_location));

        }

    } catch (Exception ex) {
        System.out.println(ex);
        msg.showMessage(
                "Problem Occured.Check whether the Excel file is alredy opened.Please close it and try again..",
                "Error", "error");

    }
}

From source file:Report_PRCR_New_EPF_Excel_File_Generator.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {/*w ww .  j a v a 2 s . c  om*/

        DatabaseManager dbm = DatabaseManager.getDbCon();
        Date_Handler dt = new Date_Handler();

        String year = yearfield.getText();
        String month = dt.return_month_as_num(monthfield.getText());
        String employee_detail_file_location;

        if (mv.SoftwareVersion() == 1) {
            employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "11", "location") + "/"
                    + year + month + ".xls";
            System.out.println(employee_detail_file_location);
            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "10", "location")),
                    new File(employee_detail_file_location));
        } else if (mv.SoftwareVersion() == 2) {
            employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "12", "location") + "/"
                    + year + month + ".xls";
            System.out.println(employee_detail_file_location);
            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "11", "location")),
                    new File(employee_detail_file_location));
        } else {
            employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "11", "location") + "/"
                    + year + month + ".xls";
            System.out.println(employee_detail_file_location);
            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "10", "location")),
                    new File(employee_detail_file_location));
        }

        InputStream inp = new FileInputStream(employee_detail_file_location);

        Workbook wb = WorkbookFactory.create(inp);

        org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);

        String payment_date_year_month_date = null;

        String table_name = "pr_workdata_" + year + "_" + month;

        String epf_backup_year_month = year + "_" + month;

        String previous_table_name = null;

        if (Integer.parseInt(month) == 1) {
            previous_table_name = "pr_workdata_" + (Integer.parseInt(year) - 1) + "_" + 12;
        } else {
            if ((Integer.parseInt(month) - 1) < 10) {
                previous_table_name = "pr_workdata_" + year + "_0" + (Integer.parseInt(month) - 1);
            } else {
                previous_table_name = "pr_workdata_" + year + "_" + (Integer.parseInt(month) - 1);
            }
        }

        double employee_contribution_percentage = Math.round(Double.parseDouble(
                dbm.checknReturnData("prcr_new_epf_details", "name", "employee_contribution", "value")) * 100.0)
                / 100.0;
        double employer_contribution_percentage = Math.round(Double.parseDouble(
                dbm.checknReturnData("prcr_new_epf_details", "name", "employer_contribution", "value")) * 100.0)
                / 100.0;

        String nic = null;
        String surname = null;
        String initials = null;
        int member_no = 0;
        double tot_contribution = 0;
        double employers_contribution = 0;
        double member_contribution = 0;
        double tot_earnings = 0;
        String member_status = null;
        String zone = null;
        int employer_number = 0;
        int contribution_period = 0;
        int data_submission_no = 0;
        double no_of_days_worked = 0;
        int occupation_classification_grade = 0;

        int payment_mode = 0;
        int payment_date = 0;
        String payment_reference = null;
        int d_o_code = 0;

        member_status = "E";
        zone = dbm.checknReturnData("prcr_new_epf_details", "name", "zone", "value");
        employer_number = Integer
                .parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "employer_number", "value"));
        contribution_period = Integer.parseInt(year + month);
        data_submission_no = 1;
        occupation_classification_grade = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name",
                "occupation_classification_grade", "value"));

        int normal_days = 0;
        int sundays = 0;

        double ot_before = 0;
        double ot_after = 0;
        double hours_as_decimal = 0;

        int count = 0;
        double total_member_contribution = 0;
        int need_both_reports = 1;
        if (chk.isSelected()) {
            need_both_reports = 0;
        } else {
            need_both_reports = 1;
        }

        ResultSet query = dbm.query("SELECT * FROM `" + table_name + "` WHERE `register_or_casual` = 1 "); // AND `total_pay` > 0");
        while (query.next()) {

            if (query.getDouble("total_pay") <= 0 && dbm.checkWhetherDataExistsTwoColumns("prcr_epf_etf_backup",
                    "month", epf_backup_year_month, "code", query.getInt("code")) != 1) {
                continue;
            }
            ResultSet query1 = dbm
                    .query("SELECT * FROM `personal_info` WHERE `code` = '" + query.getInt("code") + "' ");
            while (query1.next()) {

                nic = query1.getString("nic").replaceAll("\\s+", "");

                surname = split_name(query1.getString("name"))[1];
                initials = split_name(query1.getString("name"))[0];

                member_no = Integer.parseInt(query1.getString("code"));
                occupation_classification_grade = Integer.parseInt(query1.getString("occupation_grade"));
                d_o_code = Integer
                        .parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "d_o_code", "value"));

                tot_earnings = Math.round(query.getDouble("total_pay") * 100.0) / 100.0;

                if (dbm.checkWhetherDataExistsTwoColumns("prcr_epf_etf_backup", "month", epf_backup_year_month,
                        "code", member_no) == 1) {
                    tot_earnings = tot_earnings
                            + Double.parseDouble(dbm.checknReturnDatafor2checks("prcr_epf_etf_backup", "month",
                                    epf_backup_year_month, "code", member_no, "total_pay"));
                }

                employers_contribution = Math.round(tot_earnings * employer_contribution_percentage * 100.0)
                        / 100.0;
                member_contribution = Math.round(tot_earnings * employee_contribution_percentage * 100.0)
                        / 100.0;
                tot_contribution = employers_contribution + member_contribution;
                total_member_contribution = total_member_contribution + tot_contribution;

                normal_days = query.getInt("normal_days");
                sundays = query.getInt("sundays");
                /* ot_before = query.getDouble("ot_before_hours");
                 ot_after = query.getDouble("ot_after_hours");
                 if ((ot_before + ot_after) > 0) {
                 hours_as_decimal = (ot_before + ot_after) / 100;
                 } else {
                 hours_as_decimal = 0;
                 }
                 if ((normal_days + sundays + hours_as_decimal) > 0) {
                 no_of_days_worked = Math.round((normal_days + sundays + hours_as_decimal) * 100.0) / 100.0;
                 } else {
                 no_of_days_worked = 0;
                 } */
                no_of_days_worked = normal_days + sundays;

                if (dbm.checkWhetherDataExists(previous_table_name, "code", query1.getString("code")) == 1) {
                    member_status = "E";
                } else {
                    member_status = "N";
                }

                Row row = sheet.getRow(1 + count);
                if (row == null) {
                    row = sheet.createRow(1 + count);
                }

                for (int k = 0; k < 16; k++) {

                    Cell cell = row.getCell(k);

                    switch (k) {
                    case 0:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(nic);
                        break;
                    case 1:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(surname);
                        break;
                    case 2:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(initials);
                        break;
                    case 3:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(member_no);
                        break;
                    case 4:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(tot_contribution);
                        break;
                    case 5:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(employers_contribution);
                        break;
                    case 6:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(member_contribution);
                        break;
                    case 7:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(tot_earnings);
                        break;
                    case 8:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(member_status);
                        break;
                    case 9:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(zone);
                        break;
                    case 10:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(employer_number);
                        break;
                    case 11:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(contribution_period);
                        break;
                    case 12:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(data_submission_no);
                        break;
                    case 13:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(no_of_days_worked);
                        break;
                    case 14:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(occupation_classification_grade);
                        break;
                    case 15:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(d_o_code);
                        break;
                    default:
                        break;
                    }

                }
                count++;
            }
            query1.close();
        }
        query.close();

        FileOutputStream fileOut = new FileOutputStream(employee_detail_file_location);
        wb.write(fileOut);
        fileOut.close();

        Desktop.getDesktop().open(new File(employee_detail_file_location));

    } catch (Exception ex) {
        System.out.println(ex);
        msg.showMessage(
                "Problem Occured.Check whether the Excel file is alredy opened.Please close it and try again..",
                "Error", "error");

    }
}

From source file:JrubyTest.java

License:Apache License

private Workbook load(InputStream in) throws InvalidFormatException, IOException {
    Workbook workbook = WorkbookFactory.create(in);
    return workbook;
}

From source file:ApachePOIExcelWrite.java

@Override
public void doInvokeMethod(String MethodName, SiebelPropertySet inputs, SiebelPropertySet outputs)
        throws SiebelBusinessServiceException {
    if (MethodName.equalsIgnoreCase("GenerateExcelDoc")) {
        try {/*from ww  w .j a  va 2  s .c o  m*/
            //
            //IProperties AP = new ApplicationProperties();
            SiebelDataBean conn = ApplicationsConnection.connectSiebelServer();
            //Get excel path
            System.out.println(HelperAP.getInvoiceTemplate());
            inputFile = HelperAP.getInvoiceTemplate();
            //Read Excel document first
            input_document = new FileInputStream(new File(inputFile));
            // Convert it into a POI object
            Workbook my_xlsx_workbook = WorkbookFactory.create(input_document);
            // Read excel sheet that needs to be updated
            Sheet my_worksheet = my_xlsx_workbook.getSheet("Sheet1");
            // Declare a Cell object
            this.order_id = inputs.getProperty("QuoteId");
            this.quote_number = inputs.getProperty("QuoteNum");

            CustomerRecord customerInfo = new CustomerRecord(my_xlsx_workbook, my_worksheet, 3);
            customerInfo.setQuoteId(this.order_id);
            customerInfo.createCellFromList(new QShippment(conn), new ContactKey());
            customerInfo.setStartRow(8);
            customerInfo.createCellFromList(new QAddress(conn), new ContactKey());

            InvoiceExcel parts;

            int startRowAt = 17;
            parts = new InvoiceExcel(my_xlsx_workbook, my_worksheet);

            //
            parts.setStartRow(startRowAt);
            parts.setQuoteId(order_id);
            parts.createCellFromList(new QParts(conn), new ContactKey());
            my_xlsx_workbook.setForceFormulaRecalculation(true);
            input_document.close();
            XGenerator.doCreateBook(my_xlsx_workbook, "weststar_" + this.quote_number.replace(" ", "_"));
            Attachment a = new Attachment(conn, "Quote", "Quote Attachment");
            String filepath = XGenerator.getProperty("filepath");
            String filename = XGenerator.getProperty("filename");

            //Attach the file to siebel
            a.Attach(filepath, filename, Boolean.FALSE, order_id);

            boolean logoff = conn.logoff();
            my_xlsx_workbook.close();
            System.out.println("Done");
            outputs.setProperty("status", "success");
        } catch (FileNotFoundException ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE,
                    "Caught File Not Found Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        } catch (IOException ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE, "Caught IO Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        } catch (InvalidFormatException ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE,
                    "Caught Invalid Format Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        } catch (EncryptedDocumentException ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE,
                    "Caught Encrypted Document Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        } catch (Exception ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE, "Caught Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        }
    }
}

From source file:CatalogMain.java

License:BSD License

public void initializeRead() {

    workbook = null;//w w  w.j  a v  a2 s  .  c o m
    try {
        workbook = WorkbookFactory.create(new FileInputStream(excelFilePath));
    } catch (InvalidFormatException | IOException e) {
        JOptionPane.showMessageDialog(null,
                "An error has occurred (CatalogMain-initializeRead). Application will now terminate.");
        System.exit(0);
    }
}

From source file:CatalogMain.java

License:BSD License

public void loadTemplate(String language) {

    templateWorkbook = null;/*ww  w  .  j a v a2s .c  o  m*/
    InputStream input = null;
    tempLang = null;

    try {

        switch (language) {

        case "en":
            tempLang = "en.xlsx";
            break;
        case "de":
            tempLang = "de.xlsx";
            break;
        case "fr":
            tempLang = "fr.xlsx";
            break;
        default:
            return;
        }

        templateVersion = templateFile.substring(29, 33);
        input = CatalogMain.class.getClassLoader().getResourceAsStream("resource/" + templateFile + tempLang);
        templateWorkbook = WorkbookFactory.create(input);
        mainWindow.setTitle("Portrayal Catalogue Valdiator " + validatorVersion + "   |   "
                + templateFile.substring(20, 33) + tempLang.substring(0, 2));

    } catch (InvalidFormatException | IOException e) {
        JOptionPane.showMessageDialog(null,
                "An error has occurred (CatalogMain-loadTemplate). Application will now terminate.");
        System.exit(0);
    }
}

From source file:CellStyleDetails.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        throw new IllegalArgumentException("Filename must be given");
    }//  w  ww  .  j  a v a2  s.  c o  m

    Workbook wb = WorkbookFactory.create(new File(args[0]));
    DataFormatter formatter = new DataFormatter();

    for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) {
        Sheet sheet = wb.getSheetAt(sn);
        System.out.println("Sheet #" + sn + " : " + sheet.getSheetName());

        for (Row row : sheet) {
            System.out.println("  Row " + row.getRowNum());

            for (Cell cell : row) {
                CellReference ref = new CellReference(cell);
                System.out.print("    " + ref.formatAsString());
                System.out.print(" (" + cell.getColumnIndex() + ") ");

                CellStyle style = cell.getCellStyle();
                System.out.print("Format=" + style.getDataFormatString() + " ");
                System.out.print("FG=" + renderColor(style.getFillForegroundColorColor()) + " ");
                System.out.print("BG=" + renderColor(style.getFillBackgroundColorColor()) + " ");

                Font font = wb.getFontAt(style.getFontIndex());
                System.out.print("Font=" + font.getFontName() + " ");
                System.out.print("FontColor=");
                if (font instanceof HSSFFont) {
                    System.out.print(renderColor(((HSSFFont) font).getHSSFColor((HSSFWorkbook) wb)));
                }
                if (font instanceof XSSFFont) {
                    System.out.print(renderColor(((XSSFFont) font).getXSSFColor()));
                }

                System.out.println();
                System.out.println("        " + formatter.formatCellValue(cell));
            }
        }

        System.out.println();
    }
}

From source file:adams.data.io.input.ExcelSpreadSheetReader.java

License:Open Source License

/**
 * Reads the spreadsheet content from the specified file.
 *
 * @param in      the input stream to read from
 * @return      the spreadsheets or null in case of an error
 *//*from   w ww  .  j a  v a 2  s .c  om*/
@Override
protected List<SpreadSheet> doReadRange(InputStream in) {
    List<SpreadSheet> result;
    int[] indices;
    Workbook workbook;
    Sheet sheet;
    SpreadSheet spsheet;
    Row exRow;
    Cell exCell;
    adams.data.spreadsheet.Row spRow;
    int i;
    int n;
    int cellType;
    DateFormat dformat;
    boolean numeric;
    int dataRowStart;
    int firstRow;
    int lastRow;
    List<String> header;

    result = new ArrayList<>();

    workbook = null;
    dformat = DateUtils.getTimestampFormatter();
    try {
        workbook = WorkbookFactory.create(in);
        m_SheetRange.setMax(workbook.getNumberOfSheets());
        indices = m_SheetRange.getIntIndices();
        firstRow = m_FirstRow - 1;
        dataRowStart = getNoHeader() ? firstRow : firstRow + 1;
        for (int index : indices) {
            if (m_Stopped)
                break;

            spsheet = m_SpreadSheetType.newInstance();
            spsheet.setDataRowClass(m_DataRowType.getClass());
            result.add(spsheet);

            if (isLoggingEnabled())
                getLogger().info("sheet: " + (index + 1));

            sheet = workbook.getSheetAt(index);
            if (sheet.getLastRowNum() == 0) {
                getLogger().severe("No rows in sheet #" + index);
                return null;
            }
            spsheet.setName(sheet.getSheetName());

            // header
            if (isLoggingEnabled())
                getLogger().info("header row");
            exRow = sheet.getRow(firstRow);
            if (exRow == null) {
                getLogger().warning("No data in sheet #" + (index + 1) + "?");
            } else if (exRow != null) {
                spRow = spsheet.getHeaderRow();
                m_TextColumns.setMax(exRow.getLastCellNum());
                if (getNoHeader()) {
                    header = SpreadSheetUtils.createHeader(exRow.getLastCellNum(), m_CustomColumnHeaders);
                    for (i = 0; i < header.size(); i++)
                        spRow.addCell("" + (i + 1)).setContent(header.get(i));
                } else {
                    if (!m_CustomColumnHeaders.trim().isEmpty()) {
                        header = SpreadSheetUtils.createHeader(exRow.getLastCellNum(), m_CustomColumnHeaders);
                        for (i = 0; i < header.size(); i++)
                            spRow.addCell("" + (i + 1)).setContent(header.get(i));
                    } else {
                        for (i = 0; i < exRow.getLastCellNum(); i++) {
                            if (m_Stopped)
                                break;
                            exCell = exRow.getCell(i);
                            if (exCell == null) {
                                spRow.addCell("" + (i + 1)).setMissing();
                                continue;
                            }
                            numeric = !m_TextColumns.isInRange(i);
                            switch (exCell.getCellType()) {
                            case Cell.CELL_TYPE_BLANK:
                            case Cell.CELL_TYPE_ERROR:
                                spRow.addCell("" + (i + 1)).setContent("column-" + (i + 1));
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(exCell))
                                    spRow.addCell("" + (i + 1)).setContent(new DateTime(
                                            HSSFDateUtil.getJavaDate(exCell.getNumericCellValue())));
                                else if (numeric)
                                    spRow.addCell("" + (i + 1)).setContent(exCell.getNumericCellValue());
                                else
                                    spRow.addCell("" + (i + 1)).setContentAsString(numericToString(exCell));
                                break;
                            default:
                                spRow.addCell("" + (i + 1)).setContentAsString(exCell.getStringCellValue());
                            }
                        }
                    }
                }
            }

            // data
            if (spsheet.getColumnCount() > 0) {
                if (m_NumRows < 1)
                    lastRow = sheet.getLastRowNum();
                else
                    lastRow = Math.min(firstRow + m_NumRows - 1, sheet.getLastRowNum());
                for (i = dataRowStart; i <= lastRow; i++) {
                    if (m_Stopped)
                        break;
                    if (isLoggingEnabled())
                        getLogger().info("data row: " + (i + 1));
                    spRow = spsheet.addRow("" + spsheet.getRowCount());
                    exRow = sheet.getRow(i);
                    if (exRow == null)
                        continue;
                    for (n = 0; n < exRow.getLastCellNum(); n++) {
                        // too few columns in header?
                        if ((n >= spsheet.getHeaderRow().getCellCount()) && m_AutoExtendHeader)
                            spsheet.insertColumn(spsheet.getColumnCount(), "");

                        m_TextColumns.setMax(spsheet.getHeaderRow().getCellCount());
                        exCell = exRow.getCell(n);
                        if (exCell == null) {
                            spRow.addCell(n).setMissing();
                            continue;
                        }
                        cellType = exCell.getCellType();
                        if (cellType == Cell.CELL_TYPE_FORMULA)
                            cellType = exCell.getCachedFormulaResultType();
                        numeric = !m_TextColumns.isInRange(n);
                        switch (cellType) {
                        case Cell.CELL_TYPE_BLANK:
                        case Cell.CELL_TYPE_ERROR:
                            if (m_MissingValue.isEmpty())
                                spRow.addCell(n).setMissing();
                            else
                                spRow.addCell(n).setContent("");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(exCell))
                                spRow.addCell(n).setContent(
                                        dformat.format(HSSFDateUtil.getJavaDate(exCell.getNumericCellValue())));
                            else if (numeric)
                                spRow.addCell(n).setContent(exCell.getNumericCellValue());
                            else
                                spRow.addCell(n).setContentAsString(numericToString(exCell));
                            break;
                        default:
                            if (m_MissingValue.isMatch(exCell.getStringCellValue()))
                                spRow.addCell(n).setMissing();
                            else
                                spRow.addCell(n).setContentAsString(exCell.getStringCellValue());
                        }
                    }
                }
            }
        }
    } catch (Exception ioe) {
        getLogger().log(Level.SEVERE, "Failed to read range '" + m_SheetRange + "':", ioe);
        result = null;
        m_LastError = "Failed to read range '" + m_SheetRange + "' from stream!\n"
                + Utils.throwableToString(ioe);
    }

    return result;
}