我如何计算excel列名?

时间:2012-10-30 12:27:39

标签: c#

我想将数据从excel导入到sql,在此操作中,如果用户可以添加一个额外的列,我该如何检查新添加的列,同时在sql表中还添加了相同的新列列名如excel sheet ...

我可以完成阅读excel列计数 - 就像我的编码

 protected void btn_upload_Click(object sender, EventArgs e)
    {
        //Add Path to Local system dynamically
        string path = string.Empty;

        path = Server.MapPath("~//files//") + Fup_Excel.PostedFile.FileName;

        Fup_Excel.SaveAs(path);
        //-----------------Execl Connection & Count Part-------------------------------------
        //create Oledb connection for Excel Fetch
        OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 8.0");


        OleDbCommand olcmd = new OleDbCommand("select * from [sheet1$]", oconn);//create command for select excel file

        OleDbDataAdapter adapter = new OleDbDataAdapter();

        adapter.SelectCommand = olcmd;//adap the command

        DataSet ds = new DataSet();//collection of data

        adapter.Fill(ds);//data's are filled to dataset

        string count = ds.Tables[0].Columns.Count.ToString();//taking the Excel sheet column count



    }

这里我完成了从sql表中取得的数量 那段代码是

 SqlConnection sconn = new SqlConnection(@"Data Source=C07-PC\SQLEXPRESS;Initial Catalog=excel;User ID=sa;Password=**********");
        string asdf = null;
        SqlCommand scmd = new SqlCommand();
        scmd.CommandText = "select count(*) from information_schema.columns where table_name='table_1'";
        scmd.Connection = sconn;
        sconn.Open();
        SqlDataReader sr = null;
        sr = scmd.ExecuteReader();
        while (sr.Read())
        {

              asdf =sr[0].ToString();

        }

从这里开始,我不知道如何检查excel中新添加的列?那个ssame名称我想在sql表中插入列...

1 个答案:

答案 0 :(得分:0)

从excel中检索所有列后,您需要检查SQL数据库中的每个列是否存在该列。如果不存在则添加到sql数据库。