Java - Creating an MS Excel File using Jakarta POI api


/* CreateXLFile.java*/





import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;




/**
 *
 * @author dhanoopbhaskar
 */
public class CreateXLFile {
   
    HSSFWorkbook xlWorkbook = null;
    HSSFSheet xlSheet = null;
    HSSFRow xlRow = null;
    HSSFCell xlCell = null;
    FileOutputStream xlFileOutputStream = null;
   
    public CreateXLFile() {
        /**
         * creating a new MS Excel work book
         */
        xlWorkbook = new HSSFWorkbook();
        /**
         * creating a new sheet named "my first sheet" in the above created
         * work book
         */
        xlSheet = xlWorkbook.createSheet("my first sheet");
        /**
         * creating a new row at index 0 in the new sheet
         */
        xlRow = xlSheet.createRow(0);
        /**
         * creating a new cell/column in the row 0
         * the index required is of type short and so it has been type casted
         * to short
         */
        xlCell = xlRow.createCell((short) 0);
        /**
         * setting the type of data that can be accommodated in the cell
         * CELL_TYPE_STRING is a public static final int variable in the class
         * HSSFCell.
         */
        xlCell.setCellType(HSSFCell.CELL_TYPE_STRING);
        /**
         * setting the content of the cell as "IT @ UCET"
         */
        xlCell.setCellValue("IT @ UCET");
        /**
         * The so created instance of HSSFWorkbook is converted to a file using
         * the method write() in HSSFWorkbook.class passing the file output stream
         * of the file as the parameter.
         */
        try {
            xlFileOutputStream = new FileOutputStream("myexcelfile.xls");           
            xlWorkbook.write(xlFileOutputStream);           
            /**
             * Note: I couldn't find the need to flush and close the stream,
             * that we usually do. So it can be concluded that the API provider
             * performs the task already.
             *
             * xlFileOutputStream.flush();
             * xlFileOutputStream.close();
             */           
            System.out.println("Your First Excel File has been successfully created!");
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }       
    }
   
    public static void main(String[] args) {
        new CreateXLFile();
    }
}












NB: To compile and run the above program you need to download the jakarta-poi api. You can download from here...





Post a Comment

0 Comments