Read Excel files using C-Sharp windows application


This article explains how to read excel files using c sharp in windows applications.

using System.Data.OleDb;

private void btnRead_Click(object sender, EventArgs e)
{
try
{
string connStr = connStr = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + Application.StartupPath + @”\Courier.xls;Extended Properties=ImportMixedTypes=Text;Excel 8.0;HDR=Yes;IMEX=1;”;

//You must use the $ after the object you reference in the spreadsheet
OleDbDataAdapter adap = new OleDbDataAdapter(“SELECT * FROM [Sheet1$]”, connStr);

DataSet ds = new DataSet();
adap.Fill(ds, “Courier”);
dataGridView1.DataSource = ds.Tables[“Courier”].DefaultView;

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Explanation of the above code:
Here I used OleDb to read the excel file. The excel file resides with exe file as Courier.xls.

Sheet1$ is the name of excel sheet.
Courier is the name of file so i am using the same name in filling the DataSet.

Now at last the data is filled into dataGridView.

Now if you are not able to read the integer value or any value other then text then
include the
Extended Properties=ImportMixedTypes=Text;Excel 8.0;HDR=Yes;IMEX=1 property in connection string.

The above code can also be used in a web application, for this you need to replace the Application.StartupPath with Server.MapPath

HaPpY CoDiNg………..

About dotnetcoderoom

Working as an Onsite coordinator in USA. Handling UAT, CR (Change Requests), Product Support/Development, Build Management. Supervise and assist in live product implementation (at client side) and training. Providing technical direction for the development, design, and system integration. Closely monitoring and working with offshore team for Enhancements, Bug Fixing, Enforce coding standards, perform code reviews and mentors junior developers. Proven track of timely delivery of enterprise level web based applications. Skilled in a variety of software languages, tools, and methodologies, with a special expertise in Microsoft .NET technologies. MCTS .Net 4.0 Web applications MCTS .Net 2.0 Web applications GNIIT, MCA, B.Com Specialties 8+ Years of experience in .NET Technologies. Expertise in .NET, ASP.NET, MVC, C#, VB.NET, WCF, Web Services, MS SQL, JQuery. Excellent R&D and troubleshooting skills. Extensive knowledge in E-Commerce and Healthcare domain. View all posts by dotnetcoderoom

One response to “Read Excel files using C-Sharp windows application

Leave a comment