To import Excel data into the DataGridView of C #

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.