Showing posts with label opensource. Show all posts
Showing posts with label opensource. Show all posts

Wednesday, August 27, 2014

Write Excel File Using Apache POI in Java

Hi All,

Editing Microsoft documents using a java program might be useful in certain cases. For that there are various libraries. Here I'm going to show you how you can use the Apache POI with Microsoft Documents. More details are available here.

I had to use Apache POI to create and write values received from Arduino, to an Excel Sheet. So here I'm going to show you how you can write values to an Excel Sheet.

First download the latest release from Apache POI. It can be downloaded from here.

Create a new project in Eclipse and create a new class named 'WriteExcel.java'. Add a new folder to the project named 'lib'. Extract the Apache POI library and copy the 'poi-3.10.1-20140818.jar' to the lib folder. Then add the jar to the project by Right Click the Project -> Build Path -> Configure Build Path -> Add JARs.



Now we can start coding the 'WriteExcel.java' class.
Following is the complete code.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.WorkbookUtil;


public class WriteExcel {
 
 public static void main(String[] args) {
  Workbook workbook = new HSSFWorkbook(); //Create a workbook object
  
  //Create a sheet inside the workbook. There are several ways to do this. 
  //1.Create sheet with default name
  Sheet sheet1 = workbook.createSheet(); 
  //2.Create Sheet with Valid Name
  Sheet sheet2 = workbook.createSheet("ValidName"); 
  //3.Create Sheet with any (may be invalid) name
  //createSafeSheetName() will make it correct
  Sheet sheet3 = workbook.createSheet(WorkbookUtil.createSafeSheetName("%?%#23InvalidName"));
  
  //Let's write some values to rows and columns in sheet1
  
  for (int i = 0; i < 20; i++) {
   //Create a row in sheet 1 assign it to "Row" object.
   Row row = sheet1.createRow(i);
   for (int j = 0; j < 10; j++) {
    //Create a cell in 'row' and assign it to "Cell" object
    Cell cell = row.createCell(j);
    //Write Values to Cell
    cell.setCellValue("( "+i+","+j+" )");
   }
  }
  
  try {
   //Create a new file output stream to write data to a File
   FileOutputStream fileOutputStream = new FileOutputStream("FirstExcel.xls");
   //Write values to the file
   workbook.write(fileOutputStream);
   //Cose file output stream
   fileOutputStream.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

Now run the file and once you refresh the project, you'll see the "FirstExcel.xls" file added to your project. Open it. Following is the output.


Hope that helps, 
Thank You. :-) 

PHP Send Mail with XAMPP Localhost Using PHPMailer

Hi All,

When developing a website, you might want to send a mail using PHP script through the localhost, specially when developing pages like Contact Us pages.

There are several ways we can do this.

One way is to send the mail using XAMPP by changing the php.ini and sendmail.ini. I have tried to use this method, but couldn't get any good result. In some posts readers have complained that it does work at times, but not every time.

Another way is using PHPMailer. It's an opensource code that helps to send mails via PHP. This is the best method I came across and it's really really easy to integrate in your site. You can read more about PHPMailer from this link.

NOTE : Before you are trying to work with the PHPMailer and Google SMTP, one important thing you should do is to Allow Less Secure Access in the Google Account you are using to Authenticate mailing. You can do it using this link

Download the PHPMailer from github and extract it to your site. If you are using XAMPP the location would be like "C:\xampp\htdocs\your_site\email". Now first you have to develop a php file that can submit a form. Following is a template of a contact form. You can add additional fields as you want.

<div class="col-md-8" id="divMain">

    <h1>Contact Us</h1>
    <h3 style="color:#8EB037;"><?php echo @$_GET['msg'];?></h3>
    <hr/>
 <!--Start Contact form -->                                                  
    <form name="contactform" method="post" action="email/index.php" class="form-horizontal" role="form" onsubmit="return validation();">
        <div class="form-group">
            <label for="inputName" class="col-md-2 control-label" style="text-align:left;">Name</label>
            <div class="col-md-10">
                <input type="text" class="form-control" id="inputName" name="inputName" placeholder="Your Name">
            </div>
        </div>
        <div class="form-group">
            <label for="inputEmail1" class="col-md-2 control-label" style="text-align:left;">Email</label>
            <div class="col-md-10">
                <input type="text" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email">
            </div>
        </div>
        <div class="form-group">
            <label for="inputSubject" class="col-md-2 control-label" style="text-align:left;">Subject</label>
            <div class="col-md-10">
                <input type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message">
            </div>
        </div>
        <div class="form-group">
            <label for="inputPassword1" class="col-md-2 control-label" style="text-align:left;">Message</label>
            <div class="col-md-10">
                <textarea class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..."></textarea>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button type="submit" class="btn btn-primary pull-right" value="submit" name="submit" >
                    Send Message
                </button>
            </div>
        </div>
    </form>  
 <!--End Contact form -->            
</div>

Note : Here I have used bootstrap 3 for the contact form. I placed my contact form in the directory "C:\xampp\htdocs\your_site\contact.php".

Then in the email folder ("C:\xampp\htdocs\your_site\email") include the javascript validation for the validation of form fields and index.php for sending the mail. Following is the index.php code.

require_once 'phpmailer/PHPMailerAutoload.php';

 if(isset($_POST['submit']))
 {
 $name = $_POST['inputName'];
 $email = $_POST['inputEmail'];
 $query = $_POST['inputMessage'];
 $email_from = $name.'<'.$email.'>';
 $subject = $_POST['inputSubject'];

 $message="   
    
   Name:
  $name     
  

   Email-Id:
  $email     
  

   Message:
  $query     

 ";

 $mail = new PHPMailer;

 $mail->isSMTP(); // Set mailer to use SMTP
 $mail->SMTPAuth = true; // Enable SMTP authentication
 //$mail->SMTPDebug = 2; //Please enable debug if you want to check if the mail sent successfully.

 $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
 $mail->Username = 'yourname@gmail.com';    // SMTP username
 $mail->Password = 'yourpassword';  // SMTP password
 $mail->SMTPSecure = 'ssl';   // Enable encryption, 'ssl' also accepted
 $mail->Port = 465; 

 $mail->addAddress('yourname@gmail.com', 'YourName');
 $mail->From = $email;
 $mail->FromName = $name;
 $mail->Subject = $subject;
 $mail->Body    = $message;
 $mail->AltBody = $message;

 if(!$mail->send()) {
  header("Location:../contact.php?msg=Error To send Email !");
 } else {
  header("Location:../contact.php?msg=Successful Submission! Thankyou for contacting us.");
 }
 }

Following is the javascript validation

 function validation()
 {
    
 var contactname=document.contactform.inputName.value;
 var name_exp=/^[A-Za-z\s]+$/;
 if(contactname=='')
 {
  alert("Name Field Should Not Be Empty!");
  document.contactform.inputName.focus();
  return false;
 }
 else if(!contactname.match(name_exp))
 {
  alert("Invalid Name field!");
  document.contactform.inputName.focus();
  return false;
 }
 
 var email=document.contactform.inputEmail.value;
 //var email_exp=/^[A-Za-z0-9\.-_\$]+@[A-Za-z]+\.[a-z]{2,4}$/;
 var email_exp=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
 if(email=='')
 {
  alert("Please Enter Email-Id!");
  document.contactform.inputEmail.focus();
  return false;
 }
 else if(!email.match(email_exp))
 {
  alert("Invalid Email ID !");
  document.contactform.inputEmail.focus();
  return false;
 }
 
 
 var message=document.contactform.inputMessage.value;
 if(message=='')
 {
  alert("Query Field Should Not Be Empty!");
  document.contactform.inputMessage.focus();
  return false;
 }


 var subject = document.contactform.inputSubject.value;
 if(subject=='')
 {
  alert("Subject Should Not Be Empty!")
  document.contactform.inputSubject.focus();
  return false;
 }

    return true;
 }


Place the javascript file in the "C:\xampp\htdocs\your_site\email".

Now you can send the mails using your contact form.

Hope that helps,
Thank You.

Reference : https://github.com/Synchro/PHPMailer