Web Infotech

Web Infotech

  • NA
  • 20
  • 427

Unable to get excel file data in gridview please help me ...

Oct 20 2017 1:25 PM
private void btnFileUpload_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Excel Files|*.xls;*.xlsx"; // file types, that will be allowed to upload
dialog.Multiselect = false; // allow/deny user to upload more than one file at a time
if (dialog.ShowDialog() == DialogResult.OK) // if user clicked OK
{
String path = dialog.FileName; // get name of file
using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open), new UTF8Encoding())) // do anything you want, e.g. read it
{
// ...
}
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(constr);
System.Data.OleDb.OleDbDataAdapter MyDataAdapter = new System.Data.OleDb.OleDbDataAdapter("Select MobileNo from [Sheet1$]", con);
System.Data.DataTable dt = new System.Data.DataTable();
MyDataAdapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
dataGridView1.DataSource = dt;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Answers (2)