How to write and append data to an excel and read data from an excel file in Java

Download jxl.jar and add 'jxl.jar' expected project
 import java.io.File;  
 import java.io.IOException;  
 import java.util.Random;  
 import jxl.Sheet;  
 import jxl.Workbook;  
 import jxl.read.biff.BiffException;  
 import jxl.write.Label;  
 import jxl.write.WritableSheet;  
 import jxl.write.WritableWorkbook;  
 import jxl.write.WriteException;  
 import jxl.write.Number;  
 public class Writeappandreadexcelhandler {  
   public static void main(String[] args) throws BiffException, IOException, WriteException {  
     File file;  
     file = new File("jobs/output.xls");  
     // if file doesnt exists, then create it   
     if (!file.exists()) {  
       file.createNewFile();  
     }  
     // Write Data to an Excel file using jxl api   
     WritableWorkbook wworkbook = Workbook.createWorkbook(file);  
     WritableSheet wsheet = wworkbook.createSheet("First Sheet", 0);  
     for (int rows = 0; rows < 10; rows++) {  
       wsheet.addCell(new Label(0, rows, "First Coloum " + randInt(100, 500)));  
       wsheet.addCell(new Number(1, rows, randInt(100, 500)));  
       wsheet.addCell(new Label(2, rows, "third Coloum " + randInt(100, 500)));  
       wsheet.addCell(new Number(3, rows, randInt(100, 500)));  
     }  
     wworkbook.write();  
     wworkbook.close();  
     // Append Data to an Excel file using jxl api   
     Workbook workbook1 = Workbook.getWorkbook(file);  
     WritableWorkbook copy = Workbook.createWorkbook(file, workbook1);  
     WritableSheet sheet2 = copy.getSheet(0);  
     Sheet sh2 = copy.getSheet(0);  
     int size = sh2.getRows();  
     for (int rows2 = size; rows2 < size + 10; rows2++) {  
       sheet2.addCell(new Label(0, rows2, "Append1 Data1" + randInt(100, 500)));  
       sheet2.addCell(new Number(1, rows2, randInt(100, 500)));  
       sheet2.addCell(new Label(2, rows2, "Append1 Data2 " + randInt(100, 500)));  
       sheet2.addCell(new Number(3, rows2, randInt(100, 500)));  
     }  
     copy.write();  
     copy.close();  
     // Read Data from an Excel file using jxl api   
     Workbook workbook = Workbook.getWorkbook(file);  
     Sheet sh = workbook.getSheet(0);  
     for (int rows = 0; rows < sh.getRows(); rows++) {  
       for (int colm = 0; colm < sh.getColumns(); colm++) {  
         System.out.print(sh.getCell(colm, rows).getContents() + " ");  
       }  
       System.out.println();  
     }  
   }  
   public static int randInt(int min, int max) {  
     Random rand = new Random();  
     int randomNum = rand.nextInt((max - min) + 1) + min;  
     return randomNum;  
   }  
 }  

No comments:

Post a Comment