public static bool import_excel(string excelPath)
{
bool result = false;
//本地串連】
string myConnectString = "Server=localhost;Database=database;uid=sa;pwd=×××××;";
SqlConnection objConnection = new SqlConnection(myConnectString);
//建立一個excel應用程式
Excel.Application objApplication = new Excel.Application();
//建立一個活頁簿
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;
//如果只想用程式控制該excel而不想讓使用者操作時候,可以設定為false
objApplication.Visible = false;
objApplication.UserControl = true;
// sheetName為Excel檔案中Sheet的名子
string sheetName = string.Empty;
//然後通過它裡面Excel.Application,Excel.Workbook,Excel.Worksheet,Excel.Range對像獲得一些你想要的資訊
for (int i = 1; i<= objWorkbook.Sheets.Count;i++)
{
取得excel 的工作表
sh = ( Excel._Worksheet)objWorkbook.Sheets[i];
objConnection.Open();
objBuilder.Append(sh.Name);
objBuilder.Append("$");
//excel工作表名
sheetName = objBuilder.ToString();
//sqlserver的表名
mubiaotable = objBuilder.ToString();
//把excel的工作表讀出寫入sqlserver表(sql語句經常出錯)
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;
退出應用程式
objApplication.Quit();
}
catch(CSystem.CException ex)
{
throw new CSystem.CException(ex.ToString());
}
//釋放進程
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;
}