Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel.Worksheet'. An explicit conversion exists (are you missing a cast?)

Here I'm opening excel and writing to excel sheet. I'm changing my windows application to asp website and seen this error. I have added all the references and libraries. Don't know what I am missing here.

Getting error as mentioned below. Please help me.

    Excel.Application excel = new Excel.Application();
    excel.Visible = false; // to hide the processing 
    Excel.Workbook wb = excel.Workbooks.Add();
    Excel.Worksheet sh = wb.Sheets.Add(); // Error at wb


    sh.Name = "Links";

    for (int i = 1; i < list.Count; i++)
    {
        sh.Cells[i.ToString(), "A"].Value2 = list[i]; //Error at .Value2

    }
like image 787
221B Avatar asked Nov 10 '13 09:11

221B


2 Answers

you have to create a new Worksheet with Sheets array by providing WorkSheet Name. and also please Cast The Newly Created WorkSheet.

Replace this :

Excel.Worksheet sh = wb.Sheets.Add();

with following

 Excel.Worksheet sh  = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets["Sheet1"];
like image 187
Sudhakar Tillapudi Avatar answered Nov 10 '22 14:11

Sudhakar Tillapudi


To resolve your second error,

//Error at .Value2

  1. Go to project properties. (Click Project in Menu, Click properties)
  2. Set the Target Framework as .NET Framework 4
  3. This should resolve your .Value2 error.
like image 1
Cloud Exp Avatar answered Nov 10 '22 14:11

Cloud Exp