|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.OleDb;
// Written by Anurag Gandhi.
// Url: http://www.gandhisoft.com
// Contact me at: soft.gandhi@gmail.com
/// <summary>
/// Summary description for ExcelLayer
/// </summary>
public class ExcelLayer
{
public ExcelLayer()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Retireves the data from Excel Sheet to a DataTable.
/// </summary>
/// <param name="FileName">File Name along with path from the root folder.</param>
/// <param name="TableName">Name of the Table of the Excel Sheet. Sheet1$ if no table.</param>
/// <returns></returns>
public static DataTable GetDataTable(string FileName, string TableName, string SortColumn)
{
try
{
string strPath = HttpContext.Current.Request.PhysicalApplicationPath + FileName;
DataSet ds = new DataSet();
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source=" + strPath + "; " + "Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
string Query = "SELECT * FROM [" + TableName + "] where IsActive = 1";
if (SortColumn != "")
Query += " order by " + SortColumn;
OleDbCommand objCmdSelect = new OleDbCommand(Query, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(ds);
objConn.Close();
return ds.Tables[0];
}
catch (Exception ex)
{
//Log your exception here.//
return (DataTable)null;
}
}
public static DataTable GetDataTable(string FileName, string TableName)
{
return GetDataTable(FileName, TableName, String.Empty);
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Anurag Gandhi is a Freelance Developer and Consultant, Architect, Blogger, Speaker, and Ex Microsoft Employee. He is passionate about programming.
He is extensively involved in Asp.Net Core, MVC/Web API, Node/Express, Microsoft Azure/Cloud, web application hosting/architecture, Angular, AngularJs, design, and development. His languages of choice are C#, Node/Express, JavaScript, Asp .NET MVC, Asp, C, C++. He is familiar with many other programming languages as well. He mostly works with MS SQL Server as the preferred database and has worked with Redis, MySQL, Oracle, MS Access, etc. also.
He is active in programming communities and loves to share the knowledge with others whenever he gets the time for it.
He is also a passionate chess player.
Linked in Profile: https://in.linkedin.com/in/anuraggandhi
He can be contacted at soft.gandhi@gmail.com