C # Excel File Import
Excel file export operations are often used, but it is the first time that an Excel file is imported and displayed on the interface.
The following describes how to import an Excel file in C.
Add two references first
Using System. IO;
Using System. Data. OleDb;
Add the openFileDialog Control
Then we need to configure the Excel OleDb connection string
Public const string OledbConnString = "Provider = Microsoft. jet. OLEDB.4.0; Data Source = {0}; Extended Properties = 'excel 8.0; HDR = Yes; IMEX = 1; '"; // OleDb connection string in Excel
Select an Excel file
////// Select EXCEL ///Private void btn_BrowserExcel_Click (object sender, EventArgs e) {DialogResult dr = this. openFileDialog1.ShowDialog (); if (DialogResult. OK = dr) // determine whether to select the file {this.txt Path. text = this. openFileDialog1.FileName; this. btn_Import.Enabled = true ;}}
Execute the import operation and bind the data source
////// Execute the import operation ///Private void btn_Import_Click (object sender, EventArgs e) {string path = this.txt Path. text. trim (); if (string. isNullOrEmpty (path) {MessageBox. show ("select the EXCEL file to import. "," Info "); return;} if (! File. Exists (path) // determine whether the File Exists {MessageBox. Show ("info", "cannot find the corresponding Excel File. Please reselect. "); This. btn_BrowserExcel.Focus (); return;} DataTable excelTbl = this. getExcelTable (path); // call the function to obtain information in Excel. if (excelTbl = null) {return;} DgvImport. dataSource = excelTbl ;}
The core functions are as follows:
////// Obtain the information in the Excel file and save it to a able //////File Path///
Returns the generated able.
Private DataTable GetExcelTable (string path) {try {// obtain the excel Data DataTable dt1 = new DataTable ("excelTable"); string strConn = string. format (OledbConnString, path); OleDbConnection conn = new OleDbConnection (strConn); conn. open (); DataTable dt = conn. getSchema ("Tables"); // determines the number of sheet pages in an excel worksheet. query the 1st page if (dt. rows. count> 0) {string selSqlStr = string. format ("select * from [{0}]", dt. rows [0] ["TABLE_NAME"]); OleDbDataAdapter oleDa = new OleDbDataAdapter (selSqlStr, conn); oleDa. fill (dt1);} conn. close (); return dt1;} catch (Exception ex) {MessageBox. show ("Excel DataTable Conversion error:" + ex. message); return null ;}}
:
Is the Data Query Process in the database revised?
Sure enough, the knowledge is the same.