1. 程式人生 > >把excel自動匯入資料庫 根據excel內容自動建立資料庫表

把excel自動匯入資料庫 根據excel內容自動建立資料庫表

用c#  把excel的資料自動匯入sql資料庫 並根據excel的內容自動建立資料庫表,經過網上查資料和自己的努力做了出來 ,只不過是實現了功能並未優化程式碼,下面分享我的程式碼

首先建一個網站專案 ,其.aspx程式碼如下

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>Excel匯入SQL資料庫</title>
    <style type="text/css">
        #form1 {
            width: 409px;
            height: 156px;
        }
    </style>
</head>
<body style="text-align: center">
    <form id="form1" runat="server">
             <asp:FileUpload ID="FileUpload1" runat="server" Width="305px" /> 
           <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="chuanjiandebiaoming"></asp:TextBox>
          <asp:Button ID="Button3" runat="server" Text="建立表" OnClick="chuangjianbiao_Click"    /><br/>
           <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="xuanzebeidaorubiao" AutoPostBack="true" enabelViewState="true">
        </asp:DropDownList><br/>
       <asp:Button ID="Button1" runat="server" OnClick="daoru" Text="匯入SQL" /> <br/>    
        
         </form>
   
</body>
</html>
其介面如下圖

vs需要連線你要匯入的資料庫:步驟如下

1在檢視中點選伺服器資源管理器 

2.右擊資料連線  選擇新增連線

3


填寫伺服器名字  選擇驗證方式    輸入資料庫名稱     點選確定。

執行VS 後 通過瀏覽選擇你所需要匯入的excel表(表的格式xls),如果是新匯入的表則 需要填寫你想建立的表名然後點選建立。

如果想向資料庫中存在表匯入新的資料(匯入的資料格式和原來的必須相同即列名一樣且順序一致),點選瀏覽選擇你要匯入的excel表,在下拉選單中選擇你要匯入的資料庫中的表名,然後點選 “匯入SQL”

下拉選單中會顯示你所建立的所有表名

資料庫裡面要先建立一個表tableName 用來存放後來 有excel匯入時新建立的表的名字 和excel表的各列的欄位名稱 (這樣便於下次匯入時觀察原來匯入表的格式 可以把)


id列設為主鍵遞增  name列為建立的表的表名字   後面的則是每個表的列名   第一行不能為空否則會報錯

要在所建工程專案中新增一個資料夾(excel)用來存放匯入到的excel表 如下圖


下面 把一個表匯入資料庫

表的內容


匯入前資料庫裡面表結構如下圖


執行VS 然後按照1 選擇表    2  填寫新建表名  3點選 建立表

開啟資料庫可以看到  多了一個gg的表


表TableName 中的內容如下圖

下面則貼出後臺程式碼

using System;
using System.Collections.Generic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
    string text;
    int k, counts;
    string dropDownList1;
    DataSet ds;
    DataRow[] dr;
    string strConn = "Data Source=.;DataBase=lqy;Uid=sa;Pwd=318"; //連結SQL資料庫

    private SqlConnection cn = null;
    private SqlCommand cmd = null;
    private string sql = null;

    ArrayList list = new ArrayList();
    ArrayList list1 = new ArrayList();
    ArrayList dept = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(strConn);
        cn.Open();
        //   dropDownList1 = DropDownList1.SelectedItem.Text;
        bindTableName("TableName");// 引用自定義函式
        if (!IsPostBack)
        {
            DropDownList1.DataSource = dept;
            DropDownList1.DataBind();
        }
        dropDownList1 = DropDownList1.SelectedItem.Text;
    }
    protected void bindTableName(string tableName)
    {
        //獲取TableName的行數
        //  string strSql1 = "select count(*) from TableName;";
        string strSql1 = "select count(*) from " + tableName + ";";
        SqlCommand sqlcmd2 = new SqlCommand(strSql1, cn);
        int count2 = Convert.ToInt32(sqlcmd2.ExecuteScalar());
        //獲取name列的所有表名
        // string strSql2 = "select name from TableName;";
        string strSql2 = "select name from " + tableName + ";";
        SqlDataAdapter da = new SqlDataAdapter(strSql2, cn); //建立DataAdapter資料介面卡例項
        DataSet ds = new DataSet();//建立DataSet例項
        da.Fill(ds, "name");//使用DataAdapter的Fill方法(填充),呼叫SELECT命令           
        for (int i = 0; i < count2; i++)//動態繫結downlist的選項
        {
            string st = ds.Tables["name"].Rows[i]["name"].ToString();
            dept.Add(st);
        }
        //  cn.Close();//關閉資料庫
    }
    public DataSet ExecleDs(string filenameurl, string table)
    {
        string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 8.0; HDR=NO; IMEX=1'";
        OleDbConnection conn = new OleDbConnection(strConn);
        try
        {
            conn.Open();
        }
        catch (Exception e)
        {
            Response.Write("<script>alert('匯入內容:" + e.Message + "')</script>");
        }
        DataSet ds = new DataSet();
        string result = null;
        System.Data.DataTable dtName = null;

        try
        {
            dtName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
        }
        catch (Exception e)
        {
            Response.Write("<script>alert('匯入內容:" + e.Message + "')</script>");
        }


        // System.Data.DataTable dtName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
        foreach (DataRow dr1 in dtName.Rows)
        {
            result = dr1["TABLE_NAME"].ToString();//這個就是其中一個Sheet
            string strExcel = "select * from [" + result + "]";//這是你選定的sheet 
            OleDbDataAdapter odda = new OleDbDataAdapter(strExcel, conn);
            odda.Fill(ds, table);
        }
        return ds;
    }
    protected void daoru(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile == false)//HasFile用來檢查FileUpload是否有指定檔案
        {
            Response.Write("<script>alert('請您選擇Excel檔案')</script> ");
            return;//當無檔案時,返回
        }
        string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension獲得檔案的副檔名
        if (IsXls != ".xls")
        {
            Response.Write("<script>alert('只可以選擇Excel檔案')</script>");
            return;//當選擇的不是Excel檔案時,返回
        }

        insertNewshuju();
    }
    protected void chuangjianbiao_Click(object sender, EventArgs e)
    {

        string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension獲得檔案的副檔名
        if (IsXls != ".xls")
        {
            Response.Write("<script>alert('只可以選擇Excel檔案')</script>");
            return;//當選擇的不是Excel檔案時,返回
        }
        // 開啟資料庫連線
        string newConnectionString = "Integrated Security=SSPI;Initial Catalog=;Data Source=localhost;Uid=sa;Pwd=318";
        cn = new SqlConnection(newConnectionString);
        if (cn.State == ConnectionState.Open)
            cn.Close();
        cn.ConnectionString = strConn;
        cn.Open();

        string filename = DateTime.Now.ToString("yyyymmddhhMMss") + FileUpload1.FileName;              //獲取Execle檔名  DateTime日期函式
        string savePath = Server.MapPath(("~\\excel\\") + filename);//Server.MapPath 獲得虛擬伺服器相對路徑
        FileUpload1.SaveAs(savePath);                        //SaveAs 將上傳的檔案內容儲存在伺服器上       
        ds = ExecleDs(savePath, filename);         //呼叫自定義方法

        // DataRow[] dr = ds.Tables[0].Select();            //定義一個DataRow陣列
        dr = ds.Tables[0].Select();
        int rowsnum = ds.Tables[0].Rows.Count;
        k = ds.Tables[0].Columns.Count;  // 獲得excel表的列數

        string sqlcheck1 = "select count(*) from TableName where name = " + "'" + text + "'";  //建表是否存在
        SqlCommand sqlcmd1 = new SqlCommand(sqlcheck1, cn);
        int count1 = Convert.ToInt32(sqlcmd1.ExecuteScalar());
        //判斷新建表是否存在
        if (count1 >= 1)
        {
            Response.Write("<script>alert('表名已存在');location='default.aspx'</script></script> ");
            return;
        }
        else
        {
            creatTableName();//引用自定義函式  把建立的表的名稱以及列名存在tablename裡面

            if (rowsnum == 0)
            {
                Response.Write("<script>alert('Excel表為空表,無資料!')</script>");   //當Excel表為空時,對使用者進行提示
                return;
            }
            else
            {
                insertshuju();//引用自定義函式  把資料匯入資料庫
            }
            cn.Close();
        }
    }
    protected void creatTableName()
    {
        string str = null;
        string str1 = null;
        string str2 = null;
        string insert1 = null;
        for (int i = 0; i < k; i++)
        {
            list.Add(dr[0][i].ToString());//讀取第一行列名存在list中
            str = str + "'" + dr[0][i].ToString() + "'" + ","; //把列數字段名稱拼接起來
        }

        int col = 14;  //TableName的列數(除去主鍵列和表名稱列)
        for (int i = 0; i < col - k; i++)
        {
            str1 = str1 + "'" + "'" + ","; //列數不夠的插入null
        }
        sql = "CREATE TABLE " + text + "(qid int identity(1,1) primary key )"; //建立新表的主鍵            
        cmd = new SqlCommand(sql, cn);
        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (Exception e)
        {
            Response.Write("<script>alert('匯入內容:" + e.Message + "')</script>");
            return;
        }
        //動態的新增列數
        for (int kk = 0; kk < k; kk++)
        {
            sql = "ALTER TABLE " + text + " ADD " + list[kk] + " nvarchar(Max)  null";
            SqlCommand cmd1 = new SqlCommand(sql, cn);
            try
            {
                cmd1.ExecuteNonQuery();
            }
            catch (MembershipCreateUserException ex)
            {
                Response.Write("<script>alert('匯入內容:" + ex.Message + "')</script>");
                return;
            }
        }
        //把新建表的  名稱 以及列的欄位名稱存在 TableName 裡面 
        str2 = str + str1;
        str2 = "'" + text + "'" + "," + str2.Substring(0, str2.Length - 1);
        insert1 = "insert  into  TableName values(" + str2 + " )";
        cmd = new SqlCommand(insert1, cn);
        cmd.ExecuteNonQuery();
        //清空拼接字元 便於下次迴圈使用
        str = null;
        str1 = null;
        str2 = null;

    }
    protected void insertshuju()
    {

        string insertstr = null;
        string val = null;
        string val1 = null;
        string val2 = null;
        string val3 = null;
        int count1 = 0; //重複條數
        int count2 = 0; //插入條數
        //像新建表裡面插入資料
        for (int i = 1; i < dr.Length; i++)
        {
            for (int kkk = 0; kkk < k; kkk++)
            {

                val = val + "'" + dr[i][kkk].ToString() + "'" + ",";
                val3 = val3 + "'" + "'" + ",";
                val1 = dr[i][0].ToString(); //獲取第一行和第三行進行驗證
                val2 = dr[i][2].ToString();
            }
            val = val.Substring(0, val.Length - 1);//截去拼接字元最後多的一個逗好
            val3 = val3.Substring(0, val3.Length - 1);
            if (val == val3)
            {
                val = null;
                val3 = null;
                continue;
            }
            else
            {
                string sqlcheck = "select count(*) from " + text + " where " + list[0] + "='" + val1 + "' And " + list[2] + "='" + val2 + "'";  //檢查使用者是否存在
                SqlCommand sqlcmd = new SqlCommand(sqlcheck, cn);
                int count = Convert.ToInt32(sqlcmd.ExecuteScalar());
                if (count < 1)
                {
                    insertstr = "insert  into  " + text + "  values(" + val + " )";
                    SqlCommand cmd2 = new SqlCommand(insertstr, cn);
                    try
                    {
                        cmd2.ExecuteNonQuery();
                        count2++;
                    }
                    catch (MembershipCreateUserException ex)       //捕捉異常
                    {
                        Response.Write("<script>alert('匯入內容:" + ex.Message + "')</script>");
                    }
                }
                else
                {
                    count1++;
                    // Response.Write("<script>alert('內容重複!已經過濾');location='default.aspx'</script></script> ");
                    val = null;
                    val3 = null;
                    continue;
                }
                val3 = null;
                val = null;
            }
        }
        if (count1 > 0)
        {
            Response.Write("<script>alert('Excle表匯入成功 " + count2 + "條! 內容重複" + count1 + "條 !已經過濾');location='default.aspx'</script></script> ");
        }
        else
        {
            Response.Write("<script>alert('Excle表匯入成功" + count2 + "條!');location='default.aspx'</script>");
        }

        count2 = 0;
        count1 = 0;
    }
    protected void insertNewshuju()
    {
        // 開啟資料庫連線
        string newConnectionString = "Integrated Security=SSPI;Initial Catalog=;Data Source=localhost;Uid=sa;Pwd=318";
        cn = new SqlConnection(newConnectionString);
        if (cn.State == ConnectionState.Open)
            cn.Close();
        cn.ConnectionString = strConn;
        cn.Open();

        string filename = DateTime.Now.ToString("yyyymmddhhMMss") + FileUpload1.FileName;              //獲取Execle檔名  DateTime日期函式
        string savePath = Server.MapPath(("~\\excel\\") + filename);//Server.MapPath 獲得虛擬伺服器相對路徑
        FileUpload1.SaveAs(savePath);                        //SaveAs 將上傳的檔案內容儲存在伺服器上       
        ds = ExecleDs(savePath, filename);         //呼叫自定義方法

        // DataRow[] dr = ds.Tables[0].Select();            //定義一個DataRow陣列
        dr = ds.Tables[0].Select();
        int rowsnum = ds.Tables[0].Rows.Count;
        k = ds.Tables[0].Columns.Count;  // 獲得excel表的列數

        string insertstr = null;
        string val = null;
        string val1 = null;
        string val2 = null;
        string val3 = null;
        int count1 = 0; //重複條數
        int count2 = 0; //插入條數
        //像新建表裡面插入資料
        for (int i = 1; i < dr.Length; i++)
        {
            for (int kkk = 0; kkk < k; kkk++)
            {

                val = val + "'" + dr[i][kkk].ToString() + "'" + ",";
                val3 = val3 + "'" + "'" + ",";
                val1 = dr[i][0].ToString(); //獲取第一行和第三行進行驗證
                val2 = dr[i][2].ToString();
            }
            val = val.Substring(0, val.Length - 1);//截去拼接字元最後多的一個逗好
            val3 = val3.Substring(0, val3.Length - 1);
            if (val == val3)
            {
                val = null;
                val3 = null;
                continue;
            }
            else
            {
                //  string sss = "select 欄位順序='欄位'+ltrim(colid),欄位名=name from syscolumns where id=object_id('" + dropDownList1 + "')";
                string sss = "select * from " + dropDownList1;
                SqlCommand sqlcmd3 = new SqlCommand(sss, cn);
                SqlDataAdapter sad = new SqlDataAdapter(sqlcmd3);
                DataSet dds = new DataSet();
                sad.Fill(dds, "check");
                string sds1 = ds.Tables[0].Rows[0][0].ToString(); //獲取第一三欄位進行檢驗
                string sds3 = ds.Tables[0].Rows[0][2].ToString();


                string sqlcheck = "select count(*) from " + dropDownList1 + " where " + sds1 + "='" + val1 + "' And " + sds3 + "='" + val2 + "'";  //檢查使用者是否存在
                SqlCommand sqlcmd = new SqlCommand(sqlcheck, cn);
                int count = Convert.ToInt32(sqlcmd.ExecuteScalar());


                if (count < 1)
                {
                    insertstr = "insert  into  " + dropDownList1 + "  values(" + val + " )";
                    SqlCommand cmd2 = new SqlCommand(insertstr, cn);
                    try
                    {
                        cmd2.ExecuteNonQuery();
                        count2++;
                    }
                    catch (MembershipCreateUserException ex)       //捕捉異常
                    {
                        Response.Write("<script>alert('匯入內容:" + ex.Message + "')</script>");
                    }
                }
                else
                {
                    count1++;
                    //  Response.Write("<script>alert('內容重複" + count1 + "條 !已經過濾');location='default.aspx'</script></script> ");
                    val = null;
                    val3 = null;
                    continue;
                }

                val3 = null;
                val = null;
            }
        }
        if (count1 > 0)
        {
            Response.Write("<script>alert('Excle表匯入成功 " + count2 + "條! 內容重複" + count1 + "條 !已經過濾');location='default.aspx'</script></script> ");
        }
        else
        {
            Response.Write("<script>alert('Excle表匯入成功" + count2 + "條!');location='default.aspx'</script>");
        }

        count2 = 0;
        count1 = 0;
    }
    protected void xuanzebeidaorubiao(object sender, EventArgs e)
    {
        dropDownList1 = DropDownList1.Items.ToString();
    }
   
    protected void chuanjiandebiaoming(object sender, EventArgs e)
    {
        text = TextBox1.Text;
    }
}