1) Excel data is imported directly into a temporary generated DataTable
using(OleDbConnection selectconnection =NewOleDbConnection ("Provider=microsoft.ace.oledb.12.0;data source="+ FilePath +"; Extended properties= ' Excel 12.0; Hdr=yes;imex=1 '") ) {Selectconnection.open (); OleDbDataAdapter adapter=NewOleDbDataAdapter ("select * FROM [hr$]", selectconnection); //adapter. Fill (dataset);adapter. Fill (DT); }
View Code
2) Start thread, trigger DoWork event
Bgwinsertdata.runworkerasync ();
3) Program Initialization
PublicForm1 () {InitializeComponent (); //set the progress bar to update data automaticallyBgwinsertdata.workerreportsprogress =true; Bgwinsertdata.workersupportscancellation=true; Bgwinsertdata.dowork+=NewDoworkeventhandler (bgwinsertdata_dowork); Bgwinsertdata.progresschanged+=NewProgresschangedeventhandler (bgwinsertdata_progresschanged); Bgwinsertdata.runworkercompleted+=NewRunworkercompletedeventhandler (bgwinsertdata_runworkercompleted); }
View Code
4) Progress bar processing code
voidBgwinsertdata_runworkercompleted (Objectsender, Runworkercompletedeventargs e) { if(E.error! =NULL) {MessageBox.Show (E.error.message,"Tips", MessageBoxButtons.OK, Messageboxicon.error); return; } Else if(e.cancelled) {MessageBox.Show ("Cancel the operation! ","Tips", MessageBoxButtons.OK, messageboxicon.information); return; } Else { //Reinforcement if(progressBar1.Value <=0) { return; } //binding Data Data renderingDGV. Allowusertoaddrows =false; DGV. DataSource=DT; } } voidBgwinsertdata_progresschanged (Objectsender, ProgressChangedEventArgs e) {progressBar1.Value=E.progresspercentage; Lblresult.text="Data acquired"+ e.progresspercentage.tostring () +"%"; } voidBgwinsertdata_dowork (Objectsender, DoWorkEventArgs e) {BackgroundWorker worker= Sender asBackgroundWorker; //2. Call the custom function in DoWork and pass the sender that raised the DoWork eventInsertData (worker); }
View Code
5) Achieve effect
6) Related to Knowledge Point: Excel data directly into DB, thread (progress bar).
Excel data directly into the datatable--->db