Import the data from Excel into DataGridView

Source: Internet
Author: User

Https://www.cnblogs.com/lhxhappy/archive/2008/11/26/1341873.html

/// <summary>        ///Click the button to import the data///Lhxhappy/// </summary>        /// <param name= "Sender" ></param>        /// <param name= "E" ></param>        Private voidButton1_Click (Objectsender, EventArgs e) {            //Open a File selection boxOpenFileDialog OFD=NewOpenFileDialog (); Ofd. Title="Excel File"; Ofd. FileName=""; Ofd. InitialDirectory= Environment.getfolderpath (Environment.SpecialFolder.MyDocuments);//in order to obtain a specific system folder, you can use the static method GetFolderPath () of the System.Environment class. The method accepts a Environment.SpecialFolder enumeration that defines which system directory to return the path toOFD. Filter="Excel File (*.xls) |*.xls"; Ofd. Validatenames=true;//file Validation validatenames, verifying that user input is a valid Windows file nameOFD. Checkfileexists=true;//Verifying path ValidityOFD. Checkpathexists=true;//Verifying file Validity            stringStrName =string.            Empty; if(OFD. ShowDialog () = =DialogResult.OK) {strName=OFD.            FileName; }            if(StrName = ="") {MessageBox.Show ("no Excel file selected! Unable to import data"); return; }            //Invoking the Import data methodEcxeltodatagridview (StrName, This. HpGridView1); }

Excel data Import method

/// <summary>        ///Excel Data import method///Author: lhxhappy/// </summary>        /// <param name= "FilePath" ></param>        /// <param name= "DGV" ></param>         Public voidEcxeltodatagridview (stringFilepath,datagridview DGV) {            //opens an Excel file according to the path and populates the data into the dataset            stringstrconn ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source ="+ FilePath +"; Extended Properties = ' Excel 8.0; Hdr=no;imex=1 '";//import contains the first row of data in Excel, and cells mixed with numbers and characters are treated as textOleDbConnection Conn=NewOleDbConnection (strconn); Conn.            Open (); stringStrexcel =""; OleDbDataAdapter mycommand=NULL; DataSet DS=NULL; Strexcel="select * FROM [sheet1$]"; MyCommand=NewOleDbDataAdapter (Strexcel, strconn); DS=NewDataSet (); Mycommand.fill (DS,"table1"); //construct a new DataTable based on the columns of DataGridViewDataTable TB=NewDataTable (); foreach(DataGridViewColumn DGVCinchDGV. Columns) {if(DGVC. Visible && DGVC. Celltype! =typeof(Datagridviewcheckboxcell)) {DataColumn DC=NewDataColumn (); dc. ColumnName=DGVC.                    DataPropertyName; //DC. DataType = DGVC. ValueType;//Uncomment if you need to restrict the data type at import, provided that the DataGridView must first bind a data source to the empty DataTableTB.                Columns.Add (DC); }            }            //assigns the columns of the DataTable constructed above, based on the lines of Excel            foreach(DataRow ExcelrowinchDs. tables[0]. Rows) {inti =0; DataRow Dr=TB.                NewRow (); foreach(DataColumn DCinchTB. Columns) {DR[DC]=Excelrow[i]; I++; } TB.            Rows.Add (DR); }            //displaying imported data in DataGridViewDGV. DataSource=TB; }

Import data from Excel into DataGridView (GO)

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.