Read Excel file in C#
In this tutorial we will see how to read an Excel file in a C# windows forms application using ExcelDataReader package.
So let's create a Windows Forms application and add a button and a DatagridView.
Then then right click on the project and select Manage NuGet Packages..., write excelDataReader in search, select ExcelDataReader and install it and rebuild the project.
Moving to the code now, first add these directives:
And in OpenButton click event write this code:
So let's create a Windows Forms application and add a button and a DatagridView.
Then then right click on the project and select Manage NuGet Packages..., write excelDataReader in search, select ExcelDataReader and install it and rebuild the project.
Moving to the code now, first add these directives:
using System.IO;
using Excel;
using ICSharpCode.SharpZipLib;
using ICSharpCode;
And in OpenButton click event write this code:
private void OpenButton_Click(object sender, EventArgs e)
{
using (OpenFileDialog dialog = new OpenFileDialog() { Filter = "Excel Workbook 97-2003|*.xls|Excel Workbook|*.xlsx", ValidateNames = true })
{
if(dialog.ShowDialog()==DialogResult.OK)
{
FileStream fs = File.Open(dialog.FileName, FileMode.Open, FileAccess.Read);
IExcelDataReader reader;
if(dialog.FilterIndex==1)
{
reader = ExcelReaderFactory.CreateBinaryReader(fs);
}
else
{
reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
}
reader.IsFirstRowAsColumnNames = true;
DataSet resultDs;
resultDs = reader.AsDataSet();
dataGridView1.DataSource = resultDs;
reader.Close();
}
}
}
Read Excel file in C#
Reviewed by Bloggeur DZ
on
00:29
Rating:
Aucun commentaire: