Site icon TestingDocs.com

Create Excel sheets with JXL API Code Example

Overview

In this post, we will discuss creating excel sheets with JXL API Code Example. It is very useful in automation. Creating , reading and writing excel files is very common in automation. In this example, let us create an excel file and add some sample movies list to the excel sheet. Also, this exercise and code example is just to demonstrate the capability with the API. Furthermore, having sound knowledge of API helps in writing robust excel automation code.

 

Simple Code Example below:


public class JExcelExample {

 public static WritableWorkbook writableWorkbook;
 public static WritableSheet writableSheet;
 int i= 0;
    
 public JExcelExample(String filename)
 {
     try{
         System.out.println("*******Creating excel file********");
         writableWorkbook = Workbook.createWorkbook(new File(filename));
           }
     catch(Exception e){
        e.printStackTrace();
     }
 }
    
 public void writeToCell(String sheetName,String cellData) throws WriteException, IOException
     {
     if(writableWorkbook.getSheet(sheetName) == null){
         writableSheet = writableWorkbook.createSheet(sheetName, 0);
           }
     
     Label label = new Label(0,i++,cellData);
     try {
          writableSheet.addCell(label);
      } 
     catch (Exception ex) {
       ex.printStackTrace();
         }
  }
    
 public void close()
 {
  try {
          writableWorkbook.write();
           writableWorkbook.close();
           System.out.println("*******Close : The End ********");
        } 
        catch (Exception ex){
            ex.printStackTrace();
        }
    }
    
    
    public static void main(String... args) throws WriteException, IOException
    {
        JExcelExample jxl = new JExcelExample("TDoc.xls");
        System.out.println("*******Adding Movies List ********");
        jxl.writeToCell("MoviesList","MovieName");
        jxl.writeToCell("MoviesList","Mission Impossible");
        jxl.writeToCell("MoviesList","Titanic");
        jxl.close();
    }
}

 

 

Output of the program

*******Creating excel file********
*******Adding Movies List ********
*******Close : The End ********

 

 

writableWorkbook.getSheet(sheetName) == null

The above line of code checks, if the sheet is already present in the file. If not, it will create the sheet in the excel file. Furthermore, we can have a look at the JXL API Javadoc to efficiently write excel automation.

Exit mobile version