把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;
    }
}


  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值