Public static bool import_excel (string excelpath)
{
Bool result = false;
// Local connection]
String myconnectstring = "Server = localhost; database = database; uid = sa; Pwd = ×××× ;";
Sqlconnection objconnection = new sqlconnection (myconnectstring );
// Create an Excel applicationProgram
Excel. Application objapplication = new excel. Application ();
// Create a workbook
Excel. _ workbook objworkbook = objapplication. workbooks. Add (excelpath );
Excel. _ worksheet SH = new worksheetclass ();
Try
{
String strsql = string. empty;
Stringbuilder objbuilder = new stringbuilder ();
String mubiaotable = string. empty;
// If you only want to use a program to control the Excel file and do not want the user to operate it, you can set it to false.
Objapplication. Visible = false;
Objapplication. usercontrol = true;
// Sheetname is the name of the sheet in the Excel file
String sheetname = string. empty;
// Use the Excel. Application, Excel. Workbook, Excel. worksheet, and Excel. Range pairs to obtain the desired information.
For (INT I = 1; I <= objworkbook. Sheets. Count; I ++)
{
Obtain an Excel worksheet
SH = (Excel. _ worksheet) objworkbook. Sheets [I];
Objconnection. open ();
Objbuilder. append (Sh. Name );
Objbuilder. append ("$ ");
// Excel worksheet name
Sheetname = objbuilder. tostring ();
// Sqlserver table name
Mubiaotable = objbuilder. tostring ();
// Read the Excel worksheet and write it into the sqlserver table (SQL statements often encounter errors)
Strsql = "select * into" + mubiaotable + "from OpenRowSet ('Microsoft. jet. oledb.4.0 ', 'excel 5.0; HDR = yes; database = "+ excelpath +"', "+ sheetname + ")";
Sqlcommand objcmd = new sqlcommand (strsql, objconnection );
Objcmd. executenonquery ();
Objconnection. Close ();
//
Objbuilder. Remove (0, objbuilder. Length );
}
Result = true;
Exit Application
Objapplication. Quit ();
}
Catch (csystem. cexception ex)
{
Throw new csystem. cexception (ex. tostring ());
}
// Release the process
Finally
{
System. runtime. interopservices. Marshal. releasecomobject (objapplication );
System. runtime. interopservices. Marshal. releasecomobject (objworkbook );
System. runtime. interopservices. Marshal. releasecomobject (SH );
Objapplication = NULL;
Objworkbook = NULL;
SH = NULL;
GC. Collect ();
Objconnection. Close ();
Objconnection = NULL;
}
Return result;
}