简体   繁体   中英

How is downcasting/upcasting done between 2 interfaces in Selenium WebDriver in Java in Excel

Interface WritableSheet extends interface Sheet (jxl) library. I want to use the addCell() that is there in WritableSheet .

But when I try to convert Sheet object to WritableSheet object,I get ClassCastException . I want to know how to typecast between two interfaces.

Below is my code :

package xyz;  
import java.io.File;  
import java.io.IOException;  
import jxl.Cell;  
import jxl.Sheet;  
import jxl.Workbook;  
import jxl.read.biff.BiffException;  
import jxl.write.Label;  
import jxl.write.WritableSheet;  
import jxl.write.WriteException;  
import jxl.write.biff.RowsExceededException;  
public class WriteExcel12  
{   
   public static Workbook wb;  
   public static Sheet s;  
   public static Cell c;  
   public static WritableSheet ws;  
   public static Label l;  
   public static void main(String[] args) throws BiffException, IOException, RowsExceededException, WriteException  
    {  
        File f=new File("D:/Input.xls");
        wb=Workbook.getWorkbook(f);
        s=wb.getSheet("Data");

        //WritableSheet extends Sheet
        ws=(WritableSheet)s;//ClassCastException here

        //Read cell(0,0) from Sheet named Data
        c=s.getCell(0,0);
        String a=c.getContents();

        //Read cell(0,1) from Sheet named Data
        c=s.getCell(1,0);
        String b=c.getContents();

        //Read cell(0,2) from Sheet named Data
        c=s.getCell(2,0);
        String d=c.getContents();

        //Convert String to integer
        int e=Integer.parseInt(a);
        System.out.println(e);

        int g=Integer.parseInt(b);
        System.out.println(g);

        int h=Integer.parseInt(d);
        System.out.println(h);

        //Perform addition
        int result=e+g+h;
        System.out.println(result);

        //Convert result which is it to String
        String ans=Integer.toString(result);

        // Write String  ans to cell(0,3)
        l=new Label(3,0,ans);
        ws.addCell(l);
    }
}  

Data.xls

10| 20| 30|


You can create a WritableWorkbook from your Workbook .Then you can get your WritableSheet .

File f=new File("D:/Input.xls");
wb=Workbook.getWorkbook(f);
WritableWorkbook copy = Workbook.createWorkbook(f, workbook);
WritableSheet sheet = copy.getSheet("Data"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM