Reading and Writing Excel File using jxl.jar

Reading Data from Excel File
Copy input.xls

package com.excel.test;

import java.io.File;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadingExcelDemo {

 public static void main(String[] args) throws BiffException, IOException {
  File file = new File("./TestData/input.xls");
  Workbook wb = Workbook.getWorkbook(file);
  
  Sheet sheet = wb.getSheet(0);
  
  int noOfRows = sheet.getRows();
  int noOfColumns = sheet.getColumns();
  
  System.out.println("No of Rows: " + noOfRows);
  System.out.println("No of Columns: " + noOfColumns);
  
  System.out.println("Cell02 1st Column and 3rd Row: " 
  + sheet.getCell(0, 2).getContents());
  String data = "";
  for (int i = 0; i < noOfRows; i++) {
   for (int j = 0; j < noOfColumns; j++) {
    data = sheet.getCell(j, i).getContents();
    System.out.print(data + "\t");
   }
   System.out.println();
  }
  wb.close();
 }
}

Writing Data to an Excel File:
package com.excel.test;

import java.io.File;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class WritingExcelDemo {
 public static void main(String[] args) throws Exception {
  File file = new File("./TestData/output.xls");
  
  WritableWorkbook wb = Workbook.createWorkbook(file);
  WritableSheet sht = wb.createSheet("data", 0);
  
  Label ll = new Label(0, 0, "Result");
  sht.addCell(ll);
  sht.addCell(new Label(0, 1, "Pass"));
  sht.addCell(new Label(0, 2, "Fail"));
  
  wb.write();
  wb.close();
  System.out.println("Workbook is created");
 }
}

3 comments: