The main code is as follows:
Define a dataset to hold data read by Excel
<summary>//// The data read in Excel table//// </summary> public DataSet Exceldata { get; Set; }
To get an Excel template:
//Get Excel template private void Sbtnget_click (object sender, EventArgs e) {SaveFileDialog SFD = new SaveFileDialog (); SfD. Filter = "Excel|*xls"; SfD. Filter = "(*.xls,*.xlsx) |*.xls;*.xlsx"; SfD. FileName = "Student Information" +datetime.now.tostring ("yyyy-mm-dd") + ". xls"; if (SFD. ShowDialog (This) = = DialogResult.OK) {string fileName = Application.startuppath + "\\config\\ Student information template. xls"; if (file.exists (filename)) {file.copy (filename, sfd. FileName, True); Function.showmsg ("Download successful! ", CYSoft.Common.CYEnumerate.MsgType.OK); } else {function.showmsg ("Student Information template file not found! ", CYSoft.Common.CYEnumerate.MsgType.OK); Return } } }
Select File:
Select File private void Btnfile_click (object sender, EventArgs e) {OpenFileDialog ofd = new Openf Iledialog (); Ofd. Filter = "(*.xls,*.xlsx) |*.xls;*.xlsx"; if (OFD. ShowDialog (This) = = DialogResult.OK) {This.btnFile.Text = ofd. FileName; Exceldata = null; #region read Excel File//connection string//03 version microsoft.jet.oledb.4.0 const string strconn = "provider= Microsoft.ace.oledb.12.0;data source= ' {0} '; Extended properties= ' {1}; Hdr=yes;imex=1 ' "; OleDbConnection conn = new OleDbConnection (string. Format (strconn, OFD. FileName, "Excel 8.0"); try {Conn. Open (); } catch {conn = new OleDbConnection (string. Format (strconn, OFD. FileName, "Excel 12.0"); try {Conn. Open (); } catch (Exception ee) {func.showmessage ("Connection Excel File Error:" + EE.M Essage, Func.InfoEnum.HintIE); Return }} DataTable dt = conn. GetOleDbSchemaTable (OleDbSchemaGuid.Tables, new object[] {null, NULL, NULL, "TABLE"}); DataSet ds = new DataSet (); foreach (DataRow dr in Dt. Rows) {String sql = "SELECT * FROM [" + dr["table_name"]. ToString () + "]"; OleDbDataAdapter aper = new OleDbDataAdapter (SQL, conn); Aper. Fill (DS, dr["table_name"). ToString ()); if (ds. tables[dr["table_name"]. ToString ()]. Columns.count < 2) {continue; }//DT = MySet. tables[dr["table_name"]. ToString ()]; if (ds = = null | | ds. Tables[0]. Rows.Count < 1) {func.showmessage ("Connection Excel File Error:", Func.InfoEnum.HintIE); Return }} conn. Close (); Conn. Dispose (); #endregion exceldata = ds; Validate Data and load InitExcelData2 (); } }
Description
Data check, load, save will not write
WinForm Excel Import