Namespaces that need to be introduced
Using system.runtime.interopservices;//to get mouse events
Using System.IO;
Using System.Data.OleDb;
Core code
private void Button1_Click (object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog ();//First select the file to open according to the Open File dialog box
Ofd. Filter = "Excel table |*.xlsx| excel97-2003 table |*.xls| All Files |*.* ";//Open File dialog filter, default display file type
String strpath;//definition file path
if (OFD. ShowDialog () = = DialogResult.OK)
{
Try
{
strpath = ofd. FileName;
String sss = Ofd. safefilename;//Get file name
String fileType = System.IO.Path.GetExtension (strpath);//Gets the suffix of the file
String strcon = "";
if (FileType = = ". xls")//If the file is 97-2003 format
{
Strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strpath + "; Extended properties= ' Excel 8.0; Hdr=yes;imex=1 ' ";
}
else//If the file is 2007 format
{
Strcon = "Provider=microsoft.ace.oledb.12.0;data source=" +strpath+ "; Extended properties= ' Excel 12.0; Hdr=yes;iemx=1 ' ";
}
OleDbConnection conn=new OleDbConnection (Strcon);
Application.doevents ();
String strSQL = "SELECT * FROM [sheet1$]";
OleDbCommand cmd= New OleDbCommand (Strsql,conn);
OleDbDataAdapter da = new OleDbDataAdapter (CMD);
DataSet ds = new DataSet ();
Da. Fill (ds, "Insert Table");
Datagridview1.datasource=ds. Tables[0];
Datagridview1.allowusertoaddrows = false;
Datagridview1.allowusertodeleterows = false;
MessageBox.Show (SSS);
}
catch (Exception ex)
{
MessageBox.Show (ex. Message);//Catch exception
}
}
}
This article from "Boring life _ positive face" blog, please be sure to keep this source http://321331.blog.51cto.com/311331/1919852
Import Excel data into C # DataGridView