把Excel表中的數據導入到數據庫

Excel中的數據如圖:


數據庫表中的結構:


前臺頁面:


<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="導入" οnclick="Button1_Click" />
    </div>
    </form>
</body>


後臺代碼:
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.SqlClient;
using System.Data.OleDb;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    #region
    /// <summary>
    /// 把Excel中的數據存到DataTable
    /// </summary>
    /// <param name="uploadPath">Excel存放的路徑</param>
    /// <returns></returns>
    private DataTable GetExcelTable(string uploadPath)
    {
        DataSet ds = new DataSet();
        string Xls_ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + uploadPath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";//HDR爲yes 則第一數據行爲列名,爲no 則自動爲列加列名F1  F2  F3
        OleDbConnection Conn = new OleDbConnection(Xls_ConnStr);
        try
        {
            Conn.Open();
            string sql_str = "select * from [Sheet1$]";
            OleDbDataAdapter da = new OleDbDataAdapter(sql_str, Conn);
            da.Fill(ds, "excel_data");
            Conn.Close();
        }
        catch
        {
            if (Conn.State == ConnectionState.Open)
            {
                Conn.Close();
            }
            return null;
        }
        finally
        {
            Conn.Dispose();
        }
        if (ds == null)
        {
            return null;
        }
        if (ds.Tables.Count < 1)
        {
            return null;
        }
        return ds.Tables[0];
    }
    #endregion
    /// <summary>
    /// 把DataTable裏德數據添加到數據庫中的表裏
    /// </summary>
    /// <param name="table1"></param>
    public void InsertTable(DataTable table1)
    {
        string strInsert = "insert into ceshi values(" + GenrateSql(table1) + ")";
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString);
        conn.Open();
        SqlCommand com = new SqlCommand(strInsert, conn);

        for (int i = 0; i < table1.Rows.Count; i++)
        {
          
            for(int j=0;j<table1.Columns.Count;j++)
            {
                SqlParameter p1 = new SqlParameter("@value"+j.ToString(), SqlDbType.VarChar);
                p1.Value=table1.Rows[i][j].ToString();
                com.Parameters.Add(p1);
            }
            com.ExecuteNonQuery();
            com.Parameters.Clear();///在同一事務中若要多次執行同一SQL語句,必須在下一次執行前清理前一次的參數。否則會報變量名 @XXX 已聲明。變量名在批查詢或存儲過程內部必須唯一的錯誤
        }
        conn.Close();
    }
    /// <summary>
    /// SQL語句中的參數
    /// </summary>
    /// <param name="tbl"></param>
    /// <returns></returns>
    private string GenrateSql(DataTable tbl)
    {
         string temp="";
         for (int i = 0; i < tbl.Columns.Count; i++)
        {
           if(i==0)
               temp+="@value"+i.ToString();
             else
             {
             temp+=","+"@value"+i.ToString();
             }
        }
         return "("+temp+")";
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string path = @"C:UsersAdministratorDesktopstudent.xls";//Excel存放的位置
        GetExcelTable(path);
        InsertTable(GetExcelTable(path));
    }
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章