Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import excel sheet in winform

Tags:

c#

I am using oledb connection string to import excel sheet. I am referencing 12.0 object libraries. I tried with excel 2003 and 2007 both but getting same exception as below

Creating an instance of the COM component with CLSID {00020820-0000-0000-C000-000000000046} from the IClassFactory failed due to the following error: 80010001.

my code is

        txtpath.Text = fdlg.FileName;

        Excel.Worksheet worksheet = new Excel.Worksheet();
        Excel.Sheets sheets;
        Excel.Workbook theWorkbook;
        string SheetName;

        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"" + txtpath.Text + "\";Extended Properties=\"Excel 12.0 Xml;HDR=Yes;\";");
        conn.Open();

        Excel.Application ExcelObj = null;
        ExcelObj = new Excel.Application();

        theWorkbook = ExcelObj.Workbooks.Open(txtpath.Text, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", true, true, 0, true, 1, 0);

        sheets = theWorkbook.Worksheets;

        worksheet = (Excel.Worksheet)theWorkbook.Worksheets.get_Item(1);
        SheetName = worksheet.Name.Trim();

        OleDbDataAdapter da = new OleDbDataAdapter("Select * FROM [" + SheetName + "$]", conn);
        DataSet ds = new DataSet();
        da.Fill(ds);

please help.

like image 568
Ankita_K Avatar asked Nov 15 '22 09:11

Ankita_K


1 Answers

It is a very low-level COM error, RPC_E_CALL_REJECTED, "Call was rejected by callee". That doesn't help much, but clearly Excel isn't very happy with your code. A very good candidate is this statement:

 Excel.Worksheet worksheet = new Excel.Worksheet();

Lose that, it doesn't do anything useful. Creating the Application object first is always required.

like image 76
Hans Passant Avatar answered Dec 08 '22 22:12

Hans Passant