how to insert a date field in excel sheet using jexcel

how to insert a date field in excel sheet using jexcel

Previous Home Next

 

In this example we are going to see how we can add a date field to the excel file using the JExcel Api. 

For adding the date field to an excel worksheet via jexcel you have to import the jxl.write.DateTime class and jxl.write.DateFormats class as well as java.util.Date class.
 In the given example we have called the costructor  of the DateTime class. In that constructor we have passed the value of column, row and the Date() object and the WritableCellFormat object. 

This code shown below will add a date field to your worksheet in the workbook that you have created.

 

package r4r.co.in;

import java.io.IOException;
import java.io.File;
import jxl.Workbook;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.Label;
import jxl.write.DateTime;
import jxl.format.*;
import jxl.write.DateFormats;
import java.util.Date;

public class InsertDateInWorkbook {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException, WriteException{
		// TODO Auto-generated method stub

	try
	{
		WritableWorkbook workbook=Workbook.createWorkbook(new File("F:/JAVA PROJECTS/Jexcel/src/r4r/co/in/firstsheet.xls"));
	    WritableSheet sheet=workbook.createSheet("mysheet", 0);
        WritableFont wfobj=new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD);
	    WritableCellFormat cfobj=new WritableCellFormat(wfobj);
	    cfobj.setBackground(Colour.PINK);
	    
	    cfobj.setWrap(true);
	    
	    Label lblDate = new Label(3,0,"Date",cfobj);
	    WritableCellFormat cf1=new WritableCellFormat(DateFormats.FORMAT9);
	    sheet.addCell(lblDate);
	    DateTime dt=new DateTime(3,1,new Date(), cf1);
	    sheet.addCell(dt);
	    workbook.write();
	    workbook.close();
	}
	catch(IOException e)
	{
		e.printStackTrace();
	}
	catch(WriteException e)
	{
		e.printStackTrace();
	}
	}

}


Previous Home Next