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)