Retrieving COM Class Factory Error [Resolved]

Posted by Sharpcnet under C# on 11/21/2013 | Points: 10 | Views : 878 | Status : [Member] | Replies : 1
I get the Error - Retrieving the COM class factory...' at the line
Excel.Workbook wb = new Excel.Workbook.
Using VS2010, Windows 7 64 bit. I already set the Target platform to 'X(86)'.

using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;

protected void btnOpen_Click(object sender, EventArgs e)
{
OpenExcel();
}

private void OpenExcel()
{
Excel.Application app = new Excel.Application();
Excel.Workbook wb = new Excel.Workbook();
Excel.Worksheet ws = new Excel.Worksheet();
Excel.Range range = null;

app.visible = true;
wb = app.Workbooks.Add(1);
ws = wb.WorkSheets[1];

range = ws.get_Range("A1","A3");
ws.Cells[0,0]="Date";
ws.Cells[0,1]="Code";
ws.Cells[0,2]="Name";
}





Responses

Posted by: Sharpcnet on: 11/21/2013 [Member] Starter | Points: 25

Up
0
Down

Resolved
This worked for me. Microsoft.Interop indexing starts from 0 instead of 1 and also, the workbook, worksheet variables better be declared nulls instead of new instances.

Excel.Application app = new Excel.Application();
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Range range = null;

app.visible = true;
wb = app.Workbooks.Add(1);
ws = (Excel.Worksheet)wb.WorkSheets[1];
range = ws.get_Range("A1","D1");

ws.Cells[1,1]="Date";
ws.Cells[1,2]="Code";
ws.Cells[1,3]="Name";


Sharpcnet, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response