自己寫的excel匯入sqlserver函數

來源:互聯網
上載者:User

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;

    }  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.