接口WritableSheet扩展了接口Sheet(jxl)库。我想使用其中的addCell()
WritableSheet

但是当我尝试将Sheet对象转换为WritableSheet对象时,得到了ClassCastException。我想知道如何在两个接口之间进行类型转换。

下面是我的代码:

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);
    }
}





  数据文件
  
  10 | 20 | 30 |

最佳答案

您可以从WritableWorkbook创建一个Workbook,然后可以获取WritableSheet

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

10-04 23:16