Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am creating a document level vsto solution for excel .
My excel is like :
sheet name : Sheet1
data :

columns- A B C D
Projetc1
Project2
Project3

I need to read column B values . So i wrote below code :

private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{

Workbook wb =
Globals.Factory.GetVstoObject(Globals.ThisWorkbook.Application.ActiveWorkbook);
Worksheet ws = (Worksheet)wb.Worksheets[1];

string s = ws.Name;
var cell1 = ws.Range["B", Type.Missing];
var content = cell1.Value2;

}


But i am getting invalid cast error
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Tools.Excel.Worksheet.

I need to read the column b values in a list .
PLease guide me how to do it .
Posted

1 solution

error msg already tells you what the deal is:

Worksheet ws = (Worksheet)wb.Worksheets[1];
According to that, you cannot cast the object as workbook, since there is no workbook object at index 1.

if you're bound to use VSTO, then you should read this:
http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.activesheet.aspx

else, I would prefer odbc method

http://lmgtfy.com/?q=c%23+excel+odbc[^]
 
Share this answer
 
Comments
prejval2006 24-Jan-14 5:07am    
how can there be no worsheet at index 1 ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900