Friday, March 23, 2018

Most Popular Programming Languages between 1988 and 2018

Here is a list of the most popular programming languages in the last 30 years, published by the tiobe.com website. Note that these are the average positions for a period of 12 months. TIOBE website suggests visitors to inform site managers if there is a shortage. In case you can notice that there is a suggestion, and you can contact them at tpci@tiobe.com.






Sunday, January 31, 2016

TIOBE programming languages ranking between 1985 and 2015

Here is a list of the most popular programming languages in the last 30 years, published by the tiobe.com website. Note that these are the average positions for a period of 12 months. TIOBE website suggests visitors to inform site managers if there is a shortage. In case you can notice that there is a suggestion, and you can contact them at tpci@tiobe.com.

tiobe programming langage rank 1985-2015

References:
http://www.javacademia.com/2015/08/classement-tiobe-des-langages-de-programmation-1985-2015.html

Monday, January 25, 2016

Java - How to generate random alpha-numeric strings

In this tutorial, we will show you how to get a random string using three methods in the examples bellow. Generation of random characters in Java does not exist, but there are several ways to do that. We will use java.util.Random.nextInt () method to generate random integers and then convert those integers to the conrresponding character according to the ASCII code.

Generate type character

The ASCII code of the first character is lowercase alphabetic 65 (a) and the last is 97 + 26 = 122 (z). The generated number is in the interval [97, 122] or in the range [0.26] + 97.

Random rand = new Random();
char c = (char)(rand.nextInt(26) + 97);
System.out.println(c);

Generate random string

For n characters, you need to use for loop:

public static void main(String[] args) {

   Random rand = new Random();
   String str="";
   for(int i = 0 ; i < 15 ; i++){
       char c = (char)(rand.nextInt(26) + 97);
       str += c;
       System.out.print(c+" ");
   }
}
q v r i v g z a w b b d n x y 

Generate alpha-numeric string from a set

This example show how to generate alphanumeric characters from a defined set of characters. Proceed as follows:
  • Create a String with all that you want
  • Get the length of this string
  • Call Rand.nextInt() method that returns the random length between 0 and n.
  • Print out the char using alphabet.charAt (k) method

Random rand = new Random();
String set = "abcd1235";
int length = set.length();
for(int i = 0; i < 20; i++) {
   int k = rand.nextInt(length);
   System.out.print(set.charAt(k)+" ");
}
d 5 1 b 1 b 2 3 c a b b 5 5 d d b 2 c 3 
References:
How to generate a random String in Java
Java doc: java.util.Random class
Extended ascii code

Java array sort in ascending and descending order

In this tutorial, we will study the methods of sorting a table in the ascending and descending order in Java. We'll show you how to use the sort () method to perform the sorting task.

Several methods in Java allow you to sort your tables and use these methods of sorting tables, you will primarily import a library named Arrays. You do it with the keyword import:

import java.util.Arrays;
Here is an example:

import java.util.Arrays;

public class ArraysTest {

   public static void main(String[] args) {

   // array init
   int array[] = {11,87,14,5,63,24};

   // display all the elements before sorting
   for (int value : array) {
      System.out.println("number: " + value);
   }

   // Call Arrays.sort() method
   Arrays.sort(array);

   // display all the elements after sorting
   System.out.println("Sorted array\n");
   for (int value : array) {
      System.out.println("number: " + value);
   }
   }
}
After complilation and execution, we should get that result:

number: 11
number: 87
number: 14
number: 5
number: 63
number: 24
Sorted array

number: 5
number: 11
number: 14
number: 24
number: 63
number: 87

Sort array in descending order

Sorting in descending order is only possible if you write your own code or convert the array into an array of objects, then import collections librairy and call Collections.sort() method. This method sort the array in the ascendeng order, to sort it in the descending order, we call reverse() method that should reverse the result array.

import java.util.Arrays;
import java.util.Collections;

public class ArraysTest {

   public static void main(String[] args) {

   // array init
   int array[] = {11,87,14,5,63,24};

   // display all the elements before sorting
   for (int value : array) {
      System.out.println("number: " + value);
   }

   //create array of integer to store integer objects
   Integer[] integerArray = new Integer[array.length];
   for (int i=0; i < array.length; i++) {
    //create an new integer object and store it
    integerArray[i] = new Integer(array[i]);
   }
  
   // sort the array then inverse it using reverseOrder() method
   Arrays.sort(integerArray, Collections.reverseOrder());

   // display all the elements after sorting
   System.out.println("Sorted array\n");
   for (int value : integerArray) {
      System.out.println("number: " + value);
   }
   }
}
Let us compile and run this program:

number: 11
number: 87
number: 14
number: 5
number: 63
number: 24
Sorted array

number: 87
number: 63
number: 24
number: 14
number: 11
number: 5
References:
Java.util.Arrays.sort(int[]) Method

How to loop over HashMap in Java

In this tutorial, we will show you how to iterate over each entry in HashMap using two methods to display all elements of an HashMap in Java:
  1. Advanced for loop or for each
  2. Iterator + while loop 
In the example below, we are using for loop and iterator with while loop to print out elements:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class IterateHashMap{
 
    public static void main(String[] args) {

        HashMap<String, Integer> map = new HashMap<String, Integer>();

        map.put("A",1);
        map.put("B",2);
        map.put("C",3);
        map.put("D",4);
        
        //for each loop
        System.out.println("for each:");
        for (Map.Entry mapentry : map.entrySet()) {
           System.out.println("key: "+mapentry.getKey() 
                              + " | value: " + mapentry.getValue());
        }

        //iterator and while loop
        System.out.println("Iterator + while loop");
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
          Map.Entry mapentry = (Map.Entry) iterator.next();
          System.out.println("key: "+mapentry.getKey()
                            + " | value: " + mapentry.getValue());
        } 
    }
}
Execution:

Boucle for:
Key: D | value: 1
Key: A | value: 2
Key: B | value: 3
Key: C | value: 4
Boucle while
Key: D | value: 1
Key: A | value: 2
Key: B | value: 3
Key: C | value: 4
In both cases, we get a set map of key-value data in the object Map.Entry. In for loop, we used entrySet () method of the Map class. In the while loop, was recovered an Iterator object and after obtaining all key-value, then we cast Map.Entry to print the keys and values with both getKey () and getValue () method.

References:
Iterate through a HashMap

How to sort ArrayList in ascending/descending order in Java

Elements in ArrayList are displayed in the order of their inclusion in the list by defalut, but sometimes we need to iterate through the ArrayList to display elements in ascending or descending order. In this tutorial, we will implement a code that use Collections.sort () method that makes sorting a Arraylist in ascending and descending order.

Sort ArrayList in ascending order

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListAscendingOrder {

   public static void main(String[] args) {
      ArrayList unsorted = new ArrayList();
      unsorted.add("Ee");
      unsorted.add("5a");
      unsorted.add("c8");
      unsorted.add("41");
      unsorted.add("09");
  
      System.out.println("Before sort");
      for(int i=0; i < unsorted.size(); i++)
        System.out.println(unsorted.get(i));
  
      System.out.println("\nAfter sort");
      Collections.sort(unsorted);
      for(int i=0; i < unsorted.size(); i++)
        System.out.println(unsorted.get(i));
   }
}
Execution:

Avant le tri
Ee
5a
c8
41
09

Après le tri
09
41
5a
c8
Ee

Sort ArrayList in descending order

The Collections class has another method Collections.sort (List <T>, Comparator <T>). This method sort an ArrayList in both ascending and descending order. sort() method uses a comparator of objects that compare two objects using compareTo() method.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayListDescendingOrder{

   public static void main(String[] args) {
      ArrayList unsorted= new ArrayList();
      unsorted.add("000");
      unsorted.add("110");
      unsorted.add("101");
      unsorted.add("100");
      unsorted.add("111");
  
      System.out.println("Before sort");
      for(int i=0; i < unsorted.size(); i++)
        System.out.println(unsorted.get(i)+" ");
  
      System.out.println("\nAfter sort");

      Collections.sort(unsorted, new Comparator() {
            @Override
            public int compare(String  s1, String  s2)
            {
                /*to get the descending order, we shall compare s2 with s1
                return s2.compareTo(s1);
            }
      });
      for(int i=0; i < unsorted.size(); i++)
        System.out.println(unsorted.get(i)+" ");
   }
}
Execution:

Avant le tri
000
110
101
100
111

Après le tri
111
110
101
100
000

Rerefences:
stackOverFlow:How to sort a ArrayList in java
How to sort ArrayList in Java - BeginnersBook

Saturday, January 9, 2016

How to loop over ArrayList in Java

Iterate an ArrayList in Java is done by using three loops:
  • The for loop
  • The while loop or do..while
  • The while+iterator loop
The example below show how to use the three methods mentioned.

import java.util.ArrayList;
import java.util.Iterator;

public class main{

 public static void main(String[] args) {
  
  ArrayList arraylist = new ArrayList();

  arraylist .add(1);
  arraylist .add(2);
  arraylist .add(3);
  
  System.out.println("for loop");
  for(int i = 0 ; i < arraylist .size(); i++)
   System.out.println(arraylist .get(i));
  
  System.out.println("Advanced for loop");
  for(Integer n : arraylist)
   System.out.println(n);
  
  System.out.println("while+iterator loop");
  int i = 0;
  while(i iterator = arraylist.iterator();
  while(iterator.hasNext())
   System.out.println(iterator.next());
 }
}
Compilation and execution:

for loop
1
2
3

Advanced for loop
1
2
3

while+iterator loop
1
2
3

How to browse an ArrayList using the Enumeration interface

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

public class main{

  public static void main(String[] args) {
  
     ArrayList alist = new ArrayList();

     alist.add("a");
     alist.add("b");
     alist.add("c");

     // get Enumeratioin object
     Enumeration enumeration = Collections.enumeration(alist);
  
     // iterate
     while(enumeration.hasMoreElements())
        System.out.println(enumeration.nextElement());
  }
}
After compilation and execution of this code:

a
b
c

How to save/read an ArrayList to/from file in Java

Java provides a mechanism where an object can be represented as a sequence of bits that contains the data of this object and this information: type, and the types of data stored in the object.

After the serialized object has been well recorded in the file, it can be read without problems from the file and then deserialize. The bits that represent the object and its data can be used to recreate the object in memory.

The ObjectInputStream and ObjectOutputStream classes are two high-level data stream that contain the methods for recording and reading the contents of an ArrayList from a file.

ArrayList is serializable by default. This means that you do not need to implement Serializable in order to serialize an ArrayList.

Write ArrayList to file in Java

This class creates a test file that will have an ArrayList object as a stream of bits. The test file is used to save and recreate the object from bitstream. Note that we do not implement Serializable in this example because ArrayList is already serialized by default.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class SerializeArrayList {

  public static void main(String[] args) {
     ArrayList arraylist=new ArrayList();
     arraylist.add("hello world");
     
     try {
       FileOutputStream fileOut = new FileOutputStream("file");
       ObjectOutputStream out = new ObjectOutputStream(fileOut);
       out.writeObject(arraylist);
       out.close();
       fileOut.close();
       System.out.println("\nSerialization completed successfully...\n");
 
     } catch (FileNotFoundException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     }
  }
}
After compilation and execution:

Serialization completed successfully

Read and create an ArrayList from file

In this class, one recovers the data stream in the form of bits from the test file that was stored using the class above. We converted the returned object in ArrayList with the cast and shows the ArrayList elements. By observing the output, we obtain the same elements which are added to the list before serialization.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class main{

  public static void main(String[] args) {

    ArrayList<String> arraylist= new ArrayList<String>();
    try {
      FileInputStream fileis = new FileInputStream("file");
      ObjectInputStream ois = new ObjectInputStream(fileis);
      arraylist = (ArrayList) ois.readObject();
      ois.close();
      fileIn.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
       e.printStackTrace();
    }

    System.out.println("Reading data: \n");
    for(String o:arraylist)
      System.out.println(o);
  }
}

After compilation and execution:

hello world

Sunday, August 2, 2015

How to convert java ArrayList to array

In this tutorial we will see how to get an array from ArrayList using Java.util.ArrayList.toArray() Method.

This method return an array that contains all the elements of ArrayList.

Example

import java.util.ArrayList;

public class toArray {

 public static void main(String[] args) {
  
  ArrayList list = new ArrayList();

  list.add("aa");
  list.add("bb");
  list.add("cc");
  
  String[] array = new String[list.size()];
  list.toArray(array);
  
  for(int i = 0 ; i < array.length; i++)
   System.out.println(array[i]);

 }
}
Output:
aa
bb
cc

Friday, July 24, 2015

Java - ArrayList constructors and methods example

ArrayList is a dynamic array that implements the List interface that is a sorted collection that the user of this interface has total control over the inserted elements and position by accessing and searching for items in the list.

ArrayList implements all methods List, more than that, the class has its own methods such as manipulating the size of the array used to store the list. This class is equivalent to Vector.
Arraylist uses an array that stores data, this table has a capability that automatically adapts to each time an item is inserted. There is a ensureCapacity method that increases the capacity of ArrayList before adding many elements to ensure the size.

Access to the list is made simultaneously by multiple threads. This can cause problems when it comes to a change, insert, delete because another thread will access and update the size of the list is underway. The solution is synchronization process using the Collections.synchronizedList method.

List list = Collections.synchronizedList(new ArrayList(...));

To browse the list with the iterator class or ListIterator, but if the list has changed: delete, insert ... after creating iterator, it will trigger a ConcurrentModificationException exception. The solution is to create a mutual exclusion with the aim to prevent other threads to access it after creating iterator and during playback.

ArraylList Consturctors

ArrayList three manufacturer:

- ArrayList (): creates an empty list with an initial size of 10.
- ArrayList (<? Extends E> Collection c) Creates a list from a collection of data and returns a NullPointerException if the collection is zero.
- ArrayList (int size) Creates a list by setting the initial size and returns an IllegalArgumentException if size is negative.

ArrayList Methods

1) add(Object o): add element in the end.
list.add("hello");

2) add(int indice, Object o): insert element in the middle
list.add(2, "hi");
It insert the string in the second position of the list.

3) addAll(Collection c): add a collection to the list.
ArrayList toadd = new ArrayList();
l1.add("e1");
l1.add("e2");
l1.add("e3");
list.addAll(toadd);
This operation add a list toadd to the end of the list.

4) addAll(int indice, Collection c): insert a collection c in the middle
list.addAll(3, l1);
this method insert the collection l1 in the fourth position of the list.

5) clear(): remove all elements from the list.

6) contains(Object o): return true if the searched object o is in the list.
boolean b = list.contains(o)

8) ensureCapacity(int capacite): set and ensure the minimum capacity.
list.ensureCapacity(8);
This will ensure at least 8 elements.

9) get(int index): return object at the specific position.
system.out.println(list.get(3));
This will print the object at the third position.

10) indexOf(Object o): search and return the first occurrece of object o.
int k = indexOf("o2");

11) isEmpty(): if the list is empty, this method return true.
boolean empty = list.isEmpty();

12) remove(Object o): remove the first occurrence of object o.
boolean b = list.remove("o3");
This wil return true if the object o3 is found and deleted with success.

13) removeAll(Collection<?> c): remove all elements that belong to collection c.
AarrayList<String> c = new ArrayList<String>();
c.add("o1");
c.add("o2");
c.add("o3");
list.removeAll(c);

14) removeRange( int startIndex, int endIndex): remove elements between startIndex and endIndex.
list.removeRange(4,7);
This method remove elements between 4 and 7.

15) retainsAll(Collection<?> c):  retain only elements that belong to collection c.

16) set(int index, Object o): set object value in a specific index.
list.set(2, "o4");
object in position 2 has been replaced with value "o54.

17) size(): return the arralist size.

18) subList(int startIndex, int endIndex): return a sublist that belong between startIndex and endIndex.

19) toArray(): create an array from ArrayList.
String[] t = list.toArray();
Result array contains all elments of ArrayList. This method is usefull when you use a method that accept only array type argument.

20) trimToSize(): reduce the storage capacity to its miminum.

How to iterate through ArrayList

We can use two methods:

1) for loop

for(int i = 0; i < list.size(); i++)
    system.out.println(list.get(i));
//if we use generic type. In this example an Integer (ArrayList<Integer>)
for(Integer digit: list)
    system.out.println(digit);

2) Iterator+ while loop

Iterator itr = list.iterator();
while(itr.hasNext())
      system.out.println(itr.next());

ArrayList Exemple

import java.util.ArrayList;

public class Test {

 public static void main(String[] args) {
  
  //create ArrayList with generic string type
  ArrayList<String> stringList= new ArrayList<String>();
  //add elements to arraylist
  stringList.add("e1");
  stringList.add("e2");
  stringList.add("e3");
  stringList.add("e4");
  stringList.add("e5");

  //operations example
  System.out.println("e1 exist ? "+stringList.contains("o3"));
  System.out.println("index of "+"o2: "+stringList.indexOf("o2"));
  System.out.println("e5 is deleted: "+stringList.remove("o2"));
  System.out.println("arraylist size: "+stringList.size());
  System.out.println("sublist[0, 2] : "+stringList.subList(0, 2));
  
  //loop arraylist
  for(String s : stringList)
     System.out.println(s);

  stringList.clear();
  System.out.println("is empty ? "+stringList.isEmpty());
 }
}
Output:
e1 exist ? false
index of o2: -1
e5 is deleted: false
arraylist size: 5
sublist[0, 2] : [e1, e2]
e1
e2
e3
e4
e5
is empty ? true

Java socket programming: create client/server chat application

In this tutorial you will learn how to create a java chat between two hosts using sockets, as well as your network configuration in order to communicate two machines on the local network of your home for example. We will implement what we saw in theory: Client / Server model.

At the end of this tutorial you will be able to know how sockets can exchange messages.

1- Java Server

The java server initiates the connection and launches listening on a port and waits for incoming connections to accept. For example, the port number is 5000, the client sends a request to the server with the port number 5000. The server accepts the request and forwarded his information (IP address) to the client. Now connection is established and an exchange of messages can be done.

Java has a java.net package that processes the network, we need only two classes:
  • java.net.ServerSocket: accepts connections goings of clients.
  • java.net.Socket: allows connection to the remote machine.
We also need tools to capture, send and receive the stream:
  • Scanner: read keyboard input.
  • BufferedReader: read the text received from the transmitter.
  • PrintWriter: send the text entered.

ServerSocket serverSocket;
Socket socket;
Final BufferedReader in;
final PrintWriter out;
Final Scanner sc = new Scanner (System.in);
try {
    serverSocket = new ServerSocket (5000);
    serverSocket.accept = ();
    out = new PrintWriter ( .getOutputStream ());
    in = new BufferedReader (new InputStreamReader ( .getInputStream ()));
    String s;
    s = sc.next ();
    System.out.println (s);
    out.flush ();
    String receivedmessage;
    receivedmessage in.readLine = ();
    System.out.println ("Client:" + receivedmessage);
    }
catch (IOException e) {
  e.printStackTrace ();
}

After creating the server socket that carries the port number 5000, the server waits for incoming connections and as soon as one is found, he accepts it. in and out are initialized so that they are directly connected with the sending and receiving streams.
Variable 's' stores the entered text with the next() method, and then sent to the println (s) method.
The flush() method is important because it flushes the write buffer to the output if a null value will be received by the other side.
The receivedmessage variable stores the received message is displayed with println() method.

The limit of this code is that it is able to send and receive a message once. You will have an idea in the head: to make a while loop (true). This is true, but if for example the server sends to the client, the client can not retrieve the message until it has sent also. The optimal solution is to create two threads: one for sending and one for receiving. Both processes allow the sending and receiving are done simultaneously.

java.io.BufferedReader import;
import java.io.IOException;
java.io.InputStreamReader import;
java.io.PrintWriter import;
java.net.ServerSocket import;
java.net.Socket import;
java.util.Scanner import;
/ *
 * javaisback.blogspot.com
 * /
public class Server {

   public static void main (String [] test) {
 
     ServerSocket final serverSocket;
     Socket final clientSocket;
     Final BufferedReader in;
     final PrintWriter out;
     Final Scanner sc = new Scanner (System.in);
 
     try {
       serverSocket = new ServerSocket (5000);
       clientSocket serverSocket.accept = ();
       out = new PrintWriter (clientSocket.getOutputStream ());
       in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
       Thread sending = new Thread (new Runnable () {
          String msg;
          Override
          public void run () {
             while (true) {
                sc.nextLine msg = ();
                System.out.println (msg);
                out.flush ();
             }
          }
       });
       envoi.start ();
 
       Thread receive = new Thread (new Runnable () {
          String msg;
          Override
          public void run () {
             try {
                in.readLine msg = ();
                // As the client is connected
                while (msg! = null) {
                   System.out.println ("Client:" + msg);
                   in.readLine msg = ();
                }
                // Exit the loop if the client connection is ended
                System.out.println ("Client deconected");
                // Close the stream and socket session
                out.close ();
                clientSocket.close ();
                serverSocket.close ();
             } Catch (IOException e) {
                  e.printStackTrace ();
             }
         }
      });
      receive.start ();
      } Catch (IOException e) {
         e.printStackTrace ();
      }
   }
}

The separation of the two processes is clear, the Server and the Client can exchange data at any time and infinitely. The while loop reading tests if the connection is not yet established if not forget to close your streams reading and writing as well as the connection after the exit of the while loop with close() method.

2- Java Client

The client side needs only the Socket class to establish the server connection, the constructor takes as input the server IP address and port number. The rest of the code is the same as that of the server.

java.io.BufferedReader import;
import java.io.IOException;
java.io.InputStreamReader import;
java.io.PrintWriter import;
java.net.Socket import;
java.util.Scanner import;
/ *
 * javaisback.blogspot.com
 * /
public class Client{

   public static void main (String [] args) {
   
      Socket final clientSocket;
      Final BufferedReader in;
      final PrintWriter out;
      Final Scanner sc = new Scanner (System.in); // to read from the keyboard

      try {
         / *
         * Server informations (port and IP address or host name
         * 127.0.0.1 is the host local address
         * /
         clientSocket = new Socket ("127.0.0.1", 5000);
 
         // Flow to send
         out = new PrintWriter (clientSocket.getOutputStream ());
         // Feed to receive
         in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
 
         Thread send = new Thread (new Runnable () {
             String msg;
              Override
              public void run () {
                while (true) {
                  sc.nextLine msg = ();
                  System.out.println (msg);
                  out.flush ();
                }
             }
         });
         send.start ();
 
        Thread receive = new Thread (new Runnable () {
            String msg;
            Override
            public void run () {
               try {
                 in.readLine msg = ();
                 while (msg! = null) {
                    System.out.println ("Server:" + msg);
                    in.readLine msg = ();
                 }
                 System.out.println ("Server deconected");
                 out.close ();
                 clientSocket.close ();
               } Catch (IOException e) {
                   e.printStackTrace ();
               }
            }
        });
        receive.start ();
 
      } Catch (IOException e) {
           e.printStackTrace ();
      }
  }
}

Output:

create java chat server using sockets
Server
create java chat client using sockets
Client
If you work on the same machine you need to run Eclipse twice. one for the server and one for the client.

Saturday, July 18, 2015

Apache POI: How to create, write and read excel file in java

Typically, spreadsheets are widely used in finance domain and accounting to facilitate the calculation and creation of bills, management reports, etc. If part of your required application of such operations: creation, reading or writing, several API are available and most efficient is Apache POI API.

The API also manages POI Word and PowerPoint documents, over time users have had more confidence.

Download Apache POI API

You can download Apache POI. Then, import  the following .jar into your project:
- poi
- poi-OOXML
- poi-OOXML-schemas
- xmlbeans

Create and write

The two main classes which processes the Excel file are:

HSSFWorkbook: for Microsoft Excel 97 and 2003 files with xls extension.
XSSFWorkbook: for Microsoft Excel 2007 with .xlsx file extension.

The following code creates an excel file with the values of different types:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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.xssf.usermodel.XSSFWorkbook;

public class writeDemo{
    public static void main(String[] args) {
   
       //create a blanc document
       XSSFWorkbook wb = new XSSFWorkbook();
       //create a black sheet
       Sheet sheet = wb.createSheet("new sheet");
       //create a new row 0
       Row row = sheet.createRow((short)0);
       //create a new cell
       Cell cell = row.createCell(0);
       //insert value in the created cell
       cell.setCellValue(1.4);
   
       //add other cells with different types
       /*int*/row.createCell(1).setCellValue(7);
       /*int*/row.createCell(2).setCellValue(99);
       /*string*/row.createCell(3).setCellValue("string");
       /*boolean*/row.createCell(4).setCellValue(true);

       FileOutputStream fos;
       try {
         fos= new FileOutputStream("newFile.xlsx");
         wb.write(fos);
         fos.close();
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
}
create excel file with java

The date to be inserted and the current time, the date format is created as follows:

//insert value in cell F1
cell = row.createCell((short) 6);
cell.setCellValue(new Date());
XSSFCellStyle cellStyle = wb.createCellStyle();
XSSFDataFormat xssfDataFormat = wb.createDataFormat();
//create date and time format
cellStyle.setDataFormat(xssfDataFormat.getFormat("dd/mm/yyyy h:mm"));
cell.setCellStyle(cellStyle);
insert date in excel file with java

Text Formatting

Text formatting includes: font, size, Italic / Bold / Underline, color, background and alignment.

Here is an example of alignment that will be applied to the cell Date:

//Row high
row.setHeightInPoints(20);
//horizontal alignement 
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
//vertical alignement
cellStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
text formating excel java

Create new font

/*create a new font*/
Font font = wb.createFont();
//size: 13px
font.setFontHeightInPoints((short)13);
font.setFontName("Courier New");
font.setItalic(true);
font.setBold(true);

/*create a new style*/
CellStyle cs = wb.createCellStyle();
cs.setFont(font);
//apply the style to cell 3(D1)
row.getCell(3).setCellStyle(cs);
change the excel font with java

Background color

/*change the background color*/
XSSFCellStyle csColor = wb.createCellStyle();
csColor.setFillForegroundColor(new XSSFColor(new Color(194, 154, 250)));
csColor.setFillPattern(csColor.SOLID_FOREGROUND);
//apply to the cell 3
row.getCell(2).setCellStyle(csColor);
        
/*change font color*/
Font font = wb.createFont();
font.setColor((short)45);
CellStyle csCF = wb.createCellStyle();
csCF.setFont(font);
//apply style to cell 0
row.getCell(0).setCellStyle(csCF);
change background color excel with java

Merging cells

In this example, we will merge, center horizontally and vertically four cells B2, C2, B3 and C3 with the addMergedRegion method that takes as parameters the range of cells to be fused.

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.CellRangeAddress;

public class mergingCells{

   public static void main(String[] args) throws FileNotFoundException {
       Workbook wb = new HSSFWorkbook();
       Sheet sheet = wb.createSheet("sheet1");

       Row row = sheet.createRow((short) 1);
       Cell cell = row.createCell((short) 1);
       cell.setCellValue("testing merge cells");

       sheet.addMergedRegion(new CellRangeAddress(
             1, //first row B2
             2, //last row B3
             1, //first column C2
             2  //last column C3 
       ));
       /*Center alignment*/
       cell.getCellStyle().setAlignment((short)2);
       cell.getCellStyle().setVerticalAlignment((short)1);
     
       FileOutputStream fs = null;
       try {
         fs = new FileOutputStream("Mergingdemo.xlsx");
         wb.write(fs);
         fs.close();
       } catch (IOException e) {
          e.printStackTrace();
       }
   }
}
merge cells in excel with java

Using Formulas

Excel is primarily used in the calculation and use of sometimes complex formulas in cells result. Apache poi provides a very effective means to add and test cells with their formulas.

The following code handles a simple calculation of the average 4 semesters. The formula is (A2 + B2 + C2 + D2) / 4.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class FormulaDemo{

  public static void main(String[] args) {
     XSSFWorkbook wb = new XSSFWorkbook();
     XSSFSheet sheet = wb.createSheet("Average");

     Row row = sheet.createRow((short) 0);
     row.createCell(0).setCellValue("January");
     row.createCell(1).setCellValue("February");
     row.createCell(2).setCellValue("March");
     row.createCell(3).setCellValue("April");
     row.createCell(4).setCellValue("Average");
     
     Row row1 = sheet.createRow((short) 1);
     row1.createCell(0).setCellValue(4.5);
     row1.createCell(1).setCellValue(15.4);
     row1.createCell(2).setCellValue(3.4);
     row1.createCell(3).setCellValue(6);
     row1.createCell(4).setCellFormula("(A2+B2+C2+D2)/4");

     try {
         FileOutputStream out = new FileOutputStream(new File("formulademo.xlsx"));
         wb.write(out);
         out.close();
         System.out.println("Le fichier excel a été créé avec succés");
           
     } catch (FileNotFoundException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }
  }
}
using formula in excel with java

Evaluate and browse cells

To view the value of a cell, you must know its type. Apache poi provides FormulaEvaluator.evaluateFormulaCell class that checks if the cell contains a formula. If so, it evaluates and returns the type of the formula.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class IterateDemo{

    public static void main(String[] args) throws IOException {
       FileInputStream fichier = new FileInputStream(new File("formuladomo.xlsx"));
       //create workbook instance that refers to xlsx file
       XSSFWorkbook wb = new XSSFWorkbook(fichier);
       XSSFSheet sheet = wb.getSheetAt(0);
  
       FormulaEvaluator formulaEvaluator = 
                     wb.getCreationHelper().createFormulaEvaluator();
  
       for (Row ligne : sheet) {//iterate rows
         for (Cell cell : ligne) {//iterate columns
           //cell type
           switch (formulaEvaluator.evaluateInCell(cell).getCellType())
           {
                 case Cell.CELL_TYPE_NUMERIC:
                     System.out.print(cell.getNumericCellValue() + "\t\t");
                     break;
                 case Cell.CELL_TYPE_STRING:
                     System.out.print(cell.getStringCellValue() + "\t");
                     break;
           }
         }
         System.out.println();
       }  
    }
}
Execution:

January February March April Average
4.5  15.4  3.4  6.0  7.325 
For more informations read from apache documentation http://poi.apache.org/spreadsheet/quick-guide.html