Saturday, June 7, 2008

Accessing Xls Sheet Data from .NET Application

Some time back i was in need to fetch some data from the Excel sheet from .NET Application. I have done some R & D on the Net and found some great examples of the same then i created my own sample component which will serve you like the basis component and you can enhance the same futher as per your need.

/*
* Created by Dalip Vohra
*/

using System;
using System.IO;
using System.Data;
using System.Data.OleDb;
namespace ExcelManagement.OleDB
{
///
/// Description of TimedAccess.
///

public class ExcelAccess
{
#region Private Variables
string connString;
OleDbConnection oledbConn;
#endregion

#region Constructor
public ExcelAccess(string _xlsFile, string _xlsFileSheetName)
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=../../Book2.xls;Extended Properties=Excel 8.0";
oledbConn = new OleDbConnection(connString);
try
{
// Open connection
oledbConn.Open();
}
catch
{
throw (new Exception("Connection Exception"));
}
}
#endregion

#region GetSheetData Method
public DataSet GetSheetData(string SheetName)
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + SheetName + "$]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "RecordsTable");
return ds;
}
#endregion

#region GetRangeFromSheet Method

public DataSet GetRangeFromSheet(string SheetName, String StartingCell, String EndingCell)
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + SheetName + "$" + StartingCell + ":" + EndingCell + "]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "RecordsTable");
return ds;
}
#endregion

#region Dispose Method

public void Dispose()
{
connString = null;
oledbConn.Close();
}
#endregion

}
}

No comments: