Skip to main content

apache poi example

what is apache poi?
 Apache POI is a Java library to work with different Microsoft Office file formats such as Excel, Power point, Visio, MS Word etc.

 Lets take an example.

 Java JDK 1.5 or above,apache poi latest jar,mysql connector jar and eclipse.

 create a table name it city and insert two data example:

 create table `city` (

 `id` bigint (20),

 `city_id` varchar (12),

 `city_name` varchar (60)


 insert into `city` (`id`, `city_id`, `city_name`) values('1','KOL','Kolkata');

 insert into `city` (`id`, `city_id`, `city_name`) values('2','SIL','Siliguri');

 Now create a java project in eclipse and write a class where data retrieve from database and create a excel file to show the data.

 package com.test;


 import java.sql.Connection;

 import java.sql.DriverManager;

 import java.sql.PreparedStatement;

 import java.sql.ResultSet;

 import java.sql.SQLException;

 import java.util.ArrayList;

 import java.util.List;

 import org.apache.poi.hssf.usermodel.HSSFCellStyle;

 import org.apache.poi.hssf.usermodel.HSSFFont;

 import org.apache.poi.hssf.usermodel.HSSFSheet;

 import org.apache.poi.hssf.usermodel.HSSFWorkbook;

 import org.apache.poi.hssf.util.HSSFColor;

 public class PoiExample {


 * @param args


 public static void main(String[] args) {

 PoiExample poiex=new PoiExample();

 byte[] outputByte =poiex.getExcel();

 OutputStream outt = new ByteArrayOutputStream() ;

 try {




 } catch (Exception e) {



 public Connection getConnection()


 Connection connect=null;



 // Setup the connection with the DB

 connect = DriverManager


 + "user=root&password=root");

 }catch (Exception e) {

 // TODO: handle exception


 return connect;


 public byte[] getExcel()


 List<City> cityList=new ArrayList<City>();

 City city=null;

 Connection connection = getConnection();

 PreparedStatement pst = null;

 ResultSet rs = null;

 String query = null;

 try {

 query = " select * from city ";

 pst = connection.prepareStatement(query);

 rs = pst.executeQuery();

 while ( {

 city = new City();





 } catch (Exception e) {


 } finally {

 try {


 } catch (SQLException e) {

 // TODO Auto-generated catch block




 FileOutputStream outputStream = null;

 HSSFWorkbook wb=new HSSFWorkbook();

 HSSFSheet sheet = wb.createSheet("City");

 boolean returnValue = true;

 ByteArrayOutputStream bos=null;

 String currentfilename=null;

 //////////////////////Excel Header Style/////////////////////////

 HSSFCellStyle headerlabelcs = wb.createCellStyle();





 HSSFFont headerlabelfont = wb.createFont();






 //////////////////////Excel Header Style/////////////////////////

 //////////////////////Excel Error Style/////////////////////////

 HSSFCellStyle errlabelcs = wb.createCellStyle();





 HSSFFont errlabelfont = wb.createFont();





 //////////////////////Excel Header Style/////////////////////////

 //////////////////////Excel Success Style/////////////////////////

 HSSFCellStyle successlabelcs = wb.createCellStyle();





 HSSFFont successlabelfont = wb.createFont();





 //////////////////////Excel Header Style/////////////////////////

 int rowIndex = 0;


 sheet.getRow(rowIndex).createCell(0).setCellValue("City Id");


 sheet.getRow(rowIndex).createCell(1).setCellValue("City Name");


 try {

 for(City ci: cityList){






 //Automatically Column Size Set

 for (short col = 0; col < 10; col++)sheet.autoSizeColumn((short)col);

 bos = new ByteArrayOutputStream();


 outputStream = new FileOutputStream("city.xls");


 wb = null;


 } catch (Exception e) {

 System.out.println("error="+rowIndex+" "+e.getMessage());

 returnValue = false;



 return bos.toByteArray();




 package com.test;

 public class City {

 public String id;

 public String city_name;

 public String getId() {

 return id;


 public void setId(String id) { = id;


 public String getCity_name() {

 return city_name;


 public void setCity_name(String city_name) {

 this.city_name = city_name;



 Now run the project and refresh the project .


Popular posts from this blog

jdbc mysql example in java

Here’s an example to show you how to connect to MySQL database via a JDBC driver.To connect to MySQL from Java, you have to use the JDBC driver from MySQL. You find the latest MySQL JDBC driver under the following URL:
Create a example database and named it test.Now create a a table name it user. Create table user ((userid INT NOT NULL AUTO_INCREMENT,
username VARCHAR(30) NOT NULL, PRIMARY KEY (userid)); Now add the record in your table; Now create a project in eclipse and mysql-connector jar in its classpath.package com.test;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; publicclass JavaJDBCExample { private Connection connect = null; private Statement statement = null; private ResultSet resultSet = null; publicvoid readDatabase() { try { // this will load the MySQL driver Class.forName("com.mysql.jdbc.Driver"); // setup the connection wi…

singleton design pattern

Java Singleton design pattern is one of the design pattern which suggest that only one instance of a Singleton object is created by the JVM. This is useful when exactly one object is needed to coordinate actions across the system Example: public class Singleton{ privatestatic Singleton singleton = null; private Singleton(){ } publicstaticsynchronized Singleton getInstance( ) { if(singleton == null) { singleton = new Singleton(); } returnsingleton; } publicvoid test( ) { System.out.println("test"); } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub returnnew CloneNotSupportedException(); } } publicclass SingletonTest { publicstaticvoid main(String[] args){ Singleton singleton = Singleton.getInstance(); try{ Singleton

jaxb example

Download <strong>eclipselink.jar</strong>,

 Create a java project and add a class in it.Now create a properties file




 package pck;

 import javax.xml.bind.JAXBContext;

 import javax.xml.bind.Marshaller;

 import javax.xml.bind.annotation.XmlElement;

 import javax.xml.bind.annotation.XmlRootElement;

 import net.sf.json.JSONException;

 @XmlRootElement (name="Person")

 public class Person {

 @XmlElement (name="age")

 public int age;

 @XmlElement (name="name")

 public String name;

 public static void main(String[] args) throws JSONException, Exception {

 Person me = new Person();

 me.age = 27; = "Biswajit";


 JAXBContext jc = JAXBContext.newInstance(Person.class);

 Marshaller marshaller = jc.createMar…