c#將Excel資料匯入到資料庫的實現代碼

來源:互聯網
上載者:User
c#將Excel資料匯入到資料庫的實現代碼

假如Excel中的資料如下:

資料庫建表如下:

其中Id為自增欄位:

代碼:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Data.OleDb;using System.Configuration;using System.Data.SqlClient;namespace InExcelOutExcel{    public partial class ExcelToDB : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            FileSvr fileSvr = new FileSvr();            System.Data.DataTable dt = fileSvr.GetExcelDatatable            ("C:\\Users\\NewSpring\\Desktop\\Demo\\InExcelOutExcel\\InExcelOutExcel\\excel\\ExcelToDB.xlsx", "mapTable");            fileSvr.InsetData(dt);        }    }    class FileSvr    {        /// <summary>        /// Excel資料匯入Datable        /// </summary>        /// <param name="fileUrl"></param>        /// <param name="table"></param>        /// <returns></returns>        public System.Data.DataTable GetExcelDatatable(string fileUrl, string table)        {            //office2007之前 僅支援.xls            //const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";            //支援.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是標題,不是資料;            const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";            System.Data.DataTable dt = null;            //建立串連            OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));            try            {                //開啟串連                if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)                {                    conn.Open();                }                System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);                //擷取Excel的第一個Sheet名稱                string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();                //查詢sheet中的資料                string strSql = "select * from [" + sheetName + "]";                OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);                DataSet ds = new DataSet();                da.Fill(ds, table);                dt = ds.Tables[0];                return dt;            }            catch (Exception exc)            {                throw exc;            }            finally            {                conn.Close();                conn.Dispose();            }        }        /// <summary>        /// 從System.Data.DataTable匯入資料到資料庫        /// </summary>        /// <param name="dt"></param>        /// <returns></returns>        public int InsetData(System.Data.DataTable dt)        {            int i = 0;            string lng = "";            string lat = "";            string offsetLNG = "";            string offsetLAT = "";            foreach (DataRow dr in dt.Rows)            {                lng = dr["LNG"].ToString().Trim();                lat = dr["LAT"].ToString().Trim();                offsetLNG = dr["OFFSET_LNG"].ToString().Trim();                offsetLAT = dr["OFFSET_LAT"].ToString().Trim();                //sw = string.IsNullOrEmpty(sw) ? "null" : sw;                //kr = string.IsNullOrEmpty(kr) ? "null" : kr;                string strSql = string.Format("Insert into DBToExcel (LNG,LAT,OFFSET_LNG,OFFSET_LAT)                 Values ('{0}','{1}',{2},{3})", lng, lat, offsetLNG, offsetLAT);                string strConnection = ConfigurationManager.ConnectionStrings["ConnectionStr"].ToString();                SqlConnection sqlConnection = new SqlConnection(strConnection);                try                {                    // SqlConnection sqlConnection = new SqlConnection(strConnection);                    sqlConnection.Open();                    SqlCommand sqlCmd = new SqlCommand();                    sqlCmd.CommandText = strSql;                    sqlCmd.Connection = sqlConnection;                    SqlDataReader sqlDataReader = sqlCmd.ExecuteReader();                    i++;                    sqlDataReader.Close();                }                catch (Exception ex)                {                    throw ex;                }                finally                {                    sqlConnection.Close();                }                //if (opdb.ExcSQL(strSql))                //    i++;            }            return i;        }    }}

運行結果:


以上就是c#將Excel資料匯入到資料庫的實現代碼的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.