TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
How to open Excel file in DataGridview
Kunal Vaishya
Apr 30, 2012
30.7
k
0
1
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
Here you will learn how to open Excel file in DataGridview.
WindowsFormsApplication1.zip
Setp 1 :
First Start visual Studion and Create new Project in C# Lnguages
Step 2 :
Go Design Form and put a gridview and a button on Form ;
Step 3 :
Use Namespace
using
System.Data;
using
System.Data.OleDb;
Setp 4 :
Create Event og Button Write code in
private
void
Button1_Click(
object
sender,
EventArgs
e)
{
OpenFileDialog
op =
new
OpenFileDialog
();
op.Filter =
"Excel 97 - 2003|*.xls|Excel 2007|*.xlsx"
;
if
(op.ShowDialog() == System.Windows.Forms.
DialogResult
.OK)
{
if
(
File
.Exists(op.FileName))
{
string
[] Arr =
null
;
Arr = op.FileName.Split(
'.'
);
if
(Arr.Length > 0)
{
if
(Arr[Arr.Length - 1] ==
"xls"
)
sConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+
op.FileName +
";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
;
}
else
if
(Arr[Arr.Length - 1] ==
"xlsx"
)
{
sConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ op.FileName +
";Extended Properties='Excel 12.0 Xml;HDR=YES';"
;
}
}
FillData();
}
}
}
public
string
sConnectionString;
private
void
FillData()
{
if
(sConnectionString.Length > 0)
{
OleDbConnection
cn =
new
OleDbConnection
(sConnectionString);
{
cn.Open();
DataTable
dt =
new
DataTable
();
OleDbDataAdapter
Adpt =
new
OleDbDataAdapter
(
"select * from [sheet1$]"
, cn);
Adpt.Fill(dt);
DataGridView1.DataSource = dt;
}
catch
(
Exception
ex)
{
}
}
}
Screen Shot
How to open Excel file in DataGridview
Next Recommended Reading
Insert multiple values from textbox and show them into a datagridview