Friday, 9 January 2015

How to add cells to sheet in xls file


It is very simple, create a label and add it to the sheet at specific column and row.

Example
Label label = new Label(0, 2, "A label record");
sheet.addCell(label);

cell locations starts from zero, means 1st columns is identified with 0, 2nd column with 1 etc.,

public class WorkBookNotInitializedException extends RuntimeException{

    WorkBookNotInitializedException(){
        super("work book is not initialized");
    }
}

import java.io.IOException;
import jxl.*;
import jxl.write.*;
import java.io.File;

public class XLSWritableUtils {
    WritableWorkbook workbook = null;

    public XLSWritableUtils(String fileName){
        try {
            workbook = Workbook.createWorkbook(new File(fileName));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void checkWorkbookInitialized(){
        if(workbook == null)
            throw new WorkBookNotInitializedException();
    }

    public void createSheet(String sheetName, int index){
        checkWorkbookInitialized();
        workbook.createSheet(sheetName, index);
    }

    public void addString(WritableSheet sheet, int column, int row, String data){
        Label label = new Label(column, row, data);
        try{
            sheet.addCell(label);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public void addString(String sheetName, int column, int row, String data){
        checkWorkbookInitialized();
        WritableSheet sheet = workbook.getSheet(sheetName);
        addString(sheet, column, row, data);
    }

    public void addString(int sheetIndex, int column, int row, String data){
        checkWorkbookInitialized();
        WritableSheet sheet = workbook.getSheet(sheetIndex);
        addString(sheet, column, row, data);
    }


    public void close(){
        checkWorkbookInitialized();
        try{
           workbook.write();
           workbook.close();
        }
        catch(Exception e){
            
        } 
    }
}

public class TestUtils {
    public static void main(String[] args) {
       String fileName = "data.xls";
       XLSWritableUtils utils = new XLSWritableUtils(fileName);
       utils.createSheet("employee", 0);

       /* Add employee id, firstName and lastName in row 1 */
       utils.addString("employee", 0, 0, "1");
       utils.addString("employee", 1, 0, "Hari Krishna");
       utils.addString("employee", 2, 0, "Gurram");
       
       utils.close();
    }
}


Run “TestUtils” class, you will get xls sheet with employee data.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment