import excel sheet in winform
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;
OleDbCo开发者_运维知识库nnection 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.
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.
Disclaimer: I don't do a lot of Office interop. But my Googling on this error implies that it occurs when the COM object in question isn't fully loaded, and I note that you're opening the connection before you're creating an Excel.Application
object.
Perhaps you can switch that around? Try something like this:
Excel.Worksheet worksheet = new Excel.Worksheet();
Excel.Sheets sheets;
Excel.Workbook theWorkbook;
string SheetName;
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();
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"" + txtpath.Text + "\";Extended Properties=\"Excel 12.0 Xml;HDR=Yes;\";");
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * FROM [" + SheetName + "$]", conn);
DataSet ds = new DataSet();
da.Fill(ds);
精彩评论