Example usage for org.apache.poi.xssf.usermodel XSSFSheet autoSizeColumn

List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet autoSizeColumn

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFSheet autoSizeColumn.

Prototype

@Override
public void autoSizeColumn(int column) 

Source Link

Document

Adjusts the column width to fit the contents.

Usage

From source file:org.openelis.bean.ToDoExcelHelperBean.java

License:Open Source License

private void setSize(XSSFSheet sheet, int numCols) {
    for (int i = 0; i < numCols; i++)
        sheet.autoSizeColumn(i);
}

From source file:org.ramalapure.userinfoapp.UserInfoApp.java

@Override
public void start(Stage primaryStage) {
    CheckConnection();/*from w w w  . ja  v  a 2  s.co m*/
    fillComboBox();
    // create transperant stage
    //primaryStage.initStyle(StageStyle.TRANSPARENT);

    primaryStage.setTitle("JavaFX 8 Tutorial 61 - Retrive Database Values Into CheckBox");

    primaryStage.getIcons().add(new Image("file:user-icon.png"));
    BorderPane layout = new BorderPane();
    Scene newscene = new Scene(layout, 1200, 700, Color.rgb(0, 0, 0, 0));

    Group root = new Group();
    Scene scene = new Scene(root, 320, 200, Color.rgb(0, 0, 0, 0));
    scene.getStylesheets().add(getClass().getResource("Style.css").toExternalForm());

    Color foreground = Color.rgb(255, 255, 255, 0.9);

    //Rectangila Background
    Rectangle background = new Rectangle(320, 250);
    background.setX(0);
    background.setY(0);
    background.setArcHeight(15);
    background.setArcWidth(15);
    background.setFill(Color.rgb(0, 0, 0, 0.55));
    background.setStroke(foreground);
    background.setStrokeWidth(1.5);

    VBox vbox = new VBox(5);
    vbox.setPadding(new Insets(10, 0, 0, 10));

    Label label = new Label("Label");
    //label.setTextFill(Color.WHITESMOKE);
    label.setFont(new Font("SanSerif", 20));

    TextField username = new TextField();
    username.setFont(Font.font("SanSerif", 20));
    username.setPromptText("Username");
    username.getStyleClass().add("field-background");

    PasswordField password = new PasswordField();
    password.setFont(Font.font("SanSerif", 20));
    password.setPromptText("Password");
    password.getStyleClass().add("field-background");

    password.setOnKeyPressed(e -> {
        if (e.getCode() == KeyCode.ENTER) {
            try {
                String query = "select * from UserDatabase where Username=? and Password=?";
                pst = conn.prepareStatement(query);
                pst.setString(1, username.getText());
                pst.setString(2, password.getText());
                rs = pst.executeQuery();

                if (rs.next()) {
                    //label.setText("Login Successful");
                    primaryStage.setScene(newscene);
                    primaryStage.show();
                } else {
                    label.setText("Login Failed");
                }
                username.clear();
                password.clear();
                pst.close();
                rs.close();
            } catch (Exception e1) {
                label.setText("SQL Error");
                System.err.println(e1);
            }
        }
    });

    Button btn = new Button("Login");
    btn.setFont(Font.font("SanSerif", 15));
    btn.setOnAction(e -> {
        try {
            String query = "select * from UserDatabase where Username=? and Password=?";
            pst = conn.prepareStatement(query);
            pst.setString(1, username.getText());
            pst.setString(2, password.getText());
            rs = pst.executeQuery();

            if (rs.next()) {
                //label.setText("Login Successful");
                primaryStage.setScene(newscene);
                primaryStage.show();
            } else {
                label.setText("Login Failed");
            }
            username.clear();
            password.clear();
            pst.close();
            rs.close();
        } catch (Exception e1) {
            label.setText("SQL Error");
            System.err.println(e1);
        }
    });

    vbox.getChildren().addAll(label, username, password, btn);
    root.getChildren().addAll(background, vbox);

    Button logout = new Button("Logout");
    logout.setFont(Font.font("SanSerif", 15));
    logout.setOnAction(e -> {
        primaryStage.setScene(scene);
        primaryStage.show();
    });

    layout.setTop(logout);
    BorderPane.setAlignment(logout, Pos.TOP_RIGHT);
    BorderPane.setMargin(logout, new Insets(10));

    VBox fields = new VBox(5);
    searchField = new TextField();
    searchField.setFont(Font.font("SanSerif", 15));
    searchField.setPromptText("Search");
    searchField.setMaxWidth(200);

    Label label1 = new Label("Create New User");
    label1.setFont(new Font("Sanserif", 20));

    id = new TextField();
    id.setFont(Font.font("SanSerif", 15));
    id.setPromptText("ID");
    id.setMaxWidth(200);

    fn = new TextField();
    fn.setFont(Font.font("SanSerif", 15));
    fn.setPromptText("First Name");
    fn.setMaxWidth(200);

    ln = new TextField();
    ln.setFont(Font.font("SanSerif", 15));
    ln.setPromptText("Last Name");
    ln.setMaxWidth(200);

    em = new TextField();
    em.setFont(Font.font("SanSerif", 15));
    em.setPromptText("Email");
    em.setMaxWidth(200);

    mobile = new TextField();
    mobile.setFont(Font.font("SanSerif", 15));
    mobile.setPromptText("Mobile No.");
    mobile.setMaxWidth(200);

    un = new TextField();
    un.setFont(Font.font("SanSerif", 15));
    un.setPromptText("Username");
    un.setMaxWidth(200);

    pw = new PasswordField();
    pw.setFont(Font.font("SanSerif", 15));
    pw.setPromptText("Password");
    pw.setMaxWidth(200);

    date = new DatePicker();
    date.setPromptText("Date of Birth");
    date.setMaxWidth(200);
    date.setStyle("-fx-font-size:15");

    ToggleGroup gender = new ToggleGroup();

    male = new RadioButton("Male");
    male.setToggleGroup(gender);
    male.setOnAction(e -> {
        radioButtonLabel = male.getText();
    });

    female = new RadioButton("Female");
    female.setToggleGroup(gender);
    female.setOnAction(e -> {
        radioButtonLabel = female.getText();
    });

    checkBox1 = new CheckBox("Playing");
    checkBox1.setOnAction(e -> {
        checkBoxList.add(checkBox1.getText());
    });
    checkBox2 = new CheckBox("Singing");
    checkBox2.setOnAction(e -> {
        checkBoxList.add(checkBox2.getText());
    });
    checkBox3 = new CheckBox("Dancing");
    checkBox3.setOnAction(e -> {
        checkBoxList.add(checkBox3.getText());
    });

    date.requestFocus();
    male.requestFocus();
    female.requestFocus();
    checkBox1.requestFocus();
    checkBox2.requestFocus();
    checkBox3.requestFocus();

    textArea = new TextArea();
    textArea.setFont(Font.font("SanSerif", 12));
    textArea.setPromptText("Path Of Selected File Or Files");
    textArea.setPrefSize(300, 50);
    textArea.setEditable(false);

    fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().addAll(new ExtensionFilter("Text Files", "*txt"),
            new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
            new ExtensionFilter("Audio Files", "*wav", "*.mp3", "*.aac"),
            new ExtensionFilter("All Files", "*.*"));

    browse = new Button("Browse");
    browse.setFont(Font.font("SanSerif", 15));
    browse.setOnAction(e -> {
        //Single File Selection
        file = fileChooser.showOpenDialog(primaryStage);
        if (file != null) {
            textArea.setText(file.getAbsolutePath());
            image = new Image(file.toURI().toString(), 100, 150, true, true);//path, PrefWidth, PrefHeight, PreserveRatio, Smooth

            imageView = new ImageView(image);
            imageView.setFitWidth(100);
            imageView.setFitHeight(150);
            imageView.setPreserveRatio(true);

            layout.setCenter(imageView);
            BorderPane.setAlignment(imageView, Pos.TOP_LEFT);

        }

        //Multiple File Selection
        /*List<File> fileList = fileChooser.showOpenMultipleDialog(primaryStage);
        if(fileList != null){
        fileList.stream().forEach(selectedFiles ->{
            textArea.setText(fileList.toString());
        });
        }*/
    });

    Button button = new Button("Save");
    button.setFont(Font.font("SanSerif", 15));
    button.setOnAction(e -> {
        if (validateNumber() & validateFirstName() & validateLastName() & validateEmaill() & validateMobileNo()
                & validatePassword() & validateFields()) {
            try {
                String query = "INSERT INTO UserDatabase (ID, FirstName, LastName, Email, Username, Password, DOB, Gender, MobileNo, Hobbies, Image) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
                pst = conn.prepareStatement(query);

                pst.setString(1, id.getText());
                pst.setString(2, fn.getText());
                pst.setString(3, ln.getText());
                pst.setString(4, em.getText());
                pst.setString(5, un.getText());
                pst.setString(6, pw.getText());
                pst.setString(7, ((TextField) date.getEditor()).getText());
                pst.setString(8, radioButtonLabel);
                pst.setString(9, mobile.getText());
                pst.setString(10, checkBoxList.toString());

                fis = new FileInputStream(file);
                pst.setBinaryStream(11, (InputStream) fis, (int) file.length());

                Alert alert = new Alert(AlertType.INFORMATION);
                alert.setTitle("Information Dialog");
                alert.setHeaderText(null);
                alert.setContentText("User has been created.");
                alert.showAndWait();

                pst.execute();

                pst.close();
                clearFields();
            } catch (SQLException | FileNotFoundException e1) {
                label.setText("SQL Error");
                System.err.println(e1);
            }
            fillComboBox();
            refreshTable();
        }
    });

    Button update = new Button("Update");
    update.setFont(Font.font("SanSerif", 15));
    update.setOnAction(e -> {
        if (validateNumber() & validateFirstName() & validateLastName() & validateEmaill() & validateMobileNo()
                & validatePassword() & validateFields()) {
            try {
                String query = "update UserDatabase set ID=?, FirstName=?, LastName=?, Email=?, Username=?, Password=?, DOB=?, Gender=?, MobileNo=?, Hobbies=?, Image=? where ID='"
                        + id.getText() + "' ";
                pst = conn.prepareStatement(query);

                pst.setString(1, id.getText());
                pst.setString(2, fn.getText());
                pst.setString(3, ln.getText());
                pst.setString(4, em.getText());
                pst.setString(5, un.getText());
                pst.setString(6, pw.getText());
                pst.setString(7, ((TextField) date.getEditor()).getText());
                pst.setString(8, radioButtonLabel);
                pst.setString(9, mobile.getText());
                pst.setString(10, checkBoxList.toString());

                fis = new FileInputStream(file);
                pst.setBinaryStream(11, (InputStream) fis, (int) file.length());

                Alert alert = new Alert(AlertType.INFORMATION);
                alert.setTitle("Information Dialog");
                alert.setHeaderText(null);
                alert.setContentText("User details has been updated.");
                alert.showAndWait();

                pst.execute();

                pst.close();
                clearFields();
            } catch (SQLException | FileNotFoundException e1) {
                label.setText("SQL Error");
                System.err.println(e1);
            }
            fillComboBox();
            refreshTable();
        }
    });

    fields.getChildren().addAll(searchField, label1, id, fn, ln, em, mobile, un, pw, date, male, female,
            checkBox1, checkBox2, checkBox3, browse, textArea, button);
    layout.setLeft(fields);

    BorderPane.setMargin(fields, new Insets(0, 10, 0, 10));

    table = new TableView<>();

    TableColumn column1 = new TableColumn("ID");
    column1.setMaxWidth(50);
    column1.setCellValueFactory(new PropertyValueFactory<>("ID"));

    TableColumn column2 = new TableColumn("First Name");
    column2.setMinWidth(80);
    column2.setCellValueFactory(new PropertyValueFactory<>("firstName"));

    TableColumn column3 = new TableColumn("Last Name");
    column3.setMinWidth(80);
    column3.setCellValueFactory(new PropertyValueFactory<>("lastName"));

    TableColumn column4 = new TableColumn("Email");
    column4.setMinWidth(150);
    column4.setCellValueFactory(new PropertyValueFactory<>("email"));

    TableColumn column5 = new TableColumn("Username");
    column5.setMinWidth(80);
    column5.setCellValueFactory(new PropertyValueFactory<>("username"));

    TableColumn column6 = new TableColumn("Password");
    column6.setMinWidth(80);
    column6.setCellValueFactory(new PropertyValueFactory<>("password"));

    TableColumn column7 = new TableColumn("DOB");
    column7.setMinWidth(70);
    column7.setCellValueFactory(new PropertyValueFactory<>("DOB"));

    TableColumn column8 = new TableColumn("Gender");
    column8.setMinWidth(50);
    column8.setCellValueFactory(new PropertyValueFactory<>("Gender"));

    TableColumn column9 = new TableColumn("Mobile No.");
    column9.setMinWidth(70);
    column9.setCellValueFactory(new PropertyValueFactory<>("MobileNo"));

    TableColumn column10 = new TableColumn("Hobbies");
    column10.setMinWidth(100);
    column10.setCellValueFactory(new PropertyValueFactory<>("Hobbies"));

    table.getColumns().addAll(column1, column2, column3, column4, column5, column6, column7, column8, column9,
            column10);
    table.setTableMenuButtonVisible(true);

    ScrollPane sp = new ScrollPane(table);
    //sp.setContent(table);
    sp.setPrefSize(600, 200);
    sp.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
    sp.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
    sp.setFitToHeight(true);
    sp.setHmax(3);
    sp.setHvalue(0);
    sp.setDisable(false);

    layout.setRight(sp);
    BorderPane.setMargin(sp, new Insets(0, 10, 10, 10));

    Button load = new Button("Load Table");
    load.setFont(Font.font("SanSerif", 15));
    load.setOnAction(e -> {
        refreshTable();
    });

    ComboBox comboBox = new ComboBox(options);
    comboBox.setMaxHeight(30);

    comboBox.setOnAction(e -> {

        try {
            String query = "select * from UserDatabase where FirstName = ?";
            pst = conn.prepareStatement(query);
            pst.setString(1, (String) comboBox.getSelectionModel().getSelectedItem());
            rs = pst.executeQuery();

            while (rs.next()) {
                id.setText(rs.getString("ID"));
                fn.setText(rs.getString("FirstName"));
                ln.setText(rs.getString("LastName"));
                em.setText(rs.getString("Email"));
                mobile.setText(rs.getString("MobileNo"));
                un.setText(rs.getString("Username"));
                pw.setText(rs.getString("Password"));
                ((TextField) date.getEditor()).setText(rs.getString("DOB"));

                if ("Male".equals(rs.getString("Gender"))) {
                    male.setSelected(true);
                } else if ("Female".equals(rs.getString("Gender"))) {
                    female.setSelected(true);
                } else {
                    male.setSelected(false);
                    female.setSelected(false);
                }
            }
            pst.close();
            rs.close();
        } catch (SQLException ex) {
            Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
        }

    });

    Button delete = new Button("Delete User");
    delete.setFont(Font.font("SanSerif", 15));
    delete.setOnAction(e -> {
        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("Confirmation Dialog");
        alert.setHeaderText(null);
        alert.setContentText("Are you sure to delete?");
        Optional<ButtonType> action = alert.showAndWait();

        if (action.get() == ButtonType.OK) {
            try {
                String query = "delete from UserDatabase where id = ?";
                pst = conn.prepareStatement(query);
                pst.setString(1, id.getText());
                pst.executeUpdate();

                pst.close();
            } catch (SQLException ex) {
                Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        clearFields();
        fillComboBox();
        refreshTable();

    });

    exportToXL = new Button("Export To Excel");
    exportToXL.setFont(Font.font("Sanserif", 15));
    exportToXL.setOnAction(e -> {
        try {
            String query = "Select * from UserDatabase";
            pst = conn.prepareStatement(query);
            rs = pst.executeQuery();

            //Apache POI Jar Link-
            //http://a.mbbsindia.com/poi/release/bin/poi-bin-3.13-20150929.zip
            XSSFWorkbook wb = new XSSFWorkbook();//for earlier version use HSSF
            XSSFSheet sheet = wb.createSheet("User Details");
            XSSFRow header = sheet.createRow(0);
            header.createCell(0).setCellValue("ID");
            header.createCell(1).setCellValue("First Name");
            header.createCell(2).setCellValue("Last Name");
            header.createCell(3).setCellValue("Email");

            sheet.autoSizeColumn(1);
            sheet.autoSizeColumn(2);
            sheet.setColumnWidth(3, 256 * 25);//256-character width

            sheet.setZoom(150);//scale-150% 

            int index = 1;
            while (rs.next()) {
                XSSFRow row = sheet.createRow(index);
                row.createCell(0).setCellValue(rs.getString("ID"));
                row.createCell(1).setCellValue(rs.getString("FirstName"));
                row.createCell(2).setCellValue(rs.getString("LastName"));
                row.createCell(3).setCellValue(rs.getString("Email"));
                index++;
            }

            FileOutputStream fileOut = new FileOutputStream("UserDetails.xlsx");// befor 2007 version xls
            wb.write(fileOut);
            fileOut.close();

            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Information Dialog");
            alert.setHeaderText(null);
            alert.setContentText("User Details Exported in Excel Sheet.");
            alert.showAndWait();

            pst.close();
            rs.close();

        } catch (SQLException | FileNotFoundException ex) {
            Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
        }

    });

    importXLToDB = new Button("Import XL TO DB");
    importXLToDB.setFont(Font.font("Sanserif", 15));
    importXLToDB.setOnAction(e -> {
        try {
            String query = "Insert into UserDatabase(ID, FirstName, LastName, Email) values (?,?,?,?)";
            pst = conn.prepareStatement(query);

            FileInputStream fileIn = new FileInputStream(new File("UserInfo.xlsx"));

            XSSFWorkbook wb = new XSSFWorkbook(fileIn);
            XSSFSheet sheet = wb.getSheetAt(0);
            Row row;
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                row = sheet.getRow(i);
                pst.setInt(1, (int) row.getCell(0).getNumericCellValue());
                pst.setString(2, row.getCell(1).getStringCellValue());
                pst.setString(3, row.getCell(2).getStringCellValue());
                pst.setString(4, row.getCell(3).getStringCellValue());
                pst.execute();
            }
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Information Dialog");
            alert.setHeaderText(null);
            alert.setContentText("User Details Imported From Excel Sheet To Database.");
            alert.showAndWait();

            wb.close();
            fileIn.close();
            pst.close();
            rs.close();
        } catch (SQLException | FileNotFoundException ex) {
            Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
        }
        refreshTable();
    });

    HBox hbox = new HBox(5);
    hbox.getChildren().addAll(load, delete, update, comboBox, exportToXL, importXLToDB);

    layout.setBottom(hbox);
    BorderPane.setMargin(hbox, new Insets(10, 0, 10, 10));

    ListView list = new ListView(options);
    list.setMaxSize(100, 250);
    //layout.setLeft(list);
    //BorderPane.setMargin(list, new Insets(10));

    table.setOnMouseClicked(e -> {
        try {
            User user = (User) table.getSelectionModel().getSelectedItem();

            String query = "select * from UserDatabase where ID = ?";
            pst = conn.prepareStatement(query);
            pst.setString(1, user.getID());
            rs = pst.executeQuery();

            while (rs.next()) {
                id.setText(rs.getString("ID"));
                fn.setText(rs.getString("FirstName"));
                ln.setText(rs.getString("LastName"));
                em.setText(rs.getString("Email"));
                mobile.setText(rs.getString("MobileNo"));
                un.setText(rs.getString("Username"));
                pw.setText(rs.getString("Password"));
                ((TextField) date.getEditor()).setText(rs.getString("DOB"));

                if (null != rs.getString("Gender"))
                    switch (rs.getString("Gender")) {
                    case "Male":
                        male.setSelected(true);
                        break;
                    case "Female":
                        female.setSelected(true);
                        break;
                    default:
                        male.setSelected(false);
                        female.setSelected(false);
                        break;
                    }
                else {
                    male.setSelected(false);
                    female.setSelected(false);
                }

                // Retrive Hobbies Into CheckBox

                if (rs.getString("Hobbies") != null) {
                    checkBox1.setSelected(false);
                    checkBox2.setSelected(false);
                    checkBox3.setSelected(false);

                    //hobbies in the string formate - [Playing , Dancing]
                    System.out.println(rs.getString("Hobbies"));

                    String checkBoxString = rs.getString("Hobbies").replace("[", "").replace("]", "");
                    System.out.println(checkBoxString);

                    //now can converert to a list, strip out commas and spaces
                    List<String> hobbylist = Arrays.asList(checkBoxString.split("\\s*,\\s*"));
                    System.out.println(hobbylist);

                    for (String hobby : hobbylist) {
                        switch (hobby) {
                        case "Playing":
                            checkBox1.setSelected(true);
                            break;
                        case "Singing":
                            checkBox2.setSelected(true);
                            break;
                        case "Dancing":
                            checkBox3.setSelected(true);
                            break;
                        default:
                            checkBox1.setSelected(false);
                            checkBox2.setSelected(false);
                            checkBox3.setSelected(false);
                        }
                    }
                } else {
                    checkBox1.setSelected(false);
                    checkBox2.setSelected(false);
                    checkBox3.setSelected(false);
                }

                InputStream is = rs.getBinaryStream("Image");
                OutputStream os = new FileOutputStream(new File("photo.jpg"));
                byte[] content = new byte[1024];
                int size = 0;
                while ((size = is.read(content)) != -1) {
                    os.write(content, 0, size);
                }
                os.close();
                is.close();

                image = new Image("file:photo.jpg", 100, 150, true, true);
                ImageView imageView1 = new ImageView(image);
                imageView1.setFitWidth(100);
                imageView1.setFitHeight(150);
                imageView1.setPreserveRatio(true);

                layout.setCenter(imageView1);
                BorderPane.setAlignment(imageView1, Pos.TOP_LEFT);
            }
            pst.close();
            rs.close();
        } catch (SQLException ex) {
            Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    table.setOnKeyReleased(e -> {
        if (e.getCode() == KeyCode.UP || e.getCode() == KeyCode.DOWN) {
            try {
                User user = (User) table.getSelectionModel().getSelectedItem();

                String query = "select * from UserDatabase where ID = ?";
                pst = conn.prepareStatement(query);
                pst.setString(1, user.getID());
                rs = pst.executeQuery();

                while (rs.next()) {
                    id.setText(rs.getString("ID"));
                    fn.setText(rs.getString("FirstName"));
                    ln.setText(rs.getString("LastName"));
                    em.setText(rs.getString("Email"));
                    mobile.setText(rs.getString("MobileNo"));
                    un.setText(rs.getString("Username"));
                    pw.setText(rs.getString("Password"));
                    ((TextField) date.getEditor()).setText(rs.getString("DOB"));

                    if (null != rs.getString("Gender"))
                        switch (rs.getString("Gender")) {
                        case "Male":
                            male.setSelected(true);
                            break;
                        case "Female":
                            female.setSelected(true);
                            break;
                        default:
                            male.setSelected(false);
                            female.setSelected(false);
                            break;
                        }
                    else {
                        male.setSelected(false);
                        female.setSelected(false);
                    }

                    // Retrive Hobbies Into CheckBox

                    if (rs.getString("Hobbies") != null) {
                        checkBox1.setSelected(false);
                        checkBox2.setSelected(false);
                        checkBox3.setSelected(false);

                        //hobbies in the string formate - [Playing , Dancing]
                        System.out.println(rs.getString("Hobbies"));

                        String checkBoxString = rs.getString("Hobbies").replace("[", "").replace("]", "");
                        System.out.println(checkBoxString);

                        //now can converert to a list, strip out commas and spaces
                        List<String> hobbylist = Arrays.asList(checkBoxString.split("\\s*,\\s*"));
                        System.out.println(hobbylist);

                        for (String hobby : hobbylist) {
                            switch (hobby) {
                            case "Playing":
                                checkBox1.setSelected(true);
                                break;
                            case "Singing":
                                checkBox2.setSelected(true);
                                break;
                            case "Dancing":
                                checkBox3.setSelected(true);
                                break;
                            default:
                                checkBox1.setSelected(false);
                                checkBox2.setSelected(false);
                                checkBox3.setSelected(false);
                            }
                        }
                    } else {
                        checkBox1.setSelected(false);
                        checkBox2.setSelected(false);
                        checkBox3.setSelected(false);
                    }

                    InputStream is = rs.getBinaryStream("Image");
                    OutputStream os = new FileOutputStream(new File("photo.jpg"));
                    byte[] content = new byte[1024];
                    int size = 0;
                    while ((size = is.read(content)) != -1) {
                        os.write(content, 0, size);
                    }
                    os.close();
                    is.close();

                    image = new Image("file:photo.jpg", 100, 150, true, true);
                    ImageView imageView1 = new ImageView(image);
                    imageView1.setFitWidth(100);
                    imageView1.setFitHeight(150);
                    imageView1.setPreserveRatio(true);

                    layout.setCenter(imageView1);
                    BorderPane.setAlignment(imageView1, Pos.TOP_LEFT);
                }
                pst.close();
                rs.close();
            } catch (SQLException ex) {
                Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(UserInfoApp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    FilteredList<User> filteredData = new FilteredList<>(data, e -> true);
    searchField.setOnKeyReleased(e -> {
        searchField.textProperty().addListener((observableValue, oldValue, newValue) -> {
            filteredData.setPredicate((Predicate<? super User>) user -> {
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }
                String lowerCaseFilter = newValue.toLowerCase();
                if (user.getID().contains(newValue)) {
                    return true;
                } else if (user.getFirstName().toLowerCase().contains(lowerCaseFilter)) {
                    return true;
                } else if (user.getLastName().toLowerCase().contains(lowerCaseFilter)) {
                    return true;
                }
                return false;
            });
        });
        SortedList<User> sortedData = new SortedList<>(filteredData);
        sortedData.comparatorProperty().bind(table.comparatorProperty());
        table.setItems(sortedData);

    });
    primaryStage.setScene(scene);
    primaryStage.show();
}

From source file:org.wise.vle.web.VLEGetXLS.java

License:Open Source License

/**
 * Auto sizes the columns specified so that the text in those columns
 * are completely shown and do not need to be resized to be able to
 * be read. This will only auto size the first n number of columns.
 * /* www .jav  a 2s  .  c o  m*/
 * @param sheet the sheet to auto size columns in
 * @param numColumns the number of columns to auto size
 */
@SuppressWarnings("unused")
private void autoSizeColumns(XSSFSheet sheet, int numColumns) {
    //this property needs to be set to true in order for auto sizing to work
    System.setProperty("java.awt.headless", "true");

    //loop through the specified number of columns
    for (int x = 0; x < numColumns; x++) {
        //auto size the column
        sheet.autoSizeColumn(x);
    }

    //set this property back to false
    System.setProperty("java.awt.headless", "false");
}

From source file:punchcardrecords.ui.PunchCardRecordsMainFrame.java

License:Open Source License

/**
 * Excel//from   www. j  a  va  2 s.c  o  m
 * @param year 
 */
private void writeYearCountResult(Map<String, double[]> yearRecords, String path) {
    XSSFWorkbook resultWorkBook = new XSSFWorkbook();
    XSSFSheet sheet = resultWorkBook.createSheet();
    Set<String> userNumNames = yearRecords.keySet();
    // 
    String[] titles = { "?", "??", "()", "(?)",
            "?(?)" };
    int col = 0;// 
    XSSFRow titleRow = sheet.createRow(0);
    for (String title : titles) {
        titleRow.createCell(col).setCellValue(title);
        sheet.autoSizeColumn((short) (col));
        col++;
    }
    int row = 1;// 
    // 
    for (String userStr : userNumNames) {
        XSSFRow recordRow = sheet.createRow(row);
        int innerCol = 0;// ?
        // ?
        String[] userInfos = userStr.split(":");
        for (String userInfo : userInfos) {
            recordRow.createCell(innerCol).setCellValue(userInfo);
            innerCol++;
        }
        // 
        double[] records = yearRecords.get(userStr);
        for (double record : records) {
            recordRow.createCell(innerCol).setCellValue(record);
            innerCol++;
        }
        // ?
        recordRow.createCell(innerCol)
                .setCellValue(new BigDecimal(records[0] == 0 ? 0 : records[1] / records[0])
                        .setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
        row++;
    }

    // ???,??
    JFileChooser fileSaveChooser = new JFileChooser();

    fileSaveChooser.setDialogTitle("?");
    fileSaveChooser.setSelectedFile(new File(path + "/.xlsx"));
    String[] saveType = { "xlsx" };
    fileSaveChooser.setAcceptAllFileFilterUsed(false);
    fileSaveChooser.setFileFilter(new FileNameExtensionFilter("*.xlsx", saveType));
    int saveResult = fileSaveChooser.showSaveDialog(this);
    if (saveResult == JFileChooser.APPROVE_OPTION) {
        File saveFile = fileSaveChooser.getSelectedFile();

        // ???
        String saveFilePath = saveFile.getAbsolutePath();
        addMessage("?,??->" + saveFilePath);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(saveFile);
            resultWorkBook.write(out);
            out.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PunchCardRecordsMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PunchCardRecordsMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(PunchCardRecordsMainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        Object[] options = { "", "", ",?" };
        int response = JOptionPane.showOptionDialog(this,
                "??,???", "?", JOptionPane.YES_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (0 == response) {// 
            // ??
            addMessage(",??");
            try {
                Desktop.getDesktop().open(saveFile);
            } catch (IOException ex) {
                Logger.getLogger(PunchCardRecordsMainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (1 == response) {// 
            addMessage(",??");
            String[] cmd = new String[5];
            cmd[0] = "cmd";
            cmd[1] = "/c";
            cmd[2] = "start";
            cmd[3] = " ";
            cmd[4] = saveFile.getAbsolutePath().substring(0, saveFile.getAbsolutePath().lastIndexOf("\\"));
            try {
                Runtime.getRuntime().exec(cmd);
            } catch (IOException ex) {
                Logger.getLogger(PunchCardRecordsMainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            alert("??,?()");
        }
    } else {
        // ??,?
        clearMessage();
        fileName.setText("");
        // ???
        addMessage("??");
    }
}

From source file:reports.allStaticReportsdynamic.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String monthrange = "";
    String periodlabel = "";
    String period = "Month"; //The default one
    String periodicgroupby = " "; //note that in the current query there is  an existing group by. Therefore this will be an extra infor to be added on the existing group by
    String isgroupby = "yes";
    try {//from www.  j av  a2  s  .co  m
        response.setContentType("text/html;charset=UTF-8");

        //a page to get Report of all the servlets
        String months[] = null;

        String year = "2015";
        String month = "";
        String county = "";
        String form = "moh731";

        if (request.getParameter("year") != null) {
            year = request.getParameter("year");
        }

        if (request.getParameter("county") != null) {
            county = request.getParameter("county");
        }

        if (request.getParameter("month") != null) {
            months = request.getParameterValues("month");
        }

        if (request.getParameter("form") != null) {
            form = request.getParameter("form");
        }
        if (request.getParameter("groupby") != null) {
            isgroupby = request.getParameter("groupby");
        }

        String pivotform = form;
        if (form.equalsIgnoreCase("MOH 731")) {
            form = "MOH731";
        }
        if (form.equalsIgnoreCase("MOH 711A")) {
            form = "MOH711";
        }
        if (form.equalsIgnoreCase("MOH 711 (New)")) {
            form = "moh711_new";
        }
        String facilitywhere = "";
        String yearwhere = "";
        String monthwhere = "";
        String countywhere = "";
        String districtwhere = "";
        String reporttype = "";
        String subcounty_countywhere = "";
        String indicatorslist = "all";

        String sections = "all";
        String subsections = "all";

        String indicatorswhere = "";

        //________________________________________________________________________________________________________________________________________________________            
        //________________________________________________________________________________________________________________________________________________________
        String duration = "";
        String semi_annual = "";
        String quarter = "";

        //==================================================================================================
        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        String facil = "361";

        String yearmonthstart = "";
        String yearmonthend = "";
        //=====================================================================================================

        String header = "";

        String reportType = "";

        dbConn conn = new dbConn();

        if (request.getParameter("reportType") != null) {
            reportType = request.getParameter("reportType");
        }
        if (request.getParameter("indicators") != null) {
            indicatorslist = request.getParameter("indicators");
        }

        //--------------------------sections------------
        String sectionid[] = null;

        if (request.getParameterValues("sections") != null) {
            sectionid = request.getParameterValues("sections");
        }

        String sectionvals = "(";

        if (request.getParameterValues("sections") != null) {
            for (int a = 0; a < sectionid.length; a++) {
                if (a == sectionid.length - 1) {
                    sectionvals += sectionid[a] + "";
                } else {
                    sectionvals += sectionid[a] + ",";
                }
            }
        }
        sectionvals += ")";

        if (sectionvals.equals("()")) {
            indicatorswhere += " ";
        } else {

            indicatorswhere += " and sectionid in " + sectionvals + " ";

        }

        //______________________________________________________subsections_______________________________________

        String subsectionid[] = null;

        if (request.getParameterValues("subsection") != null) {
            subsectionid = request.getParameterValues("subsection");
        }

        String subsectionvals = "(";
        if (request.getParameterValues("subsection") != null) {
            for (int a = 0; a < subsectionid.length; a++) {
                if (a == subsectionid.length - 1) {
                    subsectionvals += subsectionid[a] + "";
                } else {
                    subsectionvals += subsectionid[a] + ",";
                }
            }
        }
        subsectionvals += ")";

        if (subsectionvals.equals("()")) {
            indicatorswhere += " ";
        } else {

            indicatorswhere += " and subsectionid in " + subsectionvals + " ";

        }

        //______________________________________________________subsections_______________________________________

        //add sections
        //special indicators

        if (indicatorslist.equals("special")) {

            indicatorswhere += " and specialindicator='1'";

        }

        String reportDuration = "";

        if (request.getParameter("reportDuration") != null) {
            reportDuration = request.getParameter("reportDuration");
        }

        if (request.getParameter("facility") != null && reportType.equals("2")) {
            try {
                facil = request.getParameter("facility");

                String getfacil = "select SubPartnerNom,CentreSanteId as mflcode from subpartnera where SubPartnerID='"
                        + facil + "'";
                conn.rs = conn.st.executeQuery(getfacil);

                while (conn.rs.next()) {

                    header += " FACILITY : " + conn.rs.getString(1).toUpperCase() + "     MFL CODE  :  "
                            + conn.rs.getString(2) + "  ";

                }
            } catch (SQLException ex) {
                Logger.getLogger(allStaticReportsdynamic.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        if (request.getParameter("county") != null && reportType.equals("2")) {
            try {
                county = request.getParameter("county");
                subcounty_countywhere = " (county.CountyID='" + county + "') and ";//20160711   
                String getcounty = "select County from county where CountyID='" + county + "'";
                conn.rs = conn.st.executeQuery(getcounty);

                while (conn.rs.next()) {

                    header += " COUNTY : " + conn.rs.getString(1).toUpperCase() + " ";

                }
            } catch (SQLException ex) {
                Logger.getLogger(allStaticReportsdynamic.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        int yearcopy = Integer.parseInt(year);
        String yearmonth = "" + year;
        int prevYear = yearcopy - 1;
        int maxYearMonth = 0;
        int monthcopy = 0;

        String currentperiodlabel = "";//a variable to hold the name of a period inside a conn.rs if .

        header += " YEAR : " + year + "";

        //        GET REPORT DURATION============================================
        //annually
        //____________________________________________________________________________________________________________Annual____________________________________
        if (reportDuration.equals("1")) {

            yearmonth = "Annual Report For " + year;
            duration = " and " + form + ".yearmonth BETWEEN '" + prevYear + "10' AND '" + year + "09'";

            period = "Year";

            periodicgroupby = ", period ";
            monthrange = year;

            // tbstatduration="year='"+year+"'";
        }
        //____________________________________________________________________________________________________________Semi_annual_____________________________          
        else if (reportDuration.equals("2")) {

            period = "Semi-Annual";

            periodicgroupby = ", period  ";

            try {
                String startMonth = "", endMonth = "";
                String semiannualarray[] = request.getParameterValues("semi_annual");

                String temporaryheader = " SEMI-ANNUAL";

                for (int p = 0; p < semiannualarray.length; p++) {

                    semi_annual = semiannualarray[p];

                    String getperiodname = "SELECT name as semiannual_name,months FROM semi_annual WHERE id='"
                            + semi_annual + "'";
                    conn.rs = conn.st.executeQuery(getperiodname);

                    if (conn.rs.next() == true) {

                        String monthsinsemiannual[] = conn.rs.getString("months").split(",");
                        currentperiodlabel = conn.rs.getString("semiannual_name");

                        //_________________add year at the end of period label                  
                        if (semi_annual.equals("1")) {
                            //periodname is in format oct-Mar we will make it to be in format Oct 2015-Mar 2016

                            currentperiodlabel = conn.rs.getString("semiannual_name").replace("-",
                                    " " + prevYear + "-") + " " + year;

                        } else {
                            //periodname is in format Apr-Sep we will make it to be in format Apr-Sep 2016      
                            currentperiodlabel = conn.rs.getString("semiannual_name") + " " + year;

                        }
                        //____________________   

                        if (p == 0) {

                            startMonth = monthsinsemiannual[0];

                            endMonth = monthsinsemiannual[5];

                            monthrange = currentperiodlabel;

                        }
                        if (p == semiannualarray.length - 1 && semiannualarray.length > 1) {
                            //last row

                            monthrange += " to " + currentperiodlabel;

                            //by now we expect monthrange to be something like Oct-Mar-Apr-Sep

                            endMonth = monthsinsemiannual[5];

                        }

                        if (periodlabel.equals("")) {
                            periodlabel = conn.rs.getString("semiannual_name");
                        }

                        else {

                            periodlabel += "_" + conn.rs.getString("semiannual_name");

                        }
                    } //end of conn.
                      //get the yearmonthstart date

                    if (p == 0 && semiannualarray.length > 1) {
                        //if the quarters selected are several
                        //this is the starting quarter                                  
                        temporaryheader += "S " + currentperiodlabel + " To ";

                        if (new Integer(semi_annual) == 1) {
                            //the year will be deducted by one if the selected months are 10, 11, 12
                            yearmonthstart = " " + form + ".yearmonth  between '" + prevYear + "" + startMonth
                                    + "' and ";

                        } else {

                            yearmonthstart = " " + form + ".yearmonth  between '" + year + "" + startMonth
                                    + "' and ";

                        }

                    }

                    else if (p == semiannualarray.length - 1 && semiannualarray.length > 1) {
                        //the last month 
                        temporaryheader += currentperiodlabel; //by now we expct something like from Semi-annuals oct-Mar to Apr -Sep
                        //this assumes that the last month can never be 
                        yearmonthend = "'" + year + "" + endMonth + "'";

                    }

                    else if (p == 0 && semiannualarray.length == 1) {
                        // the number of quarters selected is one   
                        temporaryheader += " " + currentperiodlabel + " ";

                        if (new Integer(semi_annual) == 1) {

                            yearmonthstart = " " + form + ".yearmonth between '" + prevYear + startMonth
                                    + "' and";

                        } else {

                            yearmonthstart = " " + form + ".yearmonth between '" + year + "" + startMonth
                                    + "' and ";

                        }
                        yearmonthend = "'" + year + "" + endMonth + "'"; //this assumes no end month date can come in oct-dec ..all the year month ends come on mar or sep

                    } //end of last monthly row

                } //end of for loop

                header += " " + temporaryheader + "";

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

            if (!semi_annual.equals("")) {

                duration = " and " + yearmonthstart + "" + yearmonthend;

            }

        }

        // ____________________________________________________________________________________________________Quarterly____________________

        else if (reportDuration.equals("3")) {
            period = "Quarter";

            periodicgroupby = ", period ";

            try {
                String startMonth = "", endMonth = "";
                String quarterarray[] = request.getParameterValues("quarter");

                String temporaryheader = " QUARTER";

                for (int p = 0; p < quarterarray.length; p++) {

                    quarter = quarterarray[p];

                    String getMonth = "SELECT months,name as qtrname FROM quarter WHERE id='" + quarter + "'";
                    conn.rs = conn.st.executeQuery(getMonth);

                    if (conn.rs.next() == true) {

                        String monthsinqtr[] = conn.rs.getString(1).split(",");

                        //_________________add year at the end of period label                  
                        if (quarter.equals("1")) {
                            //periodname is in format oct-Mar we will make it to be in format Oct 2015-Mar 2016
                            currentperiodlabel = conn.rs.getString("qtrname").replace("-", " " + prevYear + "-")
                                    + " " + year;

                        } else {
                            //periodname is in format Apr-Sep we will make it to be in format Apr-Sep 2016      
                            currentperiodlabel = conn.rs.getString("qtrname") + " " + year;

                        }
                        //____________________

                        if (p == 0) {

                            startMonth = monthsinqtr[0];

                            monthrange = conn.rs.getString("qtrname");

                            endMonth = monthsinqtr[2];
                        }
                        if (p == quarterarray.length - 1 && quarterarray.length > 1) {
                            //last row
                            monthrange += " to " + conn.rs.getString("qtrname");

                            endMonth = monthsinqtr[2];

                        }

                        if (periodlabel.equals(""))// note period label gets all the periods in my loop 
                        {
                            periodlabel = conn.rs.getString("qtrname");
                        }

                        else {

                            periodlabel += "_" + conn.rs.getString("qtrname");

                        }
                    } //end of if
                      //get the yearmonthstart date

                    if (p == 0 && quarterarray.length > 1) {
                        //if the quarters selected are several
                        //this is the starting quarter                                  
                        temporaryheader += "S " + currentperiodlabel + " To ";

                        if (new Integer(quarter) == 1) {
                            //the year will be deducted by one if the selected months are 10, 11, 12
                            yearmonthstart = " " + form + ".yearmonth  between '" + prevYear + "" + startMonth
                                    + "' and";

                        } else {

                            yearmonthstart = " " + form + ".yearmonth  between '" + year + "" + startMonth
                                    + "' and";

                        }

                    } else if (p == quarterarray.length - 1 && quarterarray.length > 1) {
                        //the last month 
                        temporaryheader += currentperiodlabel; //by now we expct something like from Quarters oct-Dec to Jan -Mar

                        yearmonthend = "'" + year + "" + endMonth + "'";

                    } else if (p == 0 && quarterarray.length == 1) {
                        // the number of quarters selected is one   
                        temporaryheader += " " + currentperiodlabel + " ";

                        if (new Integer(quarter) == 1) {

                            yearmonthstart = " " + form + ".yearmonth between '" + prevYear + startMonth
                                    + "' and ";

                            yearmonthend = " '" + prevYear + "" + endMonth + "' ";
                        } else {

                            yearmonthstart = " " + form + ".yearmonth between '" + year + "" + startMonth
                                    + "' and ";

                            yearmonthend = " '" + year + "" + endMonth + "' ";
                        }

                    } //end of last monthly row

                } //end of for loop

                header += " " + temporaryheader + "";

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

            if (!quarter.equals("")) {

                duration = " and " + yearmonthstart + "" + yearmonthend;

            }

        }

        //_______________________________________________________________________________________________________________monthly______________________________       
        else if (reportDuration.equals("4")) {

            period = "Month";

            periodicgroupby = ", period ";

            try {

                months = request.getParameterValues("month");

                String temporaryheader = " MONTH";

                for (int u = 0; u < months.length; u++) {

                    month = months[u];

                    String getMonth = "SELECT name FROM month WHERE id='" + month + "'";
                    conn.rs = conn.st.executeQuery(getMonth);

                    if (conn.rs.next() == true) {

                        //_________________add year at the end of period label                  
                        if (new Integer(month) >= 10 && new Integer(month) <= 12) {
                            //periodname is in format oct-Mar we will make it to be in format Oct 2015-Mar 2016
                            currentperiodlabel = conn.rs.getString("name").substring(0, 3) + " " + prevYear;

                        } else {
                            //periodname is in format Apr-Sep we will make it to be in format Apr-Sep 2016      
                            currentperiodlabel = conn.rs.getString("name").substring(0, 3) + " " + year;

                        }
                        //____________________    

                        if (u == 0) {
                            monthrange = conn.rs.getString(1);
                        }
                        if (u == months.length - 1 && months.length > 1) {
                            monthrange += " to " + conn.rs.getString(1);
                        }

                        if (periodlabel.equals("")) {
                            periodlabel = conn.rs.getString("name");
                        } else {
                            periodlabel += "_" + conn.rs.getString("name");
                        }
                    }
                    //get the yearmonthstart date

                    if (u == 0 && months.length > 1) {
                        //if the month selected are several
                        //this is the starting month                                  
                        temporaryheader += "S " + currentperiodlabel + " To ";

                        if (new Integer(month) >= 10) {

                            //the year will be deducted by one if the selected months are 10, 11, 12
                            yearmonthstart = " " + form + ".yearmonth  between '" + prevYear + "" + month
                                    + "' and ";

                        } else {
                            yearmonthstart = " " + form + ".yearmonth  between '" + year + "0" + month
                                    + "' and ";

                        }

                    } else if (u == months.length - 1 && months.length > 1) {
                        //the last month 

                        if (new Integer(month) >= 10) {

                            yearmonthend = "'" + prevYear + month + "'";

                        } else {

                            yearmonthend = "'" + year + "0" + month + "'";

                        }

                    } else if (u == 0 && months.length == 1) {
                        // the number of months selected is one   
                        temporaryheader += " " + currentperiodlabel + " ";

                        if (new Integer(month) >= 10) {

                            yearmonthstart = " " + form + ".yearmonth = " + prevYear + month;

                        } else {

                            yearmonthstart = " " + form + ".yearmonth = " + year + "0" + month;

                        }
                        yearmonthend = "";

                    } //end of last monthly row

                } //end of for loop

                header += " " + temporaryheader + "";

            } catch (SQLException ex) {
                Logger.getLogger(allStaticReportsdynamic.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (!month.equals("")) {

                duration = " and " + yearmonthstart + "" + yearmonthend;

            }

        } //end of monthly records 

        else {
            duration = "";
        }

        //if someone doest want periodic grouping, then dont add a group by in the report.. get numbers for all rows. 

        if (isgroupby.equals("No")) {

            periodicgroupby = "";

        }

        //______________________________________________________________________________________COUNTY , SUBCOUNTY AND 

        String subcountywhere = "";

        String subcounty = "";

        if (reportType.equalsIgnoreCase("2")) { //get data per county if the selected

            if (!request.getParameter("subcounty").equals("")) {

                subcounty = request.getParameter("subcounty");
                subcounty_countywhere = " (district.DistrictID='" + subcounty + "') and ";
            }

            if (!request.getParameter("county").equals("")) {
                county = request.getParameter("county");
                subcounty_countywhere = " (district.countyid='" + request.getParameter("county") + "') and ";//20160711 
            }

            if (!county.equals("")) {

                countywhere = " and district.countyid = '" + county + "'";

            }

            if (!subcounty.equals("")) {

                subcountywhere = " and subpartnera.DistrictID = '" + subcounty + "'";

            }

            if (!facil.equals("") && reportType.equalsIgnoreCase("2")) {

                facilitywhere = " and " + form + ".SubPartnerID = '" + facil + "'";

            }

        }

        String joinedwhwere = " where 1=1 " + duration + " " + countywhere + " " + subcountywhere + " "
                + facilitywhere;

        // System.out.println(""+joinedwhwere);
        //we need a case statement in our main query. This will allow for friendly display of 

        String myperiodcase = "";

        if (isgroupby.equals("No")) {

            myperiodcase = "'" + monthrange + "' as period";

        }

        else {

            if (period.equalsIgnoreCase("Year")) {

                myperiodcase = " case when Annee !='' then Annee else 'no year' end as period ";

            } else if (period.equalsIgnoreCase("Semi-Annual")) {

                myperiodcase = " case when (SUBSTRING(Yearmonth,5,6) >=01 and SUBSTRING(Yearmonth,5,6) <=03) || (SUBSTRING(Yearmonth,5,6) >=10 and SUBSTRING(Yearmonth,5,6) <=12) then 'Oct-Mar' "
                        + "when SUBSTRING(Yearmonth,5,6) >=04 and SUBSTRING(Yearmonth,5,6) <=09 then 'Apr-Sep' else 'No period' end as period ";
            } else if (period.equalsIgnoreCase("Quarter")) {

                myperiodcase = " case when (SUBSTRING(Yearmonth,5,6) >=01 and SUBSTRING(Yearmonth,5,6) <=03) then 'Jan-Mar'"
                        + "when  (SUBSTRING(Yearmonth,5,6) >=10 and SUBSTRING(Yearmonth,5,6) <=12) then 'Oct-Dec' "
                        + "when SUBSTRING(Yearmonth,5,6) >=04 and SUBSTRING(Yearmonth,5,6) <=06 then 'Apr-Jun' "
                        + "when SUBSTRING(Yearmonth,5,6) >=07 and SUBSTRING(Yearmonth,5,6) <=09 then 'Jul-Sep' "
                        + "else 'No period' end as period  ";
            } else if (period.equalsIgnoreCase("Month")) {

                myperiodcase = " case " + " when SUBSTRING(Yearmonth,5,6)= '01' then 'Jan' "
                        + " when SUBSTRING(Yearmonth,5,6)= '02' then 'Feb' "
                        + " when SUBSTRING(Yearmonth,5,6)= '03' then 'Mar' "
                        + " when SUBSTRING(Yearmonth,5,6)= '04' then 'Apr' "
                        + " when SUBSTRING(Yearmonth,5,6)= '05' then 'May' "
                        + " when SUBSTRING(Yearmonth,5,6)= '06' then 'Jun' "
                        + " when SUBSTRING(Yearmonth,5,6)= '07' then 'Jul' "
                        + " when SUBSTRING(Yearmonth,5,6)= '08' then 'Aug' "
                        + " when SUBSTRING(Yearmonth,5,6)= '09' then 'Sep' "
                        + " when SUBSTRING(Yearmonth,5,6)= '10' then 'Oct' "
                        + " when SUBSTRING(Yearmonth,5,6)= '11' then 'Nov' "
                        + " when SUBSTRING(Yearmonth,5,6)= '12' then 'Dec' "
                        + " else 'No period' end as period ";

            }

        }

        //_________________________________________________________________END OF FILTERING SECTION_______________________________________________________________            
        //________________________________________________________________________________________________________________________________________________________            
        //an array to store haeder information.
        //the header information should appear only if certain parameters are met
        //The parameters listed in here can be removed if the report type doesnt require some parameters
        ArrayList Headerorgunits = new ArrayList();
        Headerorgunits.add(period);
        Headerorgunits.add("County");
        Headerorgunits.add("Sub-County");
        Headerorgunits.add("Facility");
        Headerorgunits.add("MFL Code");
        //An arralist to store a list of columns that will be selected from the database
        ArrayList dbcolumns = new ArrayList();

        ArrayList labels = new ArrayList();

        ArrayList tablename = new ArrayList();

        ArrayList iscumulative = new ArrayList();

        ArrayList ispercent = new ArrayList();

        // ArrayList isactive=new ArrayList();
        //An arralist to store a list of worksheets that will be selected from the sections and the respective service area to determine the facilities whose data will appear in that sheet
        ArrayList worksheets = new ArrayList();
        //An arralist to store distinct worksheets. This will be derived from the the sections column
        ArrayList distinctsheets = new ArrayList();
        ArrayList distinctservicearea = new ArrayList();

        //create an array to store the number of row for each excel worksheet. 
        //This will help in retrieving the number of rows for each month since we are wring data for different months with increasing rows.
        //the size of that array will be determined by the number of excel worksheets
        String selectdistinctworksheet = "select section,servicearea from pivottable where form='"
                + form.replace("_", "") + "' and active='1' " + indicatorswhere
                + " group by section order by order_per_form";

        conn.rs = conn.st.executeQuery(selectdistinctworksheet);

        while (conn.rs.next()) {
            //add the name of distinct sections
            distinctsheets.add(conn.rs.getString(1).replace("/", "_"));

            String servicearea = "  2=2 ";
            if (conn.rs.getString(2) != null) {
                servicearea = "  " + conn.rs.getString(2) + "=1";
            }
            distinctservicearea.add(servicearea);

        }

        int rowstartpersheet[] = new int[distinctsheets.size()];

        //initialize the row start position for each workshett with 2
        for (int x = 0; x < rowstartpersheet.length; x++) {

            rowstartpersheet[x] = 2;

        }

        String getattribs = "select indicator,label,section,cumulative,percentage,active ,shortlabel from pivottable where form='"
                + form.replace("_", "") + "' " + indicatorswhere + " order by order_per_form, section";
        conn.rs = conn.st.executeQuery(getattribs);

        while (conn.rs.next()) {

            //add active indicators only
            if (conn.rs.getString("active").equals("1")) {
                //System.out.println(conn.rs.getString("indicator")+"");
                //add indicator
                dbcolumns.add(conn.rs.getString("indicator"));
                //add label
                if (form.equalsIgnoreCase("MOH731")) {

                    labels.add(conn.rs.getString("shortlabel") + " \n" + conn.rs.getString("label"));

                } else {
                    labels.add(conn.rs.getString("label"));
                }
                //add worksheets
                worksheets.add(conn.rs.getString("section").replace("/", "_"));

                String perc = "0";
                String cum = "0";

                if (conn.rs.getString("cumulative") != null) {
                    iscumulative.add(conn.rs.getString("cumulative"));
                } else {
                    iscumulative.add(cum);
                }

                if (conn.rs.getString("percentage") != null) {
                    ispercent.add(conn.rs.getString("percentage"));
                } else {
                    ispercent.add(perc);
                }

            } //end of active 

        } //end of pivot table active
        //labels.add("ART High Volume");
        //labels.add("HTC High Volume");
        //labels.add("PMTCT High Volume");

        //System.out.println(perfacilselect);
        //______________________________________________________________________________________
        //                       CREATE THE WORKSHEETS          
        //______________________________________________________________________________________  
        XSSFWorkbook wb = new XSSFWorkbook();

        XSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        XSSFFont font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        XSSFCellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        XSSFCellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        XSSFCellStyle stylesum = wb.createCellStyle();
        stylesum.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylesum.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylesum.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylesum.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        XSSFFont fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        stylesum.setFont(fontx);
        stylesum.setWrapText(true);
        int cellrange[] = new int[4];

        for (int b = 0; b < distinctsheets.size(); b++) {

            XSSFSheet shet = wb.createSheet(distinctsheets.get(b).toString().toUpperCase());

            //Made my life veery simple...
            shet.setDisplayGridlines(false);
            shet.createFreezePane(5, 2);
            int firstcell = 1;

            //create headers for that worksheet
            XSSFRow rw = shet.createRow(1);
            int headercellpos = 0;
            //create the orgunit header eg MONTH | COUNTY | SUBCOUNTY  | FACILITY

            for (int e = 0; e < Headerorgunits.size(); e++) {
                XSSFCell cell0 = rw.createCell(headercellpos);
                cell0.setCellValue(Headerorgunits.get(e).toString());
                cell0.setCellStyle(stylex);

                headercellpos++;
                //shet.setColumnWidth(e, 6000);  

            }

            //create the indicators header eg HV0101 | HIV 09676  | TOTAL    
            for (int c = 0; c < dbcolumns.size(); c++) {
                //compare if the indicator belongs to the specified section and hence worksheet 
                //recall, each indicator has got an associated section / worksheet
                //An indicator should be put as an header in the respective worksheet
                if (worksheets.get(c).equals(distinctsheets.get(b))) {

                    shet.setColumnWidth(headercellpos, 6000);
                    XSSFCell cell0 = rw.createCell(headercellpos);
                    cell0.setCellValue(labels.get(c).toString());
                    cell0.setCellStyle(stylex);
                    headercellpos++;
                } //end of comparing if

            } //end of for loop

            //create is validated header
            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell0 = rw.createCell(headercellpos);
            cell0.setCellValue("ART High Volume");
            cell0.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell1 = rw.createCell(headercellpos);
            cell1.setCellValue("HTC High Volume");
            cell1.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell2 = rw.createCell(headercellpos);
            cell2.setCellValue("PMTCT High Volume");
            cell2.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell2a = rw.createCell(headercellpos);
            cell2a.setCellValue("GSN");
            cell2a.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell3 = rw.createCell(headercellpos);
            cell3.setCellValue("Form Validated ?");
            cell3.setCellStyle(stylex);
            headercellpos++;

        }

        //______________________________________________________________________________________
        //______________________________________________________________________________________
        //--------------------------------------------------------------------------------------------
        //             MONTH LOOPS
        //-------------------------------------------------------------------------------------------- 
        int cumulativestatingpoint = 3;
        boolean cumstartpointnoted = false;
        int colposcopy = 0;
        //for (int w = 0; w < months.length; w++) {

        String perfacilselect = "select " + myperiodcase
                + " , CONCAT(UPPER(SUBSTRING(County,1,1)),LOWER(SUBSTRING(County,2))) as County , DistrictNom as District , SubPartnerNom as facility ,CentreSanteId as mflcode ,  district.CountyID as countyid , ";

        //have a stringto get all distinct periods before execution of the main query. This will help in knowing the last
        String getdistinctperiod = "select " + myperiodcase;
        //--------------------------------------------------------------------------------------------
        //             PREPARE SELECT
        //--------------------------------------------------------------------------------------------
        //prepare selects
        for (int a = 0; a < dbcolumns.size(); a++) {

            //if the indicator is a percent, get an avaerage
            if (ispercent.get(a).equals("1")) {
                perfacilselect += "  AVG(" + dbcolumns.get(a) + ") as " + dbcolumns.get(a);

            } else if (iscumulative.get(a).equals("1")) {
                perfacilselect += "  SUBSTRING_INDEX(GROUP_CONCAT(CAST(IFNULL(" + dbcolumns.get(a)
                        + ",0) AS CHAR) ORDER BY yearmonth DESC),',',1) as " + dbcolumns.get(a);
                //SUBSTRING_INDEX(GROUP_CONCAT(CAST(IFNULL(HV0303,0) AS CHAR) ORDER BY yearmonth DESC),',',1)

            } else {
                perfacilselect += "  SUM(" + dbcolumns.get(a) + ") as " + dbcolumns.get(a);

            }

            //if the item is not the last, append a comma
            //if(a<dbcolumns.size()-1){
            perfacilselect += " ,";

            // } 
        }

        //---------------------------------add highvolume------------------------------------------------
        perfacilselect += " IFNULL(ART_highvolume,0) as ART_highvolume,  IFNULL(HTC_highvolume,0) as HTC_highvolume,  IFNULL(PMTCT_highvolume,0) as PMTCT_highvolume,  IFNULL(GSN,0) as GSN,";

        //-------------------------------------------------------------------------------------------------
        //     FROM  
        //------------------------------------------------------------------------------------  
        perfacilselect += "  isValidated as Form_Validated from " + form
                + "  join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on "
                + form + ".SubPartnerID = subpartnera.SubPartnerID ";

        getdistinctperiod += " from " + form
                + "  join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on "
                + form + ".SubPartnerID = subpartnera.SubPartnerID ";

        //------------------------------------------------------------------------------------------
        // WHERE 
        //------------------------------------------------------------------------------------------ 
        perfacilselect += joinedwhwere; //contains any filterings

        getdistinctperiod += joinedwhwere; //contains any filterings

        //-----------------------------------------------------------------------------------------
        //GROUP BY 
        //----------------------------------------------------------------------------------------

        perfacilselect += " group by subpartnera.SubPartnerID " + periodicgroupby + " order by yearmonth ";

        getdistinctperiod += " group by period order by yearmonth ";

        String lastperiod = "";
        ArrayList alldistinctperiods = new ArrayList();
        //System.out.println(""+getdistinctperiod);                

        conn.rs = conn.st.executeQuery(getdistinctperiod);

        while (conn.rs.next() == true) {
            lastperiod = conn.rs.getString(1); //here am asumming the last period will appear last and so will be mantained in the                
            alldistinctperiods.add(lastperiod);
        }

        String sectioncopy = "";

        int sheetpos = 0;
        int rowpos = 2;

        //-----------------INSIDE THE DATA FORM---------------------------------
        //if the section (eg HTC, PMTCT) changes, change the current workshhet index too
        //also, reset the row position counter to begin from 2 again. 
        XSSFSheet shet = null;

        //      if(--!sectioncopy.equals(shet)){}
        //create the org unit data values e.g BARINGO | BARINGO CENTRAL |KABARNET DISTRICT HOSPITAL | MFL CODE
        for (int g = 0; g < distinctsheets.size(); g++) {

            rowpos = rowstartpersheet[g];

            shet = wb.getSheetAt(g);
            int colpos = 0;

            String finalquery = perfacilselect.replace("1=1", distinctservicearea.get(g).toString());
            //System.out.println("" + finalquery);
            conn.rs = conn.st.executeQuery(finalquery);
            while (conn.rs.next()) {

                if (lastperiod.equalsIgnoreCase(conn.rs.getString("period")) && cumstartpointnoted == false) {
                    //save the current row position.
                    //get it from the current rowstartpersheet[g]

                    cumulativestatingpoint = rowstartpersheet[0];

                    cumstartpointnoted = true;
                    //this ensures that we are fetching dataonce.
                    // System.out.println("LAST STARTING POINT__"+cumulativestatingpoint);

                }

                //the fourth cell should     
                XSSFRow rw = shet.createRow(rowpos);
                for (int e = 0; e < Headerorgunits.size(); e++) {
                    XSSFCell cell0 = rw.createCell(colpos);
                    //for mfl code, last header, output integers
                    if (e > 3) {
                        cell0.setCellValue(conn.rs.getInt(e + 1));
                    } else {
                        cell0.setCellValue(conn.rs.getString(e + 1));
                    }

                    cell0.setCellStyle(style2);
                    colpos++;

                }

                //_________________________________________________________________
                //VALUES
                //_________________________________________________________________
                //create the indicators values eg 90 | 45  | 356    
                for (int c = 0; c < dbcolumns.size(); c++) {
                    //get the section of the current dbcolumn

                    //compare if the indicator belongs to the specified section and hence worksheet 
                    //recall, each indicator has got an associated section / worksheet
                    //An indicator should be put as an header in the respective worksheet
                    if (worksheets.get(c).equals(distinctsheets.get(g))) {

                        XSSFCell cell0 = rw.createCell(colpos);
                        cell0.setCellValue(conn.rs.getInt(dbcolumns.get(c).toString()));
                        cell0.setCellStyle(stborder);
                        colpos++;
                    } //end of comparing if

                } //end of for loop

                //ART_highvolume
                XSSFCell cell0 = rw.createCell(colpos);
                cell0.setCellValue(conn.rs.getInt("ART_highvolume"));
                cell0.setCellStyle(stborder);
                colpos++;

                //HTC_highvolume
                XSSFCell cell1 = rw.createCell(colpos);
                cell1.setCellValue(conn.rs.getInt("HTC_highvolume"));
                cell1.setCellStyle(stborder);
                colpos++;

                //PMTCT_highvolume
                XSSFCell cell2 = rw.createCell(colpos);
                cell2.setCellValue(conn.rs.getInt("PMTCT_highvolume"));
                cell2.setCellStyle(stborder);
                colpos++;

                //PMTCT_highvolume
                XSSFCell cell2a = rw.createCell(colpos);
                cell2a.setCellValue(conn.rs.getInt("GSN"));
                cell2a.setCellStyle(stborder);
                colpos++;

                String isvalidated = "Yes";

                if (conn.rs.getString("Form_Validated").equals("0")) {
                    isvalidated = "No";
                }
                XSSFCell cell3 = rw.createCell(colpos);
                cell3.setCellValue(isvalidated);
                cell3.setCellStyle(stborder);

                colpos++;

                rowpos++;
                if (colpos > 1) {
                    colposcopy = colpos - 1;

                }
                colpos = 0;
            } // end of while loop getting data from the db

            //____________________________________________________________________________________
            //COLUMN AUTOSIZE COLUMN WIDTH , AUTOFILTER & AUTOSUM
            //____________________________________________________________________________________
            //At this point we are sure this is the last row and we have exhausted fetching data for all periods
            //System.out.println(" Column position Before "+colposcopy);
            //                  if (lastperiod.equalsIgnoreCase(conn.rs.getString("period"))) {

            //System.out.println(" Column after "+colposcopy);
            shet.setAutoFilter(new CellRangeAddress(1, rowpos - 1, 0, colposcopy));

            //System.out.println("1,"+rowpos+",0,"+colposcopy);
            for (int e = 0; e < Headerorgunits.size(); e++) {
                shet.autoSizeColumn(e);
            }

            //autosum

            XSSFRow initialrow = shet.getRow(2);
            XSSFRow prevrow = shet.getRow(rowpos - 1);
            XSSFRow cumrow = shet.getRow(cumulativestatingpoint);//not used for now but let it stay here may be of use in future  

            XSSFRow rwsum = shet.createRow(rowpos);
            int colpossum = 0;
            int firstcols = 5;
            int periodcolumn = 0;

            for (int f = 0; f < firstcols; f++) {

                if (f == 0) {

                    XSSFCell cellsum = rwsum.createCell(0);
                    cellsum.setCellValue("Total");
                    cellsum.setCellStyle(stylesum);
                } else if (f > 0 && f < firstcols) {
                    XSSFCell cellsum = rwsum.createCell(f);
                    cellsum.setCellValue(" ");
                    cellsum.setCellStyle(stylesum);
                }
            }

            for (int c = 0; c < dbcolumns.size(); c++) {

                if (worksheets.get(c).equals(distinctsheets.get(g))) {

                    XSSFCell cellsum = rwsum.createCell(colpossum + firstcols);
                    XSSFCell initialcell = initialrow.getCell(colpossum + firstcols);

                    String cellformula = "";
                    XSSFCell prevcell = prevrow.getCell(colpossum + firstcols);//the last cell of the current column. rem whe are looping through all the columns
                    //periodcolumncell
                    XSSFCell initialperiodcell = initialrow.getCell(periodcolumn);// the first cell of the period(month, year) column
                    XSSFCell currentperiodcell = prevrow.getCell(periodcolumn);//the last cell of the period column

                    cellsum.setCellType(cellsum.CELL_TYPE_FORMULA);
                    String startcellreference = initialcell.getReference();
                    String lastavailableperiod = currentperiodcell.getStringCellValue();
                    if (iscumulative.get(c).equals("1")) {
                        //initialcell=cumrow.getCell(colpossum+firstcols);
                        //Create a formula that sums all the data for the last column to appear in the row. This should pick the first column which is the period column.
                        cellformula = "SUMPRODUCT(--(SUBTOTAL(3,OFFSET(INDEX("
                                + initialperiodcell.getReference() + ":" + currentperiodcell.getReference()
                                + ",1,1),ROW(" + initialperiodcell.getReference() + ":"
                                + currentperiodcell.getReference() + ")-ROW(INDEX("
                                + initialperiodcell.getReference() + ":" + currentperiodcell.getReference()
                                + ",1,1)),0))=1),--(" + initialperiodcell.getReference() + ":"
                                + currentperiodcell.getReference() + "=\"" + lastavailableperiod + "\"),"
                                + startcellreference + ":" + prevcell.getReference() + ")";

                    } else if (ispercent.get(c).equals("1")) {
                        //initialcell=cumrow.getCell(colpossum+firstcols);
                        //Create a formula that sums all the data for the last column to appear in the row. This should pick the first column which is the period column.
                        cellformula = "ROUNDUP(SUBTOTAL(9," + startcellreference + ":" + prevcell.getReference()
                                + "),1)"; // round of maximum values

                    } else {

                        cellformula = "SUBTOTAL(9," + startcellreference + ":" + prevcell.getReference() + ")";
                    }

                    //for cumulative indicators, we need to do column total for the last selected month
                    //we therefore need to always track where the previous month started at.
                    cellsum.setCellFormula(cellformula);
                    cellsum.setCellStyle(stylesum);

                    colpossum++;
                }
            }
            //merge last cell
            shet.addMergedRegion(new CellRangeAddress(rowpos, rowpos, 0, 4));
            // } end of checking  if this is the last month //disbled for now

            //
            rowstartpersheet[g] = rowpos;

        } // end of distinct sheets report

        // }//end of monthly loop

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        System.out.println("" + form.toUpperCase().trim() + "_RPT_FOR_" + year.trim() + "(" + periodlabel
                + ")_GEN_" + createdOn.trim() + ".xlsx");

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition",
                "attachment; filename=" + form.toUpperCase().trim() + "_REPORT_FOR_" + year.trim() + "("
                        + periodlabel.replace(" ", "") + ")_CREATED_" + createdOn.trim() + ".xlsx");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (SQLException ex) {
        Logger.getLogger(allStaticReportsdynamic.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:reports.allStaticReportsMonthly.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String monthrange = "";
    String periodlabel = "";
    String period = "Month"; //The default one
    try {// w  ww  .  ja  v a  2  s.  com
        response.setContentType("text/html;charset=UTF-8");

        //a page to get Report of all the servlets
        String months[] = null;

        String year = "2016";
        String month = "7";
        String county = "";
        String form = "moh731";

        if (request.getParameter("year") != null) {
            year = request.getParameter("year");
        }

        if (request.getParameter("county") != null) {
            county = request.getParameter("county");
        }

        if (request.getParameter("month") != null) {
            months = request.getParameterValues("month");
        }

        if (request.getParameter("form") != null) {
            form = request.getParameter("form");
        }
        String pivotform = form;
        if (form.equalsIgnoreCase("MOH 731")) {
            form = "MOH731";
        }
        if (form.equalsIgnoreCase("MOH 711A")) {
            form = "MOH711";
        }
        if (form.equalsIgnoreCase("MOH 711 (New)")) {
            form = "moh711_new";
        }
        String facilitywhere = "";
        String yearwhere = "";
        String monthwhere = "";
        String countywhere = "";
        String districtwhere = "";
        String reporttype = "";

        if (!year.equals("")) {

            yearwhere = " and Annee = '" + year + "'";

        }
        if (!county.equals("")) {

            countywhere = " and countyid = '" + county + "'";

        }

        dbConn conn = new dbConn();

        //an array to store haeder information.
        //the header information should appear only if certain parameters are met
        //The parameters listed in here can be removed if the report type doesnt require some parameters
        ArrayList Headerorgunits = new ArrayList();
        Headerorgunits.add(period);
        Headerorgunits.add("County");
        Headerorgunits.add("Sub-County");
        Headerorgunits.add("Facility");
        Headerorgunits.add("MFL Code");

        //An arralist to store a list of columns that will be selected from the database
        ArrayList dbcolumns = new ArrayList();

        ArrayList labels = new ArrayList();

        ArrayList tablename = new ArrayList();

        ArrayList iscumulative = new ArrayList();

        ArrayList ispercent = new ArrayList();

        // ArrayList isactive=new ArrayList();
        //An arralist to store a list of worksheets that will be selected from the sections and the respective service area to determine the facilities whose data will appear in that sheet
        ArrayList worksheets = new ArrayList();
        //An arralist to store distinct worksheets. This will be derived from the the sections column
        ArrayList distinctsheets = new ArrayList();
        ArrayList distinctservicearea = new ArrayList();

        //create an array to store the number of row for each excel worksheet. 
        //This will help in retrieving the number of rows for each month since we are wring data for different months with increasing rows.
        //the size of that array will be determined by the number of excel worksheets
        String selectdistinctworksheet = "select section,servicearea from pivottable where form='"
                + form.replace("_", "") + "' and active='1' group by section order by order_per_form";

        conn.rs = conn.st.executeQuery(selectdistinctworksheet);

        while (conn.rs.next()) {
            //add the name of distinct sections
            distinctsheets.add(conn.rs.getString(1).replace("/", "_"));

            String servicearea = "  2=2 ";
            if (conn.rs.getString(2) != null) {
                servicearea = "  " + conn.rs.getString(2) + "=1";
            }
            distinctservicearea.add(servicearea);

        }

        int rowstartpersheet[] = new int[distinctsheets.size()];

        //initialize the row start with 2
        for (int x = 0; x < rowstartpersheet.length; x++) {

            rowstartpersheet[x] = 2;

        }

        String getattribs = "select indicator,label,section,cumulative,percentage,active ,shortlabel from pivottable where form='"
                + form.replace("_", "") + "' order by order_per_form, section";
        conn.rs = conn.st.executeQuery(getattribs);

        while (conn.rs.next()) {

            //add active indicators only
            if (conn.rs.getString("active").equals("1")) {
                //System.out.println(conn.rs.getString("indicator")+"");
                //add indicator
                dbcolumns.add(conn.rs.getString("indicator"));
                //add label
                if (form.equalsIgnoreCase("MOH731")) {
                    labels.add(conn.rs.getString("shortlabel") + " \n" + conn.rs.getString("label"));

                } else {
                    labels.add(conn.rs.getString("label"));
                }
                //add worksheets
                worksheets.add(conn.rs.getString("section").replace("/", "_"));

                String perc = "0";
                String cum = "0";

                if (conn.rs.getString("cumulative") != null) {
                    iscumulative.add(conn.rs.getString("cumulative"));
                } else {
                    iscumulative.add(cum);
                }

                if (conn.rs.getString("percentage") != null) {
                    ispercent.add(conn.rs.getString("percentage"));
                } else {
                    ispercent.add(perc);
                }

            } //end of active 

        } //end of pivot table active
          //labels.add("ART High Volume");
          //labels.add("HTC High Volume");
          //labels.add("PMTCT High Volume");

        //System.out.println(perfacilselect);
        //______________________________________________________________________________________
        //                       CREATE THE WORKSHEETS          
        //______________________________________________________________________________________  
        XSSFWorkbook wb = new XSSFWorkbook();

        XSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        XSSFFont font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        XSSFCellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        XSSFCellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        XSSFCellStyle stylesum = wb.createCellStyle();
        stylesum.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylesum.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylesum.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylesum.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylesum.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        XSSFFont fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        stylex.setFont(fontx);
        stylex.setWrapText(true);

        stylesum.setFont(fontx);
        stylesum.setWrapText(true);
        int cellrange[] = new int[4];

        for (int b = 0; b < distinctsheets.size(); b++) {
            XSSFSheet shet = wb.createSheet(distinctsheets.get(b).toString().toUpperCase());

            //Made my life veery simple...
            shet.setDisplayGridlines(false);
            shet.createFreezePane(5, 2);
            int firstcell = 1;

            //shet.setAutoFilter(CellRangeAddress.valueOf("A2:N1"));
            //create headers for that worksheet
            XSSFRow rw = shet.createRow(1);
            int headercellpos = 0;
            //create the orgunit header eg COUNTY | SUBCOUNTY  | FACILITY

            for (int e = 0; e < Headerorgunits.size(); e++) {
                XSSFCell cell0 = rw.createCell(headercellpos);
                cell0.setCellValue(Headerorgunits.get(e).toString());
                cell0.setCellStyle(stylex);

                headercellpos++;
                //shet.setColumnWidth(e, 6000);  

            }

            //create the indicators header eg HV0101 | HIV 09676  | TOTAL    
            for (int c = 0; c < dbcolumns.size(); c++) {
                //compare if the indicator belongs to the specified section and hence worksheet 
                //recall, each indicator has got an associated section / worksheet
                //An indicator should be put as an header in the respective worksheet
                if (worksheets.get(c).equals(distinctsheets.get(b))) {

                    shet.setColumnWidth(headercellpos, 6000);
                    XSSFCell cell0 = rw.createCell(headercellpos);
                    cell0.setCellValue(labels.get(c).toString());
                    cell0.setCellStyle(stylex);
                    headercellpos++;
                } //end of comparing if

            } //end of for loop

            //create is validated header

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell0 = rw.createCell(headercellpos);
            cell0.setCellValue("ART High Volume");
            cell0.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell1 = rw.createCell(headercellpos);
            cell1.setCellValue("HTC High Volume");
            cell1.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell2 = rw.createCell(headercellpos);
            cell2.setCellValue("PMTCT High Volume");
            cell2.setCellStyle(stylex);
            headercellpos++;

            shet.setColumnWidth(headercellpos, 6000);
            XSSFCell cell3 = rw.createCell(headercellpos);
            cell3.setCellValue("Form Validated ?");
            cell3.setCellStyle(stylex);
            headercellpos++;

        }

        //______________________________________________________________________________________
        //______________________________________________________________________________________
        //--------------------------------------------------------------------------------------------
        //             MONTH LOOPS
        //-------------------------------------------------------------------------------------------- 
        int cumulativestatingpoint = 3;
        boolean cumstartpointnoted = false;
        int colposcopy = 0;
        for (int w = 0; w < months.length; w++) {

            month = months[w];

            if (!month.equals("")) {

                monthwhere = " and Mois = '" + month + "'";

            }

            String getMonth = "SELECT name FROM month WHERE id='" + month + "'";
            conn.rs = conn.st.executeQuery(getMonth);

            if (conn.rs.next() == true) {
                monthrange = conn.rs.getString(1);
                if (periodlabel.equals("")) {
                    periodlabel = monthrange.substring(0, 3);
                } else {
                    periodlabel += "_" + monthrange.substring(0, 3);
                }
            }

            String perfacilselect = "select '" + monthrange
                    + "', CONCAT(UPPER(SUBSTRING(County,1,1)),LOWER(SUBSTRING(County,2))) as County , DistrictNom as District , SubPartnerNom as facility ,CentreSanteId as mflcode ,  district.CountyID as countyid , ";

            //--------------------------------------------------------------------------------------------
            //             PREPARE SELECT
            //--------------------------------------------------------------------------------------------
            //prepare selects
            for (int a = 0; a < dbcolumns.size(); a++) {

                //if the indicator is a percent, get an avaerage
                if (ispercent.get(a).equals("1")) {
                    perfacilselect += "  AVG(" + dbcolumns.get(a) + ") as " + dbcolumns.get(a);

                } else if (iscumulative.get(a).equals("1")) {
                    perfacilselect += "  " + dbcolumns.get(a) + " as " + dbcolumns.get(a);

                } else {
                    perfacilselect += "  SUM(" + dbcolumns.get(a) + ") as " + dbcolumns.get(a);

                }

                //if the item is not the last, append a comma
                //if(a<dbcolumns.size()-1){
                perfacilselect += " ,";

                // } 
            }

            //---------------------------------add highvolume------------------------------------------------

            perfacilselect += " IFNULL(ART_highvolume,0) as ART_highvolume,  IFNULL(HTC_highvolume,0) as HTC_highvolume,  IFNULL(PMTCT_highvolume,0) as PMTCT_highvolume,";

            //-------------------------------------------------------------------------------------------------
            //     FROM  
            //------------------------------------------------------------------------------------  
            perfacilselect += "  isValidated as Form_Validated from " + form
                    + "  join ( subpartnera join (district join county on county.CountyID=district.CountyID ) on district.DistrictID = subpartnera.DistrictID )  on "
                    + form + ".SubPartnerID = subpartnera.SubPartnerID ";

            //------------------------------------------------------------------------------------------
            // WHERE 
            //------------------------------------------------------------------------------------------ 
            perfacilselect += " where  1=1 " + monthwhere + yearwhere;

            //-----------------------------------------------------------------------------------------
            //GROUP BY 
            //----------------------------------------------------------------------------------------
            perfacilselect += " group by subpartnera.SubPartnerID";

            String sectioncopy = "";

            int sheetpos = 0;
            int rowpos = 2;

            //-----------------INSIDE THE DATA FORM---------------------------------
            //if the section changes, change the position of the worksheet too
            //also, reset the position counter to begin from 2 again. 
            XSSFSheet shet = null;

            //      if(--!sectioncopy.equals(shet)){}
            //create the org unit data values e.g BARINGO | BARINGO CENTRAL |KABARNET DISTRICT HOSPITAL | MFL CODE
            for (int g = 0; g < distinctsheets.size(); g++) {

                if (w == months.length - 1 && cumstartpointnoted == false) {

                    //save the current row position.
                    //get it from the current rowstartpersheet[g]  
                    cumulativestatingpoint = rowstartpersheet[0];

                    cumstartpointnoted = true; //this ensures that we are fetching dataonce.
                    // System.out.println("LAST STARTING POINT__"+cumulativestatingpoint);

                }

                rowpos = rowstartpersheet[g];

                shet = wb.getSheetAt(g);
                int colpos = 0;

                String finalquery = perfacilselect.replace("1=1", distinctservicearea.get(g).toString());
                System.out.println("" + finalquery);
                conn.rs = conn.st.executeQuery(finalquery);
                while (conn.rs.next()) {

                    //the fourth cell should     
                    XSSFRow rw = shet.createRow(rowpos);
                    for (int e = 0; e < Headerorgunits.size(); e++) {
                        XSSFCell cell0 = rw.createCell(colpos);
                        //for mfl code, last header, output integers
                        if (e > 3) {
                            cell0.setCellValue(conn.rs.getInt(e + 1));
                        } else {
                            cell0.setCellValue(conn.rs.getString(e + 1));
                        }

                        cell0.setCellStyle(style2);
                        colpos++;

                    }

                    //_________________________________________________________________
                    //VALUES
                    //_________________________________________________________________
                    //create the indicators values eg 90 | 45  | 356    
                    for (int c = 0; c < dbcolumns.size(); c++) {
                        //get the section of the current dbcolumn

                        //compare if the indicator belongs to the specified section and hence worksheet 
                        //recall, each indicator has got an associated section / worksheet
                        //An indicator should be put as an header in the respective worksheet
                        if (worksheets.get(c).equals(distinctsheets.get(g))) {

                            XSSFCell cell0 = rw.createCell(colpos);
                            cell0.setCellValue(conn.rs.getInt(dbcolumns.get(c).toString()));
                            cell0.setCellStyle(stborder);
                            colpos++;
                        } //end of comparing if

                    } //end of for loop

                    //ART_highvolume
                    XSSFCell cell0 = rw.createCell(colpos);
                    cell0.setCellValue(conn.rs.getInt("ART_highvolume"));
                    cell0.setCellStyle(stborder);
                    colpos++;

                    //HTC_highvolume
                    XSSFCell cell1 = rw.createCell(colpos);
                    cell1.setCellValue(conn.rs.getInt("HTC_highvolume"));
                    cell1.setCellStyle(stborder);
                    colpos++;

                    //PMTCT_highvolume
                    XSSFCell cell2 = rw.createCell(colpos);
                    cell2.setCellValue(conn.rs.getInt("PMTCT_highvolume"));
                    cell2.setCellStyle(stborder);
                    colpos++;

                    String isvalidated = "Yes";

                    if (conn.rs.getString("Form_Validated").equals("0")) {
                        isvalidated = "No";
                    }
                    XSSFCell cell3 = rw.createCell(colpos);
                    cell3.setCellValue(isvalidated);
                    cell3.setCellStyle(stborder);

                    colpos++;

                    rowpos++;
                    if (colpos > 1) {
                        colposcopy = colpos - 1;

                    }
                    colpos = 0;
                } // end of while loop getting data from the db

                //____________________________________________________________________________________
                //COLUMN AUTOSIZE COLUMN WIDTH , AUTOFILTER & AUTOSUM
                //____________________________________________________________________________________

                //At this point we are sure this is the last row and we have exhausted fetching data for all months

                //System.out.println(" Column position Before "+colposcopy);

                if (w == months.length - 1) {

                    //System.out.println(" Column after "+colposcopy);

                    shet.setAutoFilter(new CellRangeAddress(1, rowpos - 1, 0, colposcopy));

                    //System.out.println("1,"+rowpos+",0,"+colposcopy);

                    for (int e = 0; e < Headerorgunits.size(); e++) {
                        shet.autoSizeColumn(e);
                    }

                    //autosum
                    XSSFRow rwsum = shet.createRow(rowpos);
                    XSSFRow initialrow = shet.getRow(2);
                    XSSFRow prevrow = shet.getRow(rowpos - 1);
                    XSSFRow cumrow = shet.getRow(cumulativestatingpoint);//not used for now but let it stay here may be of use in future  

                    int colpossum = 0;
                    int firstcols = 5;
                    int periodcolumn = 0;

                    for (int f = 0; f < firstcols; f++) {

                        if (f == 0) {

                            XSSFCell cellsum = rwsum.createCell(0);
                            cellsum.setCellValue("Total");
                            cellsum.setCellStyle(stylesum);
                        } else if (f > 0 && f < firstcols) {
                            XSSFCell cellsum = rwsum.createCell(f);
                            cellsum.setCellValue(" ");
                            cellsum.setCellStyle(stylesum);
                        }
                    }

                    for (int c = 0; c < dbcolumns.size(); c++) {

                        if (worksheets.get(c).equals(distinctsheets.get(g))) {

                            XSSFCell cellsum = rwsum.createCell(colpossum + firstcols);
                            XSSFCell initialcell = initialrow.getCell(colpossum + firstcols);

                            String cellformula = "";
                            XSSFCell prevcell = prevrow.getCell(colpossum + firstcols);//the last cell of the current column. rem whe are looping through all the columns
                            //periodcolumncell
                            XSSFCell initialperiodcell = initialrow.getCell(periodcolumn);// the first cell of the period(month, year) column
                            XSSFCell currentperiodcell = prevrow.getCell(periodcolumn);//the last cell of the period column

                            cellsum.setCellType(cellsum.CELL_TYPE_FORMULA);
                            String startcellreference = initialcell.getReference();
                            String lastavailableperiod = currentperiodcell.getStringCellValue();
                            if (iscumulative.get(c).equals("1")) {
                                //initialcell=cumrow.getCell(colpossum+firstcols);
                                //Create a formula that sums all the data for the last column to appear in the row. This should pick the first column which is the period column.
                                cellformula = "SUMPRODUCT(--(SUBTOTAL(3,OFFSET(INDEX("
                                        + initialperiodcell.getReference() + ":"
                                        + currentperiodcell.getReference() + ",1,1),ROW("
                                        + initialperiodcell.getReference() + ":"
                                        + currentperiodcell.getReference() + ")-ROW(INDEX("
                                        + initialperiodcell.getReference() + ":"
                                        + currentperiodcell.getReference() + ",1,1)),0))=1),--("
                                        + initialperiodcell.getReference() + ":"
                                        + currentperiodcell.getReference() + "=\"" + lastavailableperiod
                                        + "\")," + startcellreference + ":" + prevcell.getReference() + ")";

                            } else if (ispercent.get(c).equals("1")) {
                                //initialcell=cumrow.getCell(colpossum+firstcols);
                                //Create a formula that sums all the data for the last column to appear in the row. This should pick the first column which is the period column.
                                cellformula = "ROUNDUP(SUBTOTAL(9," + startcellreference + ":"
                                        + prevcell.getReference() + "),1)"; // round of maximum values

                            } else {

                                cellformula = "SUBTOTAL(9," + startcellreference + ":" + prevcell.getReference()
                                        + ")";
                            }

                            //for cumulative indicators, we need to do column total for the last selected month
                            //we therefore need to always track where the previous month started at.

                            cellsum.setCellFormula(cellformula);
                            cellsum.setCellStyle(stylesum);

                            colpossum++;
                        }
                    }
                    //merge last cell
                    shet.addMergedRegion(new CellRangeAddress(rowpos, rowpos, 0, 4));
                }

                //

                rowstartpersheet[g] = rowpos;

            } // end of distinct sheets report

        } //end of monthly loop

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        System.out.println("" + form.toUpperCase().trim() + "_RPT_FOR_" + year.trim() + "(" + month.trim()
                + ")_GEN_" + createdOn.trim() + ".xlsx");

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition", "attachment; filename=" + form.toUpperCase().trim()
                + "_REPORT_FOR_" + year.trim() + "(" + periodlabel + ")_CREATED_" + createdOn.trim() + ".xlsx");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (SQLException ex) {
        Logger.getLogger(allStaticReportsMonthly.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:rpt.GUI.ProgramStrategist.CyclePlans.CompareDialogController.java

public void okButtonClicked() throws IOException {
    // create two new maps, one for currentCycleplan and one for the comparison plan
    Map<String, TableVariant> currentCyclePlan = new HashMap<String, TableVariant>();
    Map<String, TableVariant> oldCyclePlan = new HashMap<String, TableVariant>();
    Map<String, TableVariant> movedVariants = new HashMap<String, TableVariant>();
    Map<String, TableVariant> changedVariants = new HashMap<String, TableVariant>();
    Map<String, Map<String, String>> changedInfo = new HashMap<String, Map<String, String>>();
    Map<String, String> diffValues = new HashMap<String, String>();

    Statement statement;//from w  ww. ja  v  a2 s. c  o m
    try {
        // Set current YYwWW and use to ignore variants that are no longer in production
        Calendar cal = Calendar.getInstance();
        String currentWeek = cal.get(Calendar.YEAR) % 100 + "w" + cal.get(Calendar.WEEK_OF_YEAR);

        // Extract all variants in the current cycleplan and put them in an map
        System.out.println("Extracting current variants");
        statement = RPT.conn.createStatement();
        statement.setQueryTimeout(30);
        String query = "SELECT * FROM VARIANTS, VariantBelongsToCyclePlan WHERE "
                + "VariantBelongsToCyclePlan.CyclePlanID= \'" + CyclePlansController.selectedCyclePlan + "\' "
                + "AND VARIANTS.VariantID = VariantBelongsToCyclePlan.VariantID " + "AND EndOfProd > '"
                + currentWeek + "'";
        ResultSet rs = statement.executeQuery(query);

        while (rs.next()) {
            TableVariant entry = new TableVariant(rs.getString("Plant"), rs.getString("Platform"),
                    rs.getString("Vehicle"), rs.getString("Propulsion"), rs.getString("Denomination"),
                    rs.getString("Fuel"), rs.getString("EngineFamily"), rs.getString("Generation"),
                    "EngineName not used", rs.getString("EngineCode"), rs.getString("Displacement"),
                    rs.getString("EnginePower"), rs.getString("ElMotorPower"), rs.getString("Torque"),
                    rs.getString("TorqueOverBoost"), rs.getString("GearboxType"), rs.getString("Gears"),
                    rs.getString("Gearbox"), rs.getString("Driveline"), rs.getString("TransmissionCode"),
                    rs.getString("CertGroup"), rs.getString("EmissionClass"), rs.getString("StartOfProd"),
                    rs.getString("EndOfProd"));
            currentCyclePlan.put(entry.getVariantID(), entry);
        }
        //Now extract all variants in the cycleplan to compare with
        System.out.println("Extracting comparison variants");
        query = "SELECT * FROM VARIANTS, VariantBelongsToCyclePlan WHERE "
                + "VariantBelongsToCyclePlan.CyclePlanID= \'"
                + cyclePlanSelector.getSelectionModel().getSelectedItem().toString() + "\' "
                + "AND VARIANTS.VariantID = VariantBelongsToCyclePlan.VariantID " + "AND EndOfProd > '"
                + currentWeek + "'";
        rs = statement.executeQuery(query);

        while (rs.next()) {
            TableVariant entry = new TableVariant(rs.getString("Plant"), rs.getString("Platform"),
                    rs.getString("Vehicle"), rs.getString("Propulsion"), rs.getString("Denomination"),
                    rs.getString("Fuel"), rs.getString("EngineFamily"), rs.getString("Generation"),
                    "EngineName not used", rs.getString("EngineCode"), rs.getString("Displacement"),
                    rs.getString("EnginePower"), rs.getString("ElMotorPower"), rs.getString("Torque"),
                    rs.getString("TorqueOverBoost"), rs.getString("GearboxType"), rs.getString("Gears"),
                    rs.getString("Gearbox"), rs.getString("Driveline"), rs.getString("TransmissionCode"),
                    rs.getString("CertGroup"), rs.getString("EmissionClass"), rs.getString("StartOfProd"),
                    rs.getString("EndOfProd"));
            oldCyclePlan.put(entry.getVariantID(), entry);
        }

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }

    //for each variant in current plan, remove from both if it exists in old
    for (Iterator<Map.Entry<String, TableVariant>> entries = currentCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        if (oldCyclePlan.containsKey(entry.getKey())) {
            entries.remove(); // remove from currentCyclePlan
            oldCyclePlan.remove(entry.getKey());
        }
    }

    // Now need to check if some entries were only moved in time
    for (Iterator<Map.Entry<String, TableVariant>> entries = currentCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        try {
            statement = RPT.conn.createStatement();
            statement.setQueryTimeout(30);
            //TODO
            //Add all columns except Start of production, as all will be important to find it correctly
            String query = "SELECT VARIANTS.VariantID, VARIANTS.StartOfProd, VARIANTS.EndOfProd FROM VARIANTS, VariantBelongsToCyclePlan WHERE "
                    + "VARIANTS.VariantID = VariantBelongsToCyclePlan.VariantID AND "
                    + "VariantBelongsToCyclePlan.CyclePlanID= \'"
                    + cyclePlanSelector.getSelectionModel().getSelectedItem().toString() + "\' AND "
                    + "VARIANTS.Plant = \'" + entry.getValue().getPlant() + "\' AND " + "VARIANTS.Platform = \'"
                    + entry.getValue().getPlatform() + "\' AND " + "VARIANTS.Vehicle = \'"
                    + entry.getValue().getVehicle() + "\' AND " + "VARIANTS.Propulsion = \'"
                    + entry.getValue().getPropulsion() + "\' AND " + "VARIANTS.Denomination = \'"
                    + entry.getValue().getDenomination() + "\' AND " + "VARIANTS.Fuel = \'"
                    + entry.getValue().getFuel() + "\' AND " + "VARIANTS.EngineFamily = \'"
                    + entry.getValue().getEngineFamily() + "\' AND " + "VARIANTS.Generation = \'"
                    + entry.getValue().getGeneration() + "\' AND " + "VARIANTS.EngineCode = \'"
                    + entry.getValue().getEngineCode() + "\' AND " + "VARIANTS.Displacement = \'"
                    + entry.getValue().getDisplacement() + "\' AND " + "VARIANTS.EnginePower = \'"
                    + entry.getValue().getEnginePower() + "\' AND " + "VARIANTS.ElMotorPower = \'"
                    + entry.getValue().getElMotorPower() + "\' AND " + "VARIANTS.TorqueOverBoost = \'"
                    + entry.getValue().getTorqueOverBoost() + "\' AND " + "VARIANTS.GearboxType = \'"
                    + entry.getValue().getGearboxType() + "\' AND " + "VARIANTS.Gears = \'"
                    + entry.getValue().getGears() + "\' AND " + "VARIANTS.Gearbox = \'"
                    + entry.getValue().getGearbox() + "\' AND " + "VARIANTS.Driveline = \'"
                    + entry.getValue().getDriveline() + "\' AND " + "VARIANTS.TransmissionCode = \'"
                    + entry.getValue().getTransmissionCode() + "\' AND " + "VARIANTS.CertGroup = \'"
                    + entry.getValue().getCertGroup() + "\' AND " // may remove once
                    + "VARIANTS.EmissionClass = \'" + entry.getValue().getEmissionClass() + "\'";
            ResultSet rs = statement.executeQuery(query);
            if (rs.next()) {
                entry.getValue().setOldSOP(rs.getString("StartOfProd"));
                entry.getValue().setOldEOP(rs.getString("EndOfProd"));
                movedVariants.put(entry.getKey(), entry.getValue()); //Save variant to moved map
                entries.remove(); //remove variant from current map
                oldCyclePlan.remove(rs.getString("VariantID")); //remove variant from old map
            }

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    // Now check for variants that have been slightly changed only.
    // Show a dialog window allowing the user to define what a minor change is
    majorChanges = new ArrayList();
    Stage stage;
    Parent root;
    stage = new Stage();
    root = FXMLLoader
            .load(getClass().getResource("/rpt/GUI/ProgramStrategist/CyclePlans/dialogDefineChanged.fxml"));
    stage.setScene(new Scene(root));
    stage.setTitle("Set change definition");
    stage.initModality(Modality.APPLICATION_MODAL);
    stage.showAndWait(); // pause until the user has selected minor changes

    // Now loop through the remaining Added items and check if they are to be moved to "Modified"
    //for (String s : majorChanges) {
    //    System.out.println(s);
    //}
    // Create string for extracting data which has been judged as minor
    //String dataString = ""; // Data which will be used for difference check
    //for (String s : majorChanges) {
    //    dataString = dataString + ", VARIANTS." + s;
    //}
    // Build list of parameters to extract and compare with the new variant
    ArrayList<String> infoArray = new ArrayList();
    String query = "PRAGMA table_info(VARIANTS)"; //Get all column names
    String extractionData = "";
    try {
        statement = RPT.conn.createStatement();
        statement.setQueryTimeout(30);
        ResultSet rsColumns = statement.executeQuery(query);
        //traverser through list of columns and add those not pointed out as MAJOR
        boolean first = true;
        while (rsColumns.next()) {
            if (!(majorChanges.contains(rsColumns.getString("name")))) {
                infoArray.add(rsColumns.getString("name"));
                if (first) {
                    extractionData = extractionData + "VARIANTS." + rsColumns.getString("name");
                    first = false;
                } else {
                    extractionData = extractionData + ", VARIANTS." + rsColumns.getString("name");
                }
            }
        }

    } catch (Exception e) {
        System.err.println("CompareDialogController error when building extraction data: " + e.getMessage());
    }

    for (Iterator<Map.Entry<String, TableVariant>> entries = currentCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        try {
            statement = RPT.conn.createStatement();
            statement.setQueryTimeout(30);
            query = "SELECT ";
            query = query + extractionData;
            query = query + " FROM VARIANTS, VariantBelongsToCyclePlan WHERE "
                    + "VARIANTS.VariantID = VariantBelongsToCyclePlan.VariantID AND "
                    + "VariantBelongsToCyclePlan.CyclePlanID= \'"
                    + cyclePlanSelector.getSelectionModel().getSelectedItem().toString() + "\'";

            for (String s : majorChanges) {
                query = query + " AND VARIANTS." + s + " = \'" + entry.getValue().getValue(s) + "\'";
            }
            //System.out.println(query);
            ResultSet rs = statement.executeQuery(query);
            if (rs.next()) {
                // Found "similar enough"
                changedVariants.put(entry.getKey(), entry.getValue()); //Save variant to moved map
                entries.remove(); //remove variant from current map
                oldCyclePlan.remove(rs.getString("VariantID")); //remove variant from old map

                // now loop through all non major columns and check for difference between variant in new and old cycle plan
                diffValues = new HashMap<String, String>();
                for (String s : infoArray) {
                    if (!rs.getString(s).equals(entry.getValue().getValue(s))) {
                        diffValues.put(s, rs.getString(s));
                    }
                }

                changedInfo.put(entry.getKey(), diffValues); //Add information about differences between new and old variant
            }

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    // Open file selector and let user specify report file
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Information");

    //turn off gridlines
    sheet.setDisplayGridlines(false);
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();

    //the following three statements are required only for HSSF
    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    // print out information about baseline cycle plan
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    Font headerFont = workbook.createFont();
    headerFont.setBold(true);
    CellStyle style = workbook.createCellStyle();
    style.setFont(headerFont);
    cell.setCellStyle(style);
    cell.setCellValue("Cycle plan:");
    cell = row.createCell(1);
    cell.setCellValue(CyclePlansController.selectedCyclePlan);

    // print out information about comaparison cycle plan
    row = sheet.createRow(1);
    cell = row.createCell(0);
    headerFont = workbook.createFont();
    headerFont.setBold(true);
    style.setFont(headerFont);
    cell.setCellStyle(style);
    cell.setCellValue("Compared to:");
    cell = row.createCell(1);
    cell.setCellValue(cyclePlanSelector.getSelectionModel().getSelectedItem().toString());

    sheet.autoSizeColumn(0);
    sheet.autoSizeColumn(1);

    // Write Added variant information
    sheet = workbook.createSheet("Added");
    //freeze the first row
    sheet.createFreezePane(0, 1);
    row = sheet.createRow(0);
    writeHeaders(workbook, row, false);
    int rowNum = 1;
    int amountOfColumns = 0;
    // loop through added
    for (Iterator<Map.Entry<String, TableVariant>> entries = currentCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        row = sheet.createRow(rowNum);
        amountOfColumns = writeRow(workbook, sheet, row, entry.getValue(), null, false, false);

        rowNum++;
    }
    //autosize all columns
    for (int i = 0; i < amountOfColumns; i++) {
        sheet.autoSizeColumn(i);
    }
    amountOfColumns = 0;

    // Write Removed variant information
    sheet = workbook.createSheet("Removed");
    //freeze the first row
    sheet.createFreezePane(0, 1);
    row = sheet.createRow(0);
    writeHeaders(workbook, row, false);
    rowNum = 1;
    // loop through removed
    for (Iterator<Map.Entry<String, TableVariant>> entries = oldCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        row = sheet.createRow(rowNum);
        amountOfColumns = writeRow(workbook, sheet, row, entry.getValue(), null, false, false);

        rowNum++;
    }
    //autosize all columns
    for (int i = 0; i < amountOfColumns; i++) {
        sheet.autoSizeColumn(i);
    }
    amountOfColumns = 0;

    // Write Changed variant information
    sheet = workbook.createSheet("Changed");
    //freeze the first row
    sheet.createFreezePane(0, 1);
    row = sheet.createRow(0);
    writeHeaders(workbook, row, false);
    rowNum = 1;
    // loop through changed
    for (Iterator<Map.Entry<String, TableVariant>> entries = changedVariants.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        row = sheet.createRow(rowNum);
        amountOfColumns = writeRow(workbook, sheet, row, entry.getValue(), changedInfo, true, false);

        rowNum++;
    }
    //autosize all columns
    for (int i = 0; i < amountOfColumns; i++) {
        sheet.autoSizeColumn(i);
    }
    amountOfColumns = 0;

    // Write Moved variant information
    sheet = workbook.createSheet("Moved");
    //freeze the first row
    sheet.createFreezePane(0, 1);
    row = sheet.createRow(0);
    writeHeaders(workbook, row, true);
    rowNum = 1;
    for (Iterator<Map.Entry<String, TableVariant>> entries = movedVariants.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        row = sheet.createRow(rowNum);
        amountOfColumns = writeRow(workbook, sheet, row, entry.getValue(), null, false, true);

        rowNum++;

    }
    //autosize all columns
    for (int i = 0; i < amountOfColumns; i++) {
        sheet.autoSizeColumn(i);
    }
    amountOfColumns = 0;

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save Comparison Result File");

    File selectedFile = fileChooser.showSaveDialog(null);

    if (selectedFile != null) {
        try {
            FileOutputStream out = new FileOutputStream(selectedFile);
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully..");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    closeDialog();
}

From source file:se.inera.intyg.rehabstod.service.export.xlsx.XlsxExportServiceImpl.java

License:Open Source License

private void addDataRows(XSSFSheet sheet, int rowIndex, List<SjukfallEnhet> sjukfallList, Urval urval,
        boolean showPatientId, boolean showSrs) {
    for (int a = 0; a < sjukfallList.size(); a++) {
        XSSFRow row = sheet.createRow(rowIndex + a);
        SjukfallEnhet sf = sjukfallList.get(a);

        int colIndex = 0;
        createDataCell(row, colIndex++, Integer.toString(a + 1));
        if (showPatientId) {
            createRichTextDataCell(row, colIndex++, buildPersonnummerRichText(sf.getPatient()));
        }/*w w w . ja  v a 2s.  c o m*/
        createDataCell(row, colIndex++, Integer.toString(sf.getPatient().getAlder()));

        if (showPatientId) {
            createDataCell(row, colIndex++, sf.getPatient().getNamn());
        }
        createDataCell(row, colIndex++, sf.getPatient().getKon().getDescription());
        createDataCell(row, colIndex++, getCompoundDiagnoseText(sf));
        createDataCell(row, colIndex++, YearMonthDateFormatter.print(sf.getStart()));
        createDataCell(row, colIndex++, YearMonthDateFormatter.print(sf.getSlut()));
        createDataCell(row, colIndex++, String.format(FORMAT_ANTAL_DAGAR, sf.getDagar()));
        createDataCell(row, colIndex++, Integer.toString(sf.getIntyg()));
        createRichTextDataCell(row, colIndex++, buildGraderRichText(sf));
        if (urval != Urval.ISSUED_BY_ME) {
            createDataCell(row, colIndex++, sf.getLakare().getNamn());
        }

        if (showSrs) {
            createDataCell(row, colIndex++, getRiskKategoriDesc(sf.getRiskSignal()));
        }

    }
    for (int a = 0; a < headers.length; a++) {
        sheet.autoSizeColumn(a);
    }
    // Makes sure the "namn" column isn't excessively wide due to the filter.
    sheet.setColumnWidth(2, 7000);
}

From source file:tr.org.liderahenk.liderconsole.core.utils.SWTResourceManager.java

License:Open Source License

private static XSSFWorkbook createWorkbookFromTable(TableViewer tableViewer, String sheetName) {

    // Create workbook & sheet
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet(sheetName == null ? "Sheet1" : sheetName);

    // Shade the background of the header row
    XSSFCellStyle headerStyle = wb.createCellStyle();
    headerStyle.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
    headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    headerStyle.setBorderTop(CellStyle.BORDER_THIN);
    headerStyle.setBorderBottom(CellStyle.BORDER_THIN);
    headerStyle.setBorderLeft(CellStyle.BORDER_THIN);
    headerStyle.setBorderRight(CellStyle.BORDER_THIN);
    headerStyle.setAlignment(HorizontalAlignment.CENTER);

    // Add header row
    Table table = tableViewer.getTable();
    TableColumn[] columns = table.getColumns();
    int rowIndex = 0;
    int cellIndex = 0;
    XSSFRow header = sheet.createRow((short) rowIndex++);
    for (TableColumn column : columns) {
        XSSFCell cell = header.createCell(cellIndex++);
        cell.setCellValue(column.getText());
        cell.setCellStyle(headerStyle);//from  w  ww.ja  va 2 s  .  c o m
    }

    // Add data rows
    TableItem[] items = tableViewer.getTable().getItems();
    for (TableItem item : items) {
        // create a new row
        XSSFRow row = sheet.createRow((short) rowIndex++);
        cellIndex = 0;

        for (int i = 0; i < columns.length; i++) {
            // Create a new cell
            XSSFCell cell = row.createCell(cellIndex++);
            String text = item.getText(i);

            // Set the horizontal alignment (default to RIGHT)
            XSSFCellStyle cellStyle = wb.createCellStyle();
            if (LiderCoreUtils.isInteger(text)) {
                cellStyle.setAlignment(HorizontalAlignment.RIGHT);
            } else if (LiderCoreUtils.isValidDate(text,
                    ConfigProvider.getInstance().get(LiderConstants.CONFIG.DATE_FORMAT))) {
                cellStyle.setAlignment(HorizontalAlignment.CENTER);
            } else {
                cellStyle.setAlignment(HorizontalAlignment.LEFT);
            }
            cell.setCellStyle(cellStyle);

            // Set the cell's value
            cell.setCellValue(text);
        }
    }

    // Auto-fit the columns
    for (int i = 0; i < columns.length; i++) {
        sheet.autoSizeColumn((short) i);
    }

    return wb;
}

From source file:util.ExcelConverter.java

public static File createXlsx(String[] header, String[][] data, String path) {

    try {/*  ww w .  j av  a2 s . c o  m*/
        XSSFWorkbook xwb = new XSSFWorkbook();
        XSSFSheet sheet = xwb.createSheet();

        CellStyle cellStyle = xwb.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
        cellStyle.setAlignment(CellStyle.VERTICAL_TOP);
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyle.setWrapText(false);

        Font bold = xwb.createFont();
        bold.setBoldweight(Font.BOLDWEIGHT_BOLD);
        bold.setFontHeightInPoints((short) 10);

        CellStyle cellStyleHeader = xwb.createCellStyle();
        cellStyleHeader.setAlignment(CellStyle.ALIGN_LEFT);
        cellStyleHeader.setAlignment(CellStyle.VERTICAL_TOP);
        cellStyleHeader.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyleHeader.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cellStyleHeader.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyleHeader.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyleHeader.setFont(bold);
        cellStyleHeader.setWrapText(false);

        XSSFRow row;
        Cell cell;

        //header
        row = sheet.createRow(0);
        for (int i = 0; i < header.length; i++) {
            cell = row.createCell(i);
            cell.setCellStyle(cellStyleHeader);
            cell.setCellValue(header[i]);
        }

        int colCount = header.length;
        int no = 1;

        for (String[] obj : data) {
            row = sheet.createRow(no);
            for (int i = 0; i < colCount; i++) {
                cell = row.createCell(i);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(obj[i]);
            }
            no++;
        }

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

        File newFile = new File(path);
        try (FileOutputStream fileOut = new FileOutputStream(path)) {
            xwb.write(fileOut);
        }

        return newFile;
    } catch (IOException e) {
        return null;
    }
}