Windows Forms: How to read an excel (.xls/.xlsx) file in C#
By FoxLearn 5/24/2017 8:59:35 PM 6.37K
How to read an excel (*.xls/.xlsx) file in C# using ExcelDataReader, lightweight and fast library written in C# for reading Microsoft Excel files ('97-2007)
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ReadExcelFile" and then click OK
Step 2: Right click on your project select Manage NuGet Packages -> Search ExcelDataReader -> Install
Step 3: Design your form as below
Create an excel file, then copy data from Northwind database to the excel file
Step 4: Add code to handle your form
using Excel; using System; using System.Data; using System.IO; using System.Windows.Forms; namespace ReadExcelFile { public partial class Form1 : Form { public Form1() { InitializeComponent(); } DataSet result; private void btnOpen_Click(object sender, EventArgs e) { using(OpenFileDialog ofd = new OpenFileDialog() { Filter= "Excel Workbook 97-2003|*.xls|Excel Workbook|*.xlsx", ValidateNames = true }) { if (ofd.ShowDialog() == DialogResult.OK) { FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read); IExcelDataReader reader; if (ofd.FilterIndex == 1) reader = ExcelReaderFactory.CreateBinaryReader(fs);//Read excel 97-2003 else reader = ExcelReaderFactory.CreateOpenXmlReader(fs);//Read excel 2007 reader.IsFirstRowAsColumnNames = true; result = reader.AsDataSet(); cboSheet.Items.Clear(); //Add sheet to comboxbox foreach (DataTable dt in result.Tables) cboSheet.Items.Add(dt.TableName); reader.Close(); } } } private void cboSheet_SelectedIndexChanged(object sender, EventArgs e) { //Fill data from excel into DataGridView based on sheet selection dataGridView.DataSource = result.Tables[cboSheet.SelectedIndex]; } } }
VIDEO TUTORIALS
- How to Use Form Load and Button click Event in C#
- How to use Advanced Filter DataGridView in C#
- How to use TagListControl in C#
- How to use Error Provider in C#
- How to Drag and Drop controls in C#
- How to Create a Random Password Generator in C#
- How to make an Application auto run on Windows startup in C#
- How to Create a Wait Form Dialog in C#
Categories
Popular Posts
C# Tutorial
07/20/2024
How to Download Microsoft SQL Server
06/22/2024
What Are RESTful Web Services?
02/19/2024