By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,910 Members | 1,077 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,910 IT Pros & Developers. It's quick & easy.

Connecting to Excel with C#

P: n/a

Can anyone send me a code snippet on how to connect to an Excel
spreadsheet and then read it in a row at a time?
John S

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
These might help:

http://www.codeproject.com/csharp/Excel_using_OLEDB.asp
http://www.c-sharpcorner.com/winforms/ExcelReadMG.asp

"John Sutor" <jo********@cinfin.com> wrote in message
news:e$**************@TK2MSFTNGP11.phx.gbl...

Can anyone send me a code snippet on how to connect to an Excel
spreadsheet and then read it in a row at a time?
John S

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #2

P: n/a
These two methods should get you started. They will fill a dataset with the
excel data.

Hope that helps.
-Darrin

private DataSet GetExcelData(System.IO.FileInfo importFile)
{
OleDbConnection _xlConn = new OleDbConnection();

try
{
DataSet _xlDataSet = new DataSet();
_xlConn = GetOleConnectionForExcel(importFile.FullName);
OleDbDataAdapter _xlAdapt = new OleDbDataAdapter();

_xlConn.Open();

DataTable _schemaTable =
_xlConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables , null);

foreach(DataRow _dr in _schemaTable.Rows)
{
_xlAdapt.SelectCommand = new OleDbCommand("Select * from [" +
_dr["TABLE_NAME"].ToString() + "]", _xlConn);
_xlAdapt.Fill(_xlDataSet, _dr["TABLE_NAME"].ToString());
}

return _xlDataSet;
}
catch(SqlException _sqlException)
{
throw new Exception("Error getting Excel data.", _sqlException);
}
catch(Exception _exception)
{
throw new Exception("Error getting Excel data.", _exception);
}
finally
{
if(_xlConn.State != ConnectionState.Closed)
_xlConn.Close();
}
}

private OleDbConnection GetOleConnectionForExcel(string filePath)
{
string _cnString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + filePath +
";" + "Extended Properties=Excel 8.0;IMEX=1";

return new OleDbConnection(_cnString);
}
"John Sutor" <jo********@cinfin.com> wrote in message
news:e$**************@TK2MSFTNGP11.phx.gbl...

Can anyone send me a code snippet on how to connect to an Excel
spreadsheet and then read it in a row at a time?
John S

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.