Searching...
Tuesday, 26 November 2013

How to create Excel file using JExcel

09:43

JExcel is an open source API that allows to create and modify Excel documents in java. In this example we will see how to create a simple Excel file and adding values using JExcel.

1. Create a Maven project and add below dependency.

                  <dependency>
			<groupId>net.sourceforge.jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.6.12</version>
		</dependency>

2. Create a Main program to create Excel file

package com.pretech;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Workbook;
import jxl.write.Boolean;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class JExcelSimpleExample {
	public static void main(String[] args) {
		WritableWorkbook workbook;
		try {
			//Creating WorkBook
			workbook = Workbook.createWorkbook(new File("JExcelExample.xls"));
			//Creating sheet
			WritableSheet sheet = workbook.createSheet("STUDENT_DETAILS", 0);
			//Addding cells
			sheet.addCell(new Label(0, 0, "STUDENT_ID"));
			sheet.addCell(new Label(1, 0, "STUDENT_NAME"));
			sheet.addCell(new Label(2, 0, "STUDENT_AGE"));
			sheet.addCell(new Label(3, 0, "EHS"));
			sheet.addCell(new Label(0, 1, "01"));
			sheet.addCell(new Label(1, 1, "SHIVA"));
			sheet.addCell(new Number(2, 1, 12));
			sheet.addCell(new Boolean(3, 1, true));
			sheet.addCell(new Label(0, 2, "02"));
			sheet.addCell(new Label(1, 2, "SANTHOSH"));
			sheet.addCell(new Number(2, 2, 11));
			sheet.addCell(new Boolean(3, 2, false));
			//Getting cell values
			Cell cell1 = sheet.getCell(0,1); 
		    Cell cell2 = sheet.getCell(1,1); 
		    Cell cell3 = sheet.getCell(2,1); 
		    Cell cell4 = sheet.getCell(3,1); 
		    
		    System.out.println(cell1.getContents()+"  "+cell2.getContents()+"  "+cell3.getContents()+"  "+cell4.getContents());
			workbook.write();
			workbook.close();
			System.out.println("Student Details file created");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RowsExceededException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

3. Output

Console

01  SHIVA  12  true
Student Details file created

JExcelExample.xls

image

0 comments: