Excelデータ読み込みSQL XML自動生成ヘッダ

361555 ワード

出張の際にお客様の要求に応じて、Excelファイル内のデータを一括してデータベースにインポートします.
通常の方法では、データ・テーブルを作成し、データベースにマッピングされたデータ・モデルを作成し、データ・アクセス・レイヤ、ビジネス・レイヤ、各テーブルに表示ページを作成する必要があります.こういったやり方で費やす
の時間が多くて、後で取引先がまた新しい表を導入する必要があるとは言わないで、それでは3階のステップに従って一歩一歩しなければなりませんか?答えは否定的だ.ここでは、より柔軟な
すべての機能を達成する方法で、拡張性にも優れており、任意のプログラムに移植して使用することができます.
くだらないことを言わずにプログラムを直接見て、プログラムは最高の解釈です.
 
このプログラムはXMLでデータベースフィールドとインタフェースに表示するヘッダーを保存します.
まず、Webサイトのルートディレクトリの下にXMLファイルを作成して、動的に生成されたデータテーブルと、各列とヘッダーに対応する中国語名を保存します.
<?xml version="1.0" encoding="utf-8"?>

<DBTable>

  <table>

    <CName>      </CName>

    <EName>rzzgtz</EName>

    <Identity>R_Id</Identity>

    <columns>

      <eColumn eName="xuhao" eType="nvarchar(MAX)" cName="  " eLength="varchar(10)" />

      <eColumn eName="Ztype" eType="nvarchar(MAX)" cName="    " eLength="varchar(10)" />

      <eColumn eName="bM" eType="nvarchar(MAX)" cName="  " eLength="varchar(10)" />

      <eColumn eName="Name" eType="nvarchar(MAX)" cName="  " eLength="varchar(10)" />

      <eColumn eName="Gender" eType="nvarchar(MAX)" cName="  " eLength="varchar(10)" />

      <eColumn eName="CID" eType="nvarchar(MAX)" cName="    " eLength="varchar(10)" />

      <eColumn eName="tTemp" eType="nvarchar(MAX)" cName="    " eLength="varchar(10)" />

      <eColumn eName="ziwu" eType="nvarchar(MAX)" cName="  /  " eLength="varchar(10)" />

      <eColumn eName="fzjg" eType="nvarchar(MAX)" cName="    " eLength="varchar(10)" />

      <eColumn eName="XCID" eType="nvarchar(MAX)" cName="    " eLength="varchar(10)" />

      <eColumn eName="Qtime" eType="nvarchar(MAX)" cName="    " eLength="varchar(10)" />

      <eColumn eName="fTime" eType="nvarchar(MAX)" cName="    " eLength="varchar(10)" />

      <eColumn eName="Other" eType="nvarchar(MAX)" cName="  " eLength="varchar(10)" />

    </columns>

  </table>

<DBTable>

DBTableノードはルートノード内部のtableであり、データテーブルの関連属性を保存します.
ノードは、中国語名であり、メニュー名でもあります.
ノードは、名前とデータテーブルの表示が1つずつ対応して保存されます.   
ノードは、テーブルのプライマリ・キー名を保存します.
ノードは、データテーブルの対応するデータ列属性を保存します.
内部ノード
属性:eName[データベース内の名前],eType[データ型]cName[ヘッダ名]eLengthの有無の属性
以上はXMLテーブル構造のいくつかの説明である.
XML対ノードのいくつかの操作と取得を専門に操作するクラスが必要です.
/**

 *    2014-02-19 15:06

 *XML       

 *    :                

 */



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

//

using System.Xml;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Configuration;







namespace CommonLib

{

    public class XMLBase : Page

    {

        //    XMLDom  

        XmlDocument xmlDoc = null;

        XmlNode root = null;

        /// <summary>

        ///     

        /// </summary>

        string xmlPath = ConfigurationManager.ConnectionStrings["XMLPath"].ConnectionString;

        /// <summary>

        ///      xml  

        /// </summary>

        public void LoadDome()

        {

            xmlDoc = new XmlDocument();

            string path = Server.MapPath(xmlPath);//       

            xmlDoc.Load(path);//    

            root = xmlDoc.SelectSingleNode("DBTable");

        }

        /// <summary>

        ///  XML       

        /// </summary>

        /// <param name="cName">    </param>

        /// <param name="eName">        </param>

        public void InsertNode(string cName, string eName, string id)

        {

            XmlElement table = xmlDoc.CreateElement("table");

            //     

            XmlElement c_Name = xmlDoc.CreateElement("CName");

            c_Name.InnerText = cName;

            table.AppendChild(c_Name);

            //     

            XmlElement e_Name = xmlDoc.CreateElement("EName");

            e_Name.InnerText = eName;

            table.AppendChild(e_Name);

            //    

            XmlElement iditent = xmlDoc.CreateElement("Identity");

            iditent.InnerText = id;

            table.AppendChild(iditent);

            root.AppendChild(table);

            string path = Server.MapPath(xmlPath);//       

            xmlDoc.Save(path);//            

        }







        /// <summary>

        ///            

        /// </summary>

        /// <param name="cTable">      </param>

        /// <param name="eTableName">      </param>

        /// <param name="eName">     </param>

        /// <param name="eType">    </param>

        /// <param name="cName">     </param>

        /// <param name="eLenght">    </param>

        public void InsertNode(string cTable, string eTableName, string eName, string eType, string cName, string eLenght)

        {

            //      

            XmlNode fatherNode = xmlDoc.SelectSingleNode("DBTable");

            XmlNode nodeRoot = null;



            for (int i = 0; i < fatherNode.ChildNodes.Count; i++)

            {

                nodeRoot = fatherNode.ChildNodes[i];

                var c_Name = nodeRoot.ChildNodes[0].InnerText;

                var e_Name = nodeRoot.ChildNodes[1].InnerText;

                if (cName == c_Name && e_Name == eName)

                {

                    break;

                }

            }

            //        

            var se = (nodeRoot as XmlNode).SelectSingleNode("columns");

            XmlElement columns = null;

            if (se == null)

            {

                columns = xmlDoc.CreateElement("columns");

            }

            else

            {

                columns = (se as XmlElement);

            }



            XmlElement eColumn = xmlDoc.CreateElement("eColumn");

            eColumn.SetAttribute("eName", eName);

            eColumn.SetAttribute("eType", eType);

            eColumn.SetAttribute("cName", cName);

            eColumn.SetAttribute("eLength", eLenght);

            columns.AppendChild(eColumn);

            nodeRoot.AppendChild(columns);

            string path = Server.MapPath(xmlPath);//       

            xmlDoc.Save(path);//            









        }



        /// <summary>

        ///               

        /// </summary>

        /// <param name="cName">    </param>

        /// <param name="eName">        </param>

        /// <returns>    false      true</returns>

        public bool CheckNode(string cName, string eName)

        {

            bool resout = true;

            XmlNode nodeRoot = xmlDoc.SelectSingleNode("DBTable");//     

            for (int i = 0; i < nodeRoot.ChildNodes.Count; i++)

            {

                var tab = nodeRoot.ChildNodes[i];

                var c_Name = tab.ChildNodes[0].InnerText;

                var e_Name = tab.ChildNodes[1].InnerText;



                if (cName == c_Name || e_Name == eName)

                {

                    resout = false;

                }

            }

            return resout;

        }

        /// <summary>

        ///     

        /// </summary>

        /// <param name="cName"></param>

        /// <param name="eName"></param>

        /// <param name="res"></param>

        public void DeleteNode(string cName, string eName, bool res)

        {

            XmlNode node = GetXMLNode(cName, eName);

            if (node != null)

            {

                XmlNode par = node.ParentNode;

                if (res)

                {

                    string sql = " drop table " + eName;

                    par.RemoveChild(par);

                }

                else

                {

                    par.RemoveChild(node);

                }

            }

            string path = Server.MapPath(xmlPath);//       

            xmlDoc.Save(path);//            

        }

        /// <summary>

        ///             

        /// </summary>

        /// <param name="cName">    </param>

        /// <param name="eName">    </param>

        /// <returns>      </returns>

        public XmlNode GetXMLNode(string cName, string eName)

        {

            XmlNode resout = null;

            XmlNode nodeRoot = xmlDoc.SelectSingleNode("DBTable");//     

            for (int i = 0; i < nodeRoot.ChildNodes.Count; i++)

            {

                var tab = nodeRoot.ChildNodes[i];

                var c_Name = tab.ChildNodes[0].InnerText;

                var e_Name = tab.ChildNodes[1].InnerText;



                if (cName == c_Name && e_Name == eName)

                {

                    resout = tab;

                    break;

                }

            }

            return resout;

        }





        /// <summary>

        ///     

        /// </summary>

        /// <param name="cName">y   </param>

        /// <param name="EName">   </param>

        /// <returns></returns>

        public bool UpdateNode(string cName, string eName)

        {

            bool resoult = false;

            XmlNode nodeRoot = xmlDoc.SelectSingleNode("DBTable");//     

            for (int i = 0; i < nodeRoot.ChildNodes.Count; i++)

            {

                var tab = nodeRoot.ChildNodes[i];

                if (tab.ChildNodes[1].InnerText == eName)

                {

                    tab.ChildNodes[0].InnerText = cName;

                    string path = Server.MapPath(xmlPath);//       

                    xmlDoc.Save(path);//            

                    resoult = true;

                }



            }

            return resoult;



        }



        /// <summary>

        ///        

        /// </summary>

        /// <param name="eName">    </param>

        /// <param name="cName">    </param>

        /// <returns> ’¦‘                  ‘,’                ‘[’   </returns>

        public string Check(string eName, string cName)

        {

            string resout = "";



            XmlNode node = GetXMLNode(cName, eName);



            if (node != null)

            {

                //     

                var columns = node.SelectSingleNode("columns");

                for (int i = 0; i < columns.ChildNodes.Count; i++)

                {

                    resout += columns.ChildNodes[i].Attributes[0].Value.ToString() + ",";

                }

                resout = resout.Substring(0, resout.Length - 1);

                resout += "¦";

                for (int i = 0; i < columns.ChildNodes.Count; i++)

                {

                    resout += columns.ChildNodes[i].Attributes[2].Value.ToString() + "[";

                }

                resout = resout.Substring(0, resout.Length - 1);

            }



            return resout;

        }



        #region      2014-02-24



        /// <summary>

        ///           

        /// </summary>

        /// <returns>  xml             【   ,   】           </returns>

        public List<XMLTableInfo> GetTableList()

        {

            List<XMLTableInfo> tableList = new List<XMLTableInfo>();

            var node = xmlDoc.SelectSingleNode("DBTable");

            for (int i = 0; i < node.ChildNodes.Count; i++)

            {

                XMLTableInfo tb = new XMLTableInfo();

                tb.CName = node.ChildNodes[i].ChildNodes[0].InnerText.ToString();

                tb.EName = node.ChildNodes[i].ChildNodes[1].InnerText.ToString();

                tableList.Add(tb);

            }

            return tableList;

        }



        public string GetIdentity(string eName, string cName)

        {

            string iditent = "";

            //    

            XmlNode node = GetXMLNode(cName, eName);

            if (node != null)

            {

                iditent = node.SelectSingleNode("Identity").InnerText;

            }

            return iditent;

        }

        #endregion



    }



    /// <summary>

    /// XML        

    /// </summary>

    public class XMLTableInfo

    {

        /// <summary>

        ///     

        /// </summary>

        public string CName { get; set; }

        /// <summary>

        ///     

        /// </summary>

        public string EName { get; set; }

    }}

 
 Web.Config
<?xml version="1.0" encoding="utf-8"?>



<!--

         ASP.NET          ,   

  http://go.microsoft.com/fwlink/?LinkId=169433

  -->



<configuration>

  <connectionStrings>

    <!--       -->

    <add name="SqlServer" connectionString="server=192.168.1.124;database=ExcelToSqlserver; uid=sa; pwd=123;"/>

    <!--XML    -->

    <add name="XMLPath" connectionString="~/DBTablePage.xml" /> 

    <!--EXCEL        -->

    <add name="ExcelUpLoadPath" connectionString="~/upload/EXCEL/" />

    <add name="RecorddPath" connectionString="../upload/attached/" />

   

   

    

  </connectionStrings>

    <system.web>

      <compilation debug="true" targetFramework="4.0" />

      <httpRuntime requestValidationMode="2.0" />

    </system.web>



</configuration>

 
     EXCEL Helper 
/**

 *    2014-02-10

 *    excel     

 *    ,    

 *      

 */



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.SqlClient;

using System.Data;

using System.Data.OleDb;

using System.IO;



using System.Configuration;

using System.Web.UI.WebControls;









namespace CommonLib

{

    public class ExcelHelper : System.Web.UI.Page

    {

        static string conStr = ConfigurationManager.ConnectionStrings["SqlServer"].ToString();

        static SqlConnection con = new SqlConnection(conStr);



        /// <summary>

        ///                   

        /// </summary>

        /// <param name="path">      </param>

        /// <returns>      </returns>

        public static OleDbConnection GetConnection(string path)

        {

            /*Office 2007*/

            string ace = "Microsoft.ACE.OLEDB.12.0";

            /*Office 97 - 2003*/

            string jet = "Microsoft.Jet.OLEDB.4.0";

            string xl2007 = "Excel 12.0 Xml";

            string xl2003 = "Excel 8.0";

            string imex = "IMEX=1";

            /* csv */

            string text = "text";

            string fmt = "FMT=Delimited";

            string hdr = "NO";

            string conn = "Provider={0};Data Source={1};Extended Properties=\"{2};HDR={3};{4}\";";

            string ext = Path.GetExtension(path);



            DataTable dt = new DataTable("data");

            switch (ext.ToLower())

            {

                case ".xlsx":

                    conn = String.Format(conn, ace, Path.GetFullPath(path), xl2007, hdr, imex);

                    break;

                case ".xls":

                    conn = String.Format(conn, jet, Path.GetFullPath(path), xl2003, hdr, imex);

                    break;

                case ".csv":

                    conn = String.Format(conn, jet, Path.GetDirectoryName(path), text, hdr, fmt);

                    //sheet = Path.GetFileName(path);

                    break;

                default:

                    throw new Exception("File Not Supported!");

            }

            OleDbConnection con = new OleDbConnection(conn);

            return con;

        }





        /// <summary>

        ///   excel   sheet  ,  excel DataTable

        /// </summary>

        public static DataTable GetExcelDataTable(string path, string tname)

        {

            string select = string.Format("SELECT * FROM [{0}$]", tname);

            string ext = Path.GetExtension(path);

            OleDbDataAdapter oda;

            DataTable dt = new DataTable("data");

            OleDbConnection con = GetConnection(path);

            con.Open();

            oda = new OleDbDataAdapter(select, con);



            oda.Fill(dt);

            con.Close();

            return dt;

        }



        /// <summary>

        ///        Sheet  

        /// 2014-02-26

        ///     

        /// </summary>

        /// /// <param name="saveName">        </param>

        /// <returns>Sheet    </returns>

        public static List<string> GetExcelSheetName(string saveName)

        {

            List<string> list = null;

            Microsoft.Office.Interop.Excel.ApplicationClass excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

            Microsoft.Office.Interop.Excel.Workbooks wbs = excelApp.Workbooks;

            Microsoft.Office.Interop.Excel.Workbook wb = wbs.Open(saveName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            int count = wb.Worksheets.Count;

            if (count > 0)

            {

                list = new List<string>();

                for (int i = 0; i < count; i++)

                {

                    string name = ((Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[i]).Name;

                    list.Add(name);

                }

                wb.Close(null, null, null);

                excelApp.Quit();

                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);

                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);

                System.Runtime.InteropServices.Marshal.ReleaseComObject(wbs);

                excelApp = null;

                wbs = null;

                wb = null;

                GC.Collect();

            }

            return list;

        }



        /// <summary>

        ///   Excel            

        /// 2014-02-26

        /// </summary>

        /// <param name="dTable">DataTable</param>

        /// <param name="rowIndex">       </param>

        /// <param name="colIndex">       </param>

        /// <param name="saveName">Excel        </param>

        /// <param name="sheetName">Sheet      Sheet1</param>

        /// <returns>            </returns>

        public static List<string> GetExcelDate(int rowIndex, int colIndex, string saveName, string sheetName = "Sheet1")

        {

            List<string> list = null;

            DataTable dtabe = ExcelHelper.GetExcelDataTable(saveName, sheetName);

            int icolums = dtabe.Columns.Count;

            int irows = dtabe.Rows.Count;

            //        

            if (irows > rowIndex)

            {

                list = new List<string>();



                for (int j = rowIndex; j < irows; j++)

                {



                    string da = "";

                    for (int i = colIndex; i < icolums; i++)

                    {



                        da += dtabe.Rows[j][i].ToString() + ",";

                    }



                    if (da.Length != icolums)//      

                    {

                        da = da.Substring(0, da.Length - 1);

                        list.Add(da);



                    }



                }

            }

            return list;

        }



        /// <summary>

        ///   Excel                   

        /// 2014-02-26

        /// </summary>

        /// <param name="eName">         </param>

        /// <param name="cName">        </param>

        /// <param name="saveName">  Excel             </param>

        /// <param name="sheetName">Excel    Sheet  </param>

        /// <returns>      ,         ,               </returns>

        public string CheckExcelTitle(string eName, string cName, string saveName, string sheetName = "Sheet1")

        {

            string resout = "";

            XMLBase xmlBase = new XMLBase();

            xmlBase.LoadDome();

            //         

            string che = xmlBase.Check(eName, cName);

            string[] columesInfo = null;

            if (che != "")

            {



                columesInfo = che.Split('¦');

            }

            string ename = columesInfo[0];

            string cname = columesInfo[1];

            //          

            // ename = ename.Substring(0, ename.Length - 1);

            //  XML    

            // cname = cname.Substring(0, cname.Length - 1);

            string[] TbE_name = ename.Split(',');

            string[] TbC_name = cname.Split('[');

            DataTable dtabe = ExcelHelper.GetExcelDataTable(saveName, sheetName);

            int icolums = dtabe.Columns.Count;

            int irows = dtabe.Rows.Count;

            //    

            List<string> list = new List<string>();

            string na = "";

            for (int i = 0; i < icolums; i++)

            {

                na += dtabe.Rows[0][i].ToString() + "+";

                list.Add(dtabe.Rows[0][i].ToString());

            }



            if (list.Count != TbC_name.Length)

            {

                resout = "";

            }

            else

            {

                for (int i = 0; i < TbC_name.Length; i++)

                {

                    if (TbC_name[i] != list[i])

                    {

                        string mes = " " + (i + 1) + "" + TbC_name[i] + "";

                        resout += mes;

                    }

                }

            }



            return resout;



        }





        /// <summary>

        ///   SQl   

        /// </summary>

        /// <param name="sql"></param>

        /// <returns></returns>

        public static DataSet GetDataSet(string sql)

        {

            if (sql == "")

            {

                return null;

            }

            SqlConnection con = new SqlConnection();

            con.ConnectionString = conStr;

            con.Open();

            SqlDataAdapter adp = new SqlDataAdapter(sql, con);

            DataSet ds = new DataSet();

            adp.Fill(ds, "table");

            con.Close();

            return ds;

        }



        #region 2014-02-28       

        /// <summary>

        ///       Sql  

        /// 2014-02-26

        /// </summary>

        /// <returns>          Sql       </returns>

        public static string InserToSqlQuerystring(string eName, string cName)

        {

            string sql = "";

            XMLBase xml = new XMLBase();

            xml.LoadDome();

            //    

            string che = xml.Check(eName, cName);

            if (che != "")

            {

                sql = "insert into  " + eName + "  (";

                //    

                string colums = che.Split('¦')[0];

                sql += colums + ") values  ";

            }

            return sql;

        }



        /// <summary>

        ///       

        /// </summary>

        /// <param name="eName">    </param>

        /// <param name="cName">    </param>

        /// <param name="id">     Id  </param>

        /// <returns></returns>

        public static string DeleteQuerystring(string eName, string cName, string id)

        {

            string sql = "";

            //        

            XMLBase xml = new XMLBase();

            xml.LoadDome();

            //    

            string che = xml.GetIdentity(eName, cName);

            if (id.IndexOf(',') == -1)

            {

                sql = "delete " + eName + " where " + che + "= " + id;

            }

            else

            {

                sql = "delete " + eName + " where " + che + " in ( " + id + " )";

            }



            return sql;

        }

        /// <summary>

        ///         

        /// </summary>

        /// <param name="eName">   </param>

        /// <param name="cName">   </param>

        /// <param name="id">  ID</param>

        /// <returns>   </returns>

        public static string UpdateQueryString(string eName, string cName, int id)

        {

            string sql = "";

            XMLBase xml = new XMLBase();

            xml.LoadDome();

            //    

            string che = xml.Check(eName, cName);

            sql = "update  " + eName + "   set  ";

            if (che != "")

            {

                string[] colums = che.Split('¦')[0].Split(',');

                for (int i = 0; i < colums.Length; i++)

                {

                    sql += colums[i] + "= {" + i + "} ,";

                }

            }

            sql = sql.Substring(0, sql.Length - 1);

            sql += "  where " + xml.GetIdentity(eName, cName) + "=" + id;

            return sql;



        }



        /// <summary>

        ///        

        /// </summary>

        /// <param name="eName">    </param>

        /// <param name="cName">    </param>

        /// <param name="id">  Id</param>

        /// <returns></returns>

        public static string GetModelQueryString(string eName, string cName, int id)

        {

            string sql = "";

            XMLBase xBase = new XMLBase();

            xBase.LoadDome();

            sql = "select * from " + eName + "  where " + xBase.GetIdentity(eName, cName) + " =" + id;

            return sql;

        }

        //2014-03-03       

        /// <summary>

        ///          

        /// </summary>

        /// <param name="eName"></param>

        /// <param name="cName"></param>

        /// <returns></returns>

        public static string GetCountQueryString(string eName, string where)

        {

            string countsql = "select count(*) from  " + eName + "   ";

            if (where != "")

            {

                countsql += " where  " + where;

            }



            return countsql;

        }



        /// <summary>

        ///        

        /// </summary>

        /// <param name="eName"></param>

        /// <param name="cName"></param>

        /// <param name="strWhere">    </param>

        /// <param name="orderby"> </param>

        /// <param name="pageIndex"></param>

        /// <param name="pageSize"></param>

        /// <returns></returns>

        public static string GetPageQueryStrong(string eName, string cName, string strWhere, string orderby, int pageIndex, int pageSize)

        {

            StringBuilder strSql = new StringBuilder();

            strSql.Append("SELECT * FROM ( ");

            strSql.Append(" SELECT ROW_NUMBER() OVER (");

            if (!string.IsNullOrEmpty(orderby.Trim()))

            {

                strSql.Append("order by T." + orderby);

            }

            else

            {

                XMLBase ba = new XMLBase();

                ba.LoadDome();



                strSql.Append("order by T." + ba.GetIdentity(eName, cName) + " desc");

            }

            strSql.Append(")AS Row, T.*  from  " + eName + "  T ");

            if (!string.IsNullOrEmpty(strWhere.Trim()))

            {

                strSql.Append(" WHERE " + strWhere);

            }

            strSql.Append(" ) TT");

            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", (pageIndex - 1) * pageSize + 1, pageIndex * pageSize);

            return strSql.ToString();

        }

        #endregion



        #region 2014-02-28     

        /// <summary>

        ///          

        /// 2014-02-26

        /// </summary>

        /// <param name="sql">   Sql             </param>

        /// <returns></returns>

        public static int ExecuteNonQuery(string sql)

        {



            int resour = 0;



            try

            {

                con.Open();

                SqlCommand cmd = new SqlCommand(sql, con);

                resour = cmd.ExecuteNonQuery();

                con.Close();

                GC.Collect();

            }

            catch (Exception)

            {

                con.Close();



            }

            return resour;



        }



        /// <summary>

        ////// </summary>

        /// <param name="sql"></param>

        /// <returns></returns>

        public static int ExecSclaer(string sql)

        {

            int resour = 0;

            try

            {

                con.Open();

                SqlCommand cmd = new SqlCommand(sql, con);

                object obj = cmd.ExecuteScalar();

                resour = Convert.ToInt32(obj);

                con.Close();

                GC.Collect();

            }

            catch (Exception)

            {

                con.Close();

                GC.Collect();

            }

            return resour;

        }



        /// <summary>

        ///       

        /// </summary>

        /// <param name="sql"></param>

        /// <returns>      '¦'  </returns>

        public static string SelectToSqlModel(string sql)

        {

            string vals = "";

            SqlCommand cmd = new SqlCommand(sql, con);

            con.Open();

            SqlDataReader read = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            if (read.HasRows)

            {



                while (read.Read())

                {

                    for (int i = 0; i < read.FieldCount; i++)

                    {

                        vals += read[i].ToString() + "¦";

                    }

                }

            }

            read.Close();

            con.Close();

            GC.Collect();

            vals = vals.Substring(0, vals.Length - 1);

            return vals;

        }

        #endregion



        #region Excel     

        public static void exportTemper(string eName, string cName, string saveName, string sql)

        {

           //    

        }

        #endregion





    }

}

 
 

ローカルコンピュータに登録されていない「Microsoft.ACE.oledb.12.0」プロバイダエラーが発生したコンピュータ生がデータインポートを行いました
処理方法:解決方法:
http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exeへダウンロードします.そしてインストールすればいいです.
このプラグインをインストールするとoffice 2010のファイルがサポートされます
キーページコード:
データテーブルページの作成
フロントインタフェース;
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExcelToSqlserver.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>XML    </title>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <h3></h3>

            <p><asp:TextBox ID="txtCname" runat="server"></asp:TextBox>

                <br />

                <br /><input type="text" id="txtEName" runat="server"  onkeyup="this.value=this.value.replace(/[^a-zA_Z_]/,'');" /><br />

                <br /><input type="text" runat="server" id="txtIditent" size="20" onkeyup="this.value=this.value.replace(/[^a-zA-Z_]/,'');" /><br />

                <br />

                <asp:Button ID="btnAdd" runat="server" OnClick="Button1_Click" Enabled="false" Text="  " Style="height: 21px" />

                &nbsp;

        <asp:Button ID="btnChange" runat="server" OnClick="Button2_Click" Enabled="false" Text="  " />

                &nbsp;

        <asp:Button ID="btnDel" runat="server" OnClick="Button3_Click" Enabled="false" Text="  " />

                &nbsp;&nbsp;

        <asp:Button ID="btnCheck" runat="server" OnClick="btnCheck_Click" Text="  " />

                <br />

                <asp:Label ID="Label1" runat="server"></asp:Label>

            </p>

        </div>

       

    </form>

</body>

</html>

バックグラウンドコード
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;



using CommonLib;



namespace ExcelToSqlserver

{

    public partial class Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {



        }



        /// <summary>

        ///     

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        protected void Button1_Click(object sender, EventArgs e)

        {

            XMLBase xmlBase = new XMLBase();

            xmlBase.LoadDome();

            bool res = xmlBase.CheckNode(txtCname.Text, txtEName.Value);

            if (res)

            {

                xmlBase.InsertNode(txtCname.Text, txtEName.Value, txtIditent.Value);

                //            

                Response.Redirect("IniTableColums.aspx?cName=" + txtCname.Text + "&eName=" + txtEName.Value);

            }

            else

            {

                Label1.Text = "         ";

            }

        }



        protected void Button2_Click(object sender, EventArgs e)

        {

            XMLBase xmlBase = new XMLBase();

            xmlBase.LoadDome();

            bool res = xmlBase.UpdateNode(txtCname.Text, txtEName.Value);

            Label1.Text = res.ToString();

        }



        protected void Button3_Click(object sender, EventArgs e)

        {

            XMLBase xb = new XMLBase();

            xb.LoadDome();

            xb.DeleteNode(txtCname.Text, txtEName.Value, true);

        }



        protected void btnCheck_Click(object sender, EventArgs e)

        {

            //    

            string cName = txtCname.Text.Trim();

            string eName = txtEName.Value.Trim();

            string identrty = txtIditent.Value.Trim();

            if (cName=="")

            {

                 Label1.Text = "  :      !";

                 return;

            }

            if (eName=="")

            {

                 Label1.Text = "  :        !";

                 return;

            }

            if (identrty=="")

            {

                 Label1.Text = "  :      !";

                 return;

            }



            XMLBase xmlBase = new XMLBase();

            xmlBase.LoadDome();

           bool res=xmlBase.CheckNode(txtCname.Text, txtEName.Value);

           if (res)

           {

               Label1.Text = "  :     ";

               btnAdd.Enabled = true;

           }

           else

           {

             



               btnChange.Enabled = true;

               btnDel.Enabled = true;

               Label1.Text = "  :     ,     ";

           }

          

        }

    }

}


テーブルを追加すると、データ列の動的追加ページにジャンプまたはジャンプします.
フロントインタフェース
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="IniTableColums.aspx.cs" Inherits="ExcelToSqlserver.IniTableColums" %>



<!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>       </title>

    <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>

</head>

<body>

    <form id="form1" runat="server"><br />

        <br /><asp:TextBox ID="txtCName" runat="server" ReadOnly="True"></asp:TextBox>

        <input type="hidden" runat="server" id="hiddTableName" />

        <br />

        <br />

        <h3></h3>

        <div class="divCoulm">

            <hr /><input class="txtEName" type="text" onkeyup="this.value=this.value.replace(/[^a-zA-Z]/,'');" />

            &nbsp;<select class="rdType">

                <option value="nvarchar(MAX)" selected="selected">    </option>

                <option value="float">    </option>

                <option value="int">    </option>

            </select>

            <br />

            <br /><input type="text" class="txtBeizhu" />

            &nbsp;<select class="txtLenght">

                <option value="varchar(10)">10</option>

                <option value="varchar(20)">20</option>

                <option value="nvarchar(MAX)">  </option>

            </select>

            <br />

            <br />

            <input type="button" onclick="del(this)" class="delColum" value="  " />

            <br />

            <hr />

        </div>

        <input type="button" value="       " id="btnGo" />

        &nbsp;&nbsp;&nbsp;&nbsp;

        <input type="button" value="  " id="btnOK" />

    </form>

</body>

</html>

<script type="text/javascript">

    $(function () {



        //        

        var addDocument = "   <div class='divCoulm'> <hr />     :<input class='txtEName' onkeyup=\"this.value=this.value.replace(/[^a-zA-Z]/,'');\" type='text' />         ,     <br/>       :<select class='rdType'>";



        addDocument += " <option value='nvarchar(MAX)' selected='selected'>    </option> <option value='float'>    </option>";



        addDocument += " <option value='varchar(9)'>    </option></select><br /> <br />     :<input type='text' class='txtBeizhu' />";



        addDocument += "   &nbsp;       :<select class='txtLenght'> <option value='varchar(10)'>10</option> <option value='varchar(20)'>20</option><option value='nvarchar(MAX)'>  </option></select>    <br /> <br />   <input type=\"button\" class=\"delColum\" onclick=' del(this)' value=\"  \" />  <hr />  </div>";



        $("#btnGo").click(function () {

          var isGo;

            var div = $(this).prev("div");

            var eName = div.children(".txtEName").val();//   

            var eType = div .children(".rdType").val();//    

            var cName = div .children(".txtBeizhu").val();//    

            var cLength = div.children(".txtLenght").val();//    

                isGo = CheckVoide(eName, eType, cName, cLength);

           

            if (!isGo) { alert("    "); } else {

                $(".divCoulm").last().append(addDocument);

            }

        });



        $("#btnOK").click(function () {

            //    

            var mess = "";

            $(".divCoulm").each(function () {

                var eName = $(this).children(".txtEName").val();//   

                var eType = $(this).children(".rdType").val();//    

                var cName = $(this).children(".txtBeizhu").val();//    

                var cLength = $(this).children(".txtLenght").val();//    

                var isGo = CheckVoide(eName, eType, cName, cLength);

                if (isGo) {

                    mess += eName + "_" + eType + "_" + cName + "_" + cLength + "|";

                }

            });

            debugger;

            var go = confirm("           ");

            if (go) {

                var tableName = $("#hiddTableName").val();//    

                var tableCName = $("#txtCName").val();//    ;

                $.post("Ajax/CreatInfoToXML.ashx", { tableName: tableName, tableCName: tableCName, mess: mess }, function () {

                    window.location.href = "EnterExcel.aspx";

                });

            }

        });



        $(".delColum").click(function () {

            debugger;

            $(this).parent("div").html("");

        });



    });

    //        

    function CheckVoide(eName, eType, cName, cLength) {

        if (eName == "" || eType == "" || cName == "" || cLength == "") {

            return false;

        } else if (eName != "" || eType != "" || cName != "" || cLength != "") {

            return true;

        }

    }

    function del(id)

    {

        $(id).parent("div").remove();

    }

</script>

バックグラウンド
        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                txtCName.Text = Request.QueryString["cName"].ToString();

                hiddTableName.Value = Request.QueryString["eName"].ToString();

            }

        }


追加するデータ列は非同期で追加されます
Ajax/CreatInfoToXML.ashx
/**

 *    2014-02-20 

 * excel           XML 

 *                        。

 *InsertXML(HttpContext context)              XML     

 */



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

//

using System.Configuration;

using CommonLib;

using System.Data;

using System.Data.SqlClient;



namespace ExcelToSqlserver.Ajax

{

    /// <summary>

    /// CreatInfoToXML      

    /// </summary>

    public class CreatInfoToXML : IHttpHandler

    {

        XMLBase xmlBase = new XMLBase();



        public void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/plain";

            InsertXML(context);



        }



        //      XML   

        private void InsertXML(HttpContext context)

        {

            //   

            string tableEName = context.Request.Form["tableName"];

            string tableCName = context.Request.Form["tableCName"];

            string mess = context.Request.Form["mess"];

            //    

            if (mess == "") return;

            mess = mess.Substring(0, mess.Length - 1);

            //       

            string[] split1 = mess.Split('|');

            xmlBase.LoadDome();

            string identity = xmlBase.GetIdentity(tableEName, tableCName);

            string sql = "create table " + tableEName + "(" + identity + "  int  identity(1,1) primary key ,";

            for (int i = 0; i < split1.Length; i++)

            {

                string mess2 = split1[i];

                string[] split2 = mess2.Split('_');

                //   

                string eName = split2[0].ToString();

                string eType = split2[1].ToString();

                string cName = split2[2].ToString();

                string eLenght = split2[3].ToString();

                //  sql  

                sql += eName + " " + eType + " ,";

                try

                {

                    xmlBase.LoadDome();

                    xmlBase.InsertNode(tableCName, tableEName, eName, eType, cName, eLenght);

                    //     

               

                }

                catch (Exception ex)

                {



                    throw ex;

                }

            }

            CreatTable(sql);

        }



        private void CreatTable(string tableSql)

        {

            string constr = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;

            SqlConnection con = new SqlConnection(constr);

            if (tableSql != "")

                tableSql = tableSql.Substring(0,tableSql.Length-1);

            string sql = tableSql + ")";

            SqlCommand cmd = new SqlCommand(sql, con);

            con.Open();

            cmd.ExecuteNonQuery();

            con.Close();

        }

      



        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}


  
テーブルの作成が完了すると、データのインポートが可能になります.
データ読み込みインタフェース
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EnterExcel.aspx.cs" Inherits="ExcelToSqlserver.EnterExcel" %>



<!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    </title>

    <style type="text/css">

         li {

        display: inline;

        list-style: none;

         display: inline;

        list-style: none;

        padding-left: 15px;

    }

    </style>

    <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>



</head>

<body>

    <form id="form1" runat="server">

    <div>

             <div>

            <ul>

                <li><a id="a_insert" runat="server">      </a></li>

                <li>      </li>



            </ul>

        </div>

        <br /><asp:DropDownList ID="dropTableInfo" runat="server" Height="16px" Width="140px" AutoPostBack="True" OnSelectedIndexChanged="dropTableInfo_SelectedIndexChanged">

        </asp:DropDownList>

        <input type="hidden" runat="server" id="hiddTableName" />

             <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="      " />

        <br />

        <br />

          EXCEL   :<asp:FileUpload ID="FileUpload1" runat="server" />

        <asp:Label ID="lblMess" runat="server" Text=""></asp:Label>

        <br />

        <br /><asp:DropDownList ID="dropch" runat="server" Height="16px" Width="61px">

            <asp:ListItem>1</asp:ListItem>

            <asp:ListItem Selected="True">2</asp:ListItem>

            <asp:ListItem>3</asp:ListItem>

            <asp:ListItem>4</asp:ListItem>

            <asp:ListItem Value="5"></asp:ListItem>

            <asp:ListItem>6</asp:ListItem>

        </asp:DropDownList>      

        <br />

        <br />

        <asp:Button ID="btnCheck" runat="server" Text="  " OnClick="btnCheck_Click" />

        &nbsp;&nbsp;&nbsp;&nbsp;

        <asp:Button ID="btnOK" runat="server" Text="    " OnClick="btnOK_Click" Enabled="False" />

        &nbsp;&nbsp;&nbsp;&nbsp; 

        <asp:Button ID="btnCon" runat="server" Enabled="false" Text="  " OnClick="btnCon_Click" />

    </div>

         <div id="divShow" runat="server" visible="false">

            <h4></h4>

             <strong>    </strong>

             <br />

          <table cellpadding="1px" border="1px" >

              <tbody id="head" runat="server">

                  <tr>

                      <th style="border:1px solid;" >asdfafd</th>

                       <th style="border:1px solid;" >asdfafd</th>

                  </tr>

              </tbody>

          </table>

        </div>

    </form>

</body>

</html>

 
バックグラウンドコード
/*

 *    2014-02-20

 *excel     

 *       

 *SQlserver       

 *   :EXCEL      

 */

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

///

using CommonLib;

using System.Configuration;

using System.Data;



namespace ExcelToSqlserver

{

    public partial class EnterExcel : System.Web.UI.Page

    {



        XMLBase xmlBase = new XMLBase();



        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                ViewState["excelPath"] = null;

                ViewState["start"] = 0;

                ViewState["end"] = 0;

                xmlBase.LoadDome();

                List<XMLTableInfo> datesource = xmlBase.GetTableList();

                if (datesource.Count > 0)

                {

                    dropTableInfo.DataSource = datesource;

                    dropTableInfo.DataTextField = "CName"; ;

                    dropTableInfo.DataValueField = "EName";

                    dropTableInfo.DataBind();

                    dropTableInfo.SelectedIndex = 0;

                    

                }

                dropTableInfo.Items.Add(new ListItem() { Text="       ", Value="-1" });

                string eName = dropTableInfo.SelectedItem.Value;

                string cName = dropTableInfo.SelectedItem.Text;

                a_insert.Attributes.Add("href", "InsertInfo.aspx?cmd=insert&eName=" + eName + "&cName=" + cName);

            }

        }



        /// <summary>

        ///       

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        protected void btnCheck_Click(object sender, EventArgs e)

        {

            //       

            string upFulPath = ConfigurationManager.ConnectionStrings["ExcelUpLoadPath"].ConnectionString;

            if (!FileUpload1.HasFile)

            {

                Response.Write("<script>alert('       ')</script>");

                return;

            }

            string fileName = FileUpload1.FileName;

            string filetype = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();

            if (filetype == ".xlsx" || filetype == ".xls")

            {

                upFulPath = Server.MapPath(upFulPath);

                string saveName = upFulPath + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + fileName;

                FileUpload1.SaveAs(saveName);

                lblMess.Text = "     ";

                lblMess.Attributes.Add("style", "color:green;");

                ViewState["excelPath"] = saveName;

                btnCon.Enabled=true;

                xmlBase.LoadDome();

                string cName = dropTableInfo.SelectedItem.Text;

                string eName = dropTableInfo.SelectedValue;

                ///    

                string cheInfo = new ExcelHelper().CheckExcelTitle(eName, cName, saveName, "Sheet1");

                if (cheInfo == "")

                {

                    Response.Write("<script>alert('    ')</script>");

                    btnOK.Enabled = true;

                   

                   

                }

                else

                {

                    //Excel          

                    xmlBase.LoadDome();

                    string tab = xmlBase.Check(eName, cName);

                    string[] tblist = tab.Split('¦')[1].Split('[');

                    string st = "<tr>";

                    for (int i = 0; i < tblist.Length; i++)

                    {

                        st += "<td>"+tblist[i]+"</td>";  

                    }

                    st+="</tr>";

                    this.head.InnerHtml = st;

                    divShow.Visible = true;



                    Response.Write("<script>alert('" + cheInfo + "')</script>");

                }

            }

            else

            {

                lblMess.Text = "     excel  !   ";

                return;



            }

            FileUpload1.Enabled = false;

            btnCheck.Enabled = false;



        }



        /// <summary>

        ///     

        /// 2014-02-16

        /// 

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        protected void btnOK_Click(object sender, EventArgs e)

        {



            string path = ViewState["excelPath"].ToString();

            int rowIndex = Convert.ToInt32(dropch.SelectedValue);

            List<string> list = ExcelHelper.GetExcelDate(rowIndex - 1, 0, path, "Sheet1");

            string cName = dropTableInfo.SelectedItem.Text;

            string eName = dropTableInfo.SelectedValue;

            string sql = ExcelHelper.InserToSqlQuerystring(eName, cName);

            int inseCount = 0;

            for (int i = 0; i < list.Count; i++)

            {

                string vals = "";

                for (int j = 0; j < list[i].Split(',').Length; j++)

                {

                    vals += "'" + list[i].Split(',')[j] + "' ,";

                }

                vals = vals.Substring(0, vals.Length - 1);

                string inser = sql + "  (" + vals + " );select @@IDENTITY";

               

                if (i==0)

                {

                    ViewState["start"] = ExcelHelper.ExecSclaer(inser);

                }

                else if(i==list.Count-1)

                {

                    ViewState["end"] = ExcelHelper.ExecSclaer(inser);

                }

                else

                {

                    ExcelHelper.ExecSclaer(inser);

                }

            }

            string mess = "Excel    :" + list.Count + "           :" + inseCount + " ";

            Response.Write("<script>alert('" + mess + "')</script>");

            Response.Redirect("ExcelListShow.aspx?tbname=" + dropTableInfo.SelectedValue + "&start="+ViewState["start"].ToString()+"&end="+ViewState["end"].ToString()+"&cName="+dropTableInfo.SelectedItem.Text+"&eName="+dropTableInfo.SelectedValue);

        }



        //       

        protected void btnCon_Click(object sender, EventArgs e)

        {

            string path = ViewState["excelPath"].ToString();

            bool re = System.IO.File.Exists(path);

            if (re)

            {

                System.IO.File.Delete(path);

                lblMess.Text = "       ";

                lblMess.Attributes.Add("style","color:green;");

                btnOK.Enabled = false;

                ViewState["excelPath"] = "";

                divShow.Visible = false;

                btnCon.Enabled = false;

                btnCheck.Enabled= true;

                FileUpload1.Enabled = true;

            }

        }



        protected void dropTableInfo_SelectedIndexChanged(object sender, EventArgs e)

        {

            string eName = dropTableInfo.SelectedItem.Value;

            string cName = dropTableInfo.SelectedItem.Text;

            lblMess.Text = "";

            if (eName=="-1")

            {

                Response.Redirect("Default.aspx");

            }

            else

            {

                a_insert.Attributes.Add("href", "InsertInfo.aspx?cmd=insert&eName=" + eName + "&cName=" + cName);

            }

           

        }



        protected void btnOutTemp_Click(object sender, EventArgs e)

        {

            string eName = dropTableInfo.SelectedItem.Value;

            string cName = dropTableInfo.SelectedItem.Text;



        }



        protected void Button1_Click(object sender, EventArgs e)

        {

            XMLBase xb = new XMLBase();

            xb.LoadDome();

            xb.DeleteNode("   ", "china", false);

        }

    }

}

 
インポートが完了すると、最新のインポートデータが別のページに表示されます.
 
フロント
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExcelListShow.aspx.cs" Inherits="ExcelToSqlserver.ExcelListShow" %>



<!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>           </title>

   

    <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>

  

</head>

<body>

    <form id="form1" runat="server">

      <div>

          <input type="hidden"  id="hiddcName" runat="server" />

          <input type="hidden" id="hiddeName" runat="server" />

          <input  type

              ="hidden" id="hiddcmd" runat="server" />

          <a id="a_Add" runat="server">    </a>    &nbsp;&nbsp;

        <a id="a_Del" href="#" runat="server">    </a>

         

      </div>

    <div style="text-align:center;">

        <asp:GridView ID="NewGrid" runat="server">

            <Columns>



            </Columns>

        </asp:GridView>

    </div>

    </form>

</body>

</html>

<script type="text/javascript">

    $(function () {

        //         

        $(".heck_box").click(function () {

            var t = $(this).attr("checked");

            if (t) {

                $(".CheckBox").attr("checked", t);

            } else {

                $(".CheckBox").attr("checked", false);

            }

        });

        //       

        $(".A_DelBind").click(function () {

            $(this).parent("td").parent("tr").hide();

        });

        //    

        $("#a_Del").click(function () {



            //    

            var eName = $("#hiddeName").val();

            var cName = $("#hiddcName").val();

            var id = "";

            //    ID

            $(".CheckBox").each(function () {

                var t = $(this).attr("checked");

                if (t) {

                    id += $(this).val() + ",";

                }

            });

            if (id=="") {

                alert("");

                return false; 

            }

            if (id.length>2) {

                id = id.substring(0, id.length - 1);

            }

            var con = confirm("      ,       !");

            if (con) {

                $.get("Ajax/AjaxDateToSql.ashx", { cmd: "delete", id: id, cName: cName, eName: eName }, function () {





                });

            }



        });



    });

</script>

 
バックグラウンドは主にデータバインド
バックグラウンド
/*

 *    

 * 2014-02-26

 *     GridView    

 *      

 * 

 * **/

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

//

using CommonLib;



namespace ExcelToSqlserver

{

    public partial class ExcelListShow : System.Web.UI.Page

    {

        XMLBase xBase = new XMLBase();



        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                string tbname = Request.QueryString["tbname"].ToString();

               ViewState["start"] = Request.QueryString["start"].ToString();

               ViewState["end"] = Request.QueryString["end"].ToString();

                string cName = Request.QueryString["cName"].ToString();

                ViewState["cName"] = cName;

                string eName = Request.QueryString["eName"].ToString();



                //////  

                //string tbname = "RZZGTZ"; //Request.QueryString["tbname"].ToString();

                //string top = "20";// Request.QueryString["top"].ToString();

                //string cName = "      ";// Request.QueryString["cName"].ToString();

                //ViewState["cName"] = cName;

                //string eName = "RZZGTZ";// Request.QueryString["eName"].ToString();



                hiddcName.Value = cName;

                hiddeName.Value = eName;

                ViewState["eName"] = eName;

                xBase.LoadDome();



                ViewState["identity"] = xBase.GetIdentity(eName, cName);

                a_Add.Attributes.Add("href", "InsertInfo.aspx?cName=" + cName + "&eName=" + eName + "&cmd=insert");

                xBase.LoadDome();

                //              

                string tbInfo = xBase.Check(eName, cName);

                ViewState["tableInfo"] = null;

                if (tbInfo != null)

                {

                    ViewState["tableInfo"] = tbInfo;

                }

                //    

                string sql = "select *  from " + eName + "  where  " + xBase.GetIdentity(eName,cName)+"  between "+ ViewState["start"].ToString()+"  and  "+ ViewState["end"].ToString();

                new GridViewTemplate().LoadInfo(this.NewGrid, eName, cName, sql);

            }

        }





    }

}

 
 
フロントのメイン操作は主に非同期操作を使用します
/*2014-02-27

 *    

 * Email:[email protected]

 *           

 *       

 *     

 *     

 *     

 * 

 * **/

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

//

using CommonLib;



namespace ExcelToSqlserver.Ajax

{

    /// <summary>

    /// AjaxDateToSql      

    /// </summary>

    public class AjaxDateToSql : IHttpHandler

    {

        XMLBase xBase = new XMLBase();

        public void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/plain";

            string cmd = context.Request.QueryString["cmd"].ToString();

            switch (cmd)

            {

                case "insert"://    

                    Insert(context);

                    break;

                case "delete"://    

                    Delete(context);

                    break;

                case "editor":

                    Editor(context);

                    break;

                default:

                    break;

            }

        }



        /// <summary>

        ///     

        /// </summary>

        /// <param name="context"></param>

        private void Editor(HttpContext context)

        {

            try

            {

                string cName = context.Request.QueryString["cName"].ToString();

                string eName = context.Request.QueryString["eName"].ToString();

                string id = context.Request.QueryString["id"].ToString();

                string values = context.Request.QueryString["values"].ToString();

                string sql = ExcelHelper.UpdateQueryString(eName, cName, Convert.ToInt32(id));

                string[] val = values.Split('¦');

                string sql2 = string.Format(sql, val);

                int res = ExcelHelper.ExecuteNonQuery(sql2);

                if (res > 0)

                {

                    context.Response.Write("    ");

                }

                else

                {

                    context.Response.Write("NO");

                }

            }

            catch (Exception  ex)

            {

                 context.Response.Write("NO");

               

            }

            

        }



        /// <summary>

        ///     

        /// </summary>

        /// <param name="context"></param>

        private void Delete(HttpContext context)

        {

            //cName=""&eName=&id='

            string cName = context.Request.QueryString["cName"].ToString();

            string eName = context.Request.QueryString["eName"].ToString();

            string id = context.Request.QueryString["id"].ToString();

            //      

            string s = ExcelHelper.DeleteQuerystring(eName, cName, id);

            int resout = ExcelHelper.ExecuteNonQuery(s);

            if (resout > 0)

            {

               context.Response.Redirect("../ShowList.aspx?cName=" + cName + "&eName=" + eName);

            }





        }

        /// <summary>

        ///     

        /// </summary>

        /// <param name="context"></param>

        private void Insert(HttpContext context)

        {

            string sql = context.Request.QueryString["values"].ToString();

            string eName = context.Request.QueryString["eName"].ToString();

            string cName = context.Request.QueryString["cName"].ToString();

            if (sql != "")

            {

                xBase.LoadDome();

                string s = ExcelHelper.InserToSqlQuerystring(eName, cName);

                string[] va = sql.Split('¦');

                string v = "";

                for (int i = 0; i < va.Length; i++)

                {

                    v += va[i] + ",";

                }

                v = v.Substring(0, v.Length - 1);

                s += " (" + v + " );select @@IDENTITY";

                int t = ExcelHelper.ExecSclaer(s);

                if (t > 0)

                {

                    context.Response.Write("    ");

                }

                else

                {

                    context.Response.Write("NO");

                }

            }

            else

            {

                context.Response.Write("NO");

            }



        }



        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

 
バックグラウンドではダイナミックバインドデータを使用しています
データベース内のカラム名をGriviewにバックグラウンドでバインドし、アクションカラムを指定してバインドします.
/*

 * 2014-02-27

 * GridView         

 *                 

 *          

 * 

 * **/

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

//

using System.Web.UI;

using System.Web.UI.WebControls;



namespace CommonLib

{

    /// <summary>

    /// GridView       

    /// </summary>

    public class GridViewTemplate : ITemplate

    {

        public delegate void EventHandler(object sender, EventArgs e);

        public event EventHandler eh;

       

        private DataControlRowType templateType;

        private string columnName;

        private string controlID;

        private XMLTableInfo xmTable = null;

        private BindType bind = BindType.label;

        public GridViewTemplate()

        { }

        /// <summary>

        ///     

        /// </summary>

        /// <param name="type">     </param>

        /// <param name="colname">                 </param>

        /// <param name="colname">        </param>

        public GridViewTemplate(DataControlRowType type, string colname, BindType bin, XMLTableInfo tab)

        {

            templateType = type;

            columnName = colname;

            bind = bin;

            this.xmTable = tab;

        }

        /// <summary>

        ///     

        /// </summary>

        /// <param name="type"></param>

        /// <param name="controlID"></param>

        /// <param name="colname"></param>

        public GridViewTemplate(DataControlRowType type, string controlID, string colname)

        {

            templateType = type;

            this.controlID = controlID;

            columnName = colname;

        }

        public void InstantiateIn(System.Web.UI.Control container)

        {

            switch (templateType)

            {

                case DataControlRowType.Header://    

                    if (bind == BindType.label)

                    {

                        Literal lc = new Literal();

                        lc.Text = columnName;

                        container.Controls.Add(lc);

                    }

                    if (bind == BindType.checkbok)

                    {

                        Literal lc = new Literal();

                        lc.Text = "<input type='checkbox' class='heck_box' />  ";

                        container.Controls.Add(lc);

                    }

                    if (bind == BindType.editor)

                    {

                        Literal lc = new Literal();

                        lc.Text = "  ";

                        container.Controls.Add(lc);

                    }

                    if (bind == BindType.delete)

                    {

                        Literal lc = new Literal();

                        lc.Text = "";// "  ";

                        container.Controls.Add(lc);

                    }



                    break;

                case DataControlRowType.DataRow://     

                    if (bind == BindType.label)

                    {

                        Label tb = new Label();

                        tb.DataBinding += tb_DataBinding;

                        container.Controls.Add(tb);

                    }

                    if (bind == BindType.checkbok)

                    {

                        Literal lic = new Literal();

                        lic.DataBinding += lic_DataBinding;

                        container.Controls.Add(lic);

                    }

                    if (bind == BindType.editor)

                    {

                        Literal lec = new Literal();

                        lec.DataBinding += lec_DataBinding;

                        container.Controls.Add(lec);

                    }

                    if (bind == BindType.editor)

                    {

                        Literal del = new Literal();

                        del.DataBinding += del_DataBinding;

                        container.Controls.Add(del);

                    }



                    break;

                default:

                    break;

            }

        }



        void del_DataBinding(object sender, EventArgs e)

        {



            Literal tb = (Literal)sender;



            GridViewRow row = (GridViewRow)tb.NamingContainer;

            tb.ID = columnName;

            tb.Text = " &nbsp;&nbsp;<a class='A_DelBind' href='Ajax/AjaxDateToSql.ashx?cmd=delete&cName=" + xmTable.CName + "&eName=" + xmTable.EName + "&id=" + DataBinder.Eval(row.DataItem, columnName).ToString() + "'>  </>";

        }



        void lec_DataBinding(object sender, EventArgs e)

        {

            Literal tb = (Literal)sender;



            GridViewRow row = (GridViewRow)tb.NamingContainer;

            tb.ID = columnName;

            tb.Text = "<a href='InsertInfo.aspx?cmd=editor&cName=" + xmTable.CName + "&eName=" + xmTable.EName + "&id=" + DataBinder.Eval(row.DataItem, columnName).ToString() + "'>  </>";

        }



        void lic_DataBinding(object sender, EventArgs e)

        {



            Literal btn = (Literal)sender;



            GridViewRow row = (GridViewRow)btn.NamingContainer;

            btn.ID = columnName;

            btn.Text = "<input type='checkbox' class='CheckBox' value='" + DataBinder.Eval(row.DataItem, columnName).ToString() + "'/>";



        }

        /// <summary>

        /// 2014-02-27

        ///    

        ///          

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        void tb_DataBinding(object sender, EventArgs e)

        {

            Label tb = (Label)sender;



            GridViewRow row = (GridViewRow)tb.NamingContainer;

            tb.ID = columnName;

            tb.Text = DataBinder.Eval(row.DataItem, columnName).ToString();

        }



        #region       



        /// <summary>

        ///      GridView  

        /// </summary>

        /// <param name="NewGrid">GridViews  </param>

        /// <param name="eName">    </param>

        /// <param name="cName">    </param>

        /// <param name="sqlOrTop">          </param>

        public  void LoadInfo(GridView NewGrid, string eName, string cName,string sqlOrTop)

        {

            NewGrid.Columns.Clear();

            XMLTableInfo tb = new XMLTableInfo();

            tb.CName = cName;

            tb.EName = eName;

            XMLBase xBase = new XMLBase();

            xBase.LoadDome();

            string tableInfo = xBase.Check(eName, cName);

            //1,    

            string[] Ename = tableInfo.Split('¦')[0].Split(',');

            string[] Cname = tableInfo.Split('¦')[1].Split('[');

            xBase.LoadDome();

            string id = xBase.GetIdentity(eName, cName);

            //    

            for (int i = 0; i < Ename.Length; i++)

            {

                //BoundColumn cu = new BoundColumn();

                //cu.DataField = Ename[i];

                //cu.HeaderText = Cname[i];

                TemplateField temp = new TemplateField();

                temp.ShowHeader = true;

                if (i == 0)

                {

                    temp.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, Cname[i], BindType.checkbok, tb);

                    temp.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, id, BindType.checkbok, tb);

                }

                else

                {

                    temp.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, Cname[i], BindType.label, tb);

                    temp.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, Ename[i], BindType.label, tb);

                }





                NewGrid.Columns.Add(temp);

            }

            //     

            TemplateField tempEditor = new TemplateField();

            tempEditor.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "  ", BindType.editor, tb);

            tempEditor.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, id, BindType.editor, tb);

            NewGrid.Columns.Add(tempEditor);



            TemplateField tempDelete = new TemplateField();

            tempDelete.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "  ", BindType.delete, tb);

            tempDelete.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, id, BindType.delete, tb);

            NewGrid.Columns.Add(tempDelete);



            string sql = "";

            if (sqlOrTop.Length<11)

            {

                sql = "select top " + sqlOrTop + " * from " + eName + "  order by  " + id + " DESC";

                NewGrid.DataSource = ExcelHelper.GetDataSet(sql);

            }

            else

            {

                NewGrid.DataSource = ExcelHelper.GetDataSet(sqlOrTop);

            }

           

            NewGrid.AutoGenerateColumns = false;

            NewGrid.DataBind();





        }

        #endregion





    }



    public enum BindType

    {

        label, checkbok, editor, delete

    }





}

 
以上のコードは、異なるタイプのデータバインドヘッダ列データ表示列操作列などを提供しています.BindTypeが提供する列挙に対応するバインドカラムタイプ
    public enum BindType

    {

        label, checkbok, editor, delete

    }

 
以上で使用したいくつかの約束
特殊クラス名
クラス名
さぎょう
出現位置
heck_box
すべて選択を制御
dateGridViewヘッダの位置でテーブル全体を制御するチェックボックスが表示されます.
CheckBox
データ・プライマリ・キー値のバインド
GridViewデータ列の位置がヘッダーの位置に表示され、データが選択されているかどうかを判断します.
以上は2つの比較的特殊なラベルクラス名です.
 
特殊なページと特殊なパラメータ:
ページのパス
パラメータ
さぎょう
InsertInfo.aspx
cmd:操作指令[insert,delede,editor]それぞれ対応追加,削除,編集機能eName:データテーブル対応の英語名cName:対応する中国語名id:対応するデータプライマリキー番号
追加ページと編集ページは同じページで、追加データ入力インタフェースを提供します.ロードデータ編集インタフェースを提供します. 
Ajax/AjaxDateToSql.ashx
パラメータを渡す必要があります
非同期ハンドラを提供します.手動で削除する方法を提供します.
参照先:
href='Ajax/AjaxDateToSql.ashx?cmd=delete&cName=CName&eName=EName&id=id'   InsertInfo.aspx?cmd=editor&cName=CName &eName=EName&id=id'
セクション
cNameとeNameの2つのパラメータは、プログラム全体を貫き、中国語の表民とデータベース内のテーブル名が一致することを保証するために二重検証を採用しています.
 
 
ここまで来るとコアコードがほとんど展示されていません
最後のステップでまとめます
データの表示
フロント
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowList.aspx.cs" Inherits="ExcelToSqlserver.ShowList" %>



<!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>      </title>

    <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <p><label id="lblTitle" runat="server">XXX  </label></p><input type="text" id="txtKey" runat="server" /><asp:Button ID="btnSech" runat="server" Text="  " OnClick="btnSech_Click" />

            <br />

            <br />

            <div>

          <input type="hidden"  id="hiddcName" runat="server" />

          <input type="hidden" id="hiddeName" runat="server" />

          <input  type

              ="hidden" id="hiddcmd" runat="server" />

          <a id="a_Add" runat="server">    </a>    &nbsp;&nbsp;

        <a id="a_Del" href="#" runat="server">    </a>

                <br />

         

      </div>

        </div>

        <div>

            <asp:GridView ID="gridView" runat="server">

                <Columns></Columns>

            </asp:GridView>

        </div>

                <div style="width: 600px; margin-top: 10px; text-align: center;">

                        <asp:Button ID="shouye" runat="server" Text="  " OnClick="shouye_Click" />

                        <asp:Button ID="btnUpPage" runat="server" Text="   " OnClick="btnUpPage_Click" />

                        <asp:Button ID="btnNextPage" runat="server" Text="   " OnClick="btnNextPage_Click" />

                        <asp:Button ID="weiye" runat="server" Text="  " OnClick="weiye_Click" />

                         <asp:Label ID="lbl_courrentPage" runat="server" Text="1"></asp:Label>

                         &nbsp;  

                <input id="currentpage" type="text" runat="server" style="width: 32px; height: 15px;" /> 

                <asp:Button ID="tiaozhuan" runat="server" Text="  " OnClick="tiaozhuan_Click" />

                        &nbsp;  <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" Height="22px"

                            Width="39px" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">

                            <asp:ListItem Value="10">10</asp:ListItem>

                            <asp:ListItem>20</asp:ListItem>

                            <asp:ListItem>30</asp:ListItem>

                        </asp:DropDownList>

                         

                    </div>

    </form>

</body>

</html>

<script type="text/javascript">

    $(function () {

        //         

        $(".heck_box").click(function () {

            var t = $(this).attr("checked");

            if (t) {

                $(".CheckBox").attr("checked", t);

            } else {

                $(".CheckBox").attr("checked", false);

            }

        });

        //       

        $(".A_DelBind").click(function () {

            $(this).parent("td").parent("tr").hide();

        });

        //    

        $("#a_Del").click(function () {



            //    

            var eName = $("#hiddeName").val();

            var cName = $("#hiddcName").val();

            var id = "";

            //    ID

            $(".CheckBox").each(function () {

                var t = $(this).attr("checked");

                if (t) {

                    id += $(this).val() + ",";

                }

            });

            if (id == "") {

                alert("");

                return false;

            }

            if (id.length > 2) {

                id = id.substring(0, id.length - 1);

            }

            var con = confirm("      ,       !");

            if (con) {

                $.get("Ajax/AjaxDateToSql.ashx", { cmd: "delete", id: id, cName: cName, eName: eName }, function () {

                    history.go(0);





                });

            }



        });



    });

</script>

 
 
バックグラウンド
/*2014-3-3

 * email:[email protected]

 *       

 *       

 *     

 * 

 * **/



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

//

using CommonLib;



namespace ExcelToSqlserver

{

    public partial class ShowList : System.Web.UI.Page

    {

        XMLBase xb = new XMLBase();

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                shouye.Enabled = false;

                btnUpPage.Enabled = false;

                btnNextPage.Enabled = false;

                weiye.Enabled = false;

                ViewState["pageIndex"] = 1;

                ViewState["pageSize"] = 10;

                ViewState["pageCount"] = 0;

                ViewState["where"] = "";

                ViewState["cName"] =Request.QueryString["cName"].ToString();

                ViewState["eName"] =Request.QueryString["eName"].ToString();

                a_Add.Attributes.Add("href", "InsertInfo.aspx?cName=" + ViewState["cName"].ToString() + "&eName=" + ViewState["eName"].ToString() + "&cmd=insert");

                hiddcmd.Value = ViewState["cName"].ToString();

                hiddeName.Value = ViewState["eName"].ToString();

                lblTitle.InnerHtml = ViewState["cName"].ToString();

                selctInfo();

            }





        }

        /// <summary>

        ///    

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        protected void btnSech_Click(object sender, EventArgs e)

        {

            xb.LoadDome();



            string[] keowo = xb.Check(ViewState["eName"].ToString(), ViewState["cName"].ToString()).Split('¦')[0].Split(',');

            string sql ="";

            string key = txtKey.Value;

            if (key != "")

            {

                for (int i = 0; i < keowo.Length; i++)

                {

                    if (i==keowo.Length-1)

                    {

                        sql += "  " + keowo[i] + "  like  '%" + key + "%'";

                    }

                    else

                    {

                        sql += "  " + keowo[i] + "  like  '%" + key + "%'" + " or";

                    }

                    

                }

                sql = sql.Trim().Substring(0, sql.Length - 2);

                ViewState["where"] = sql;

            }

            else

            {

                ViewState["where"] = "";

            }

            selctInfo();

        }

        private void ControlManager(int index, int count)

        {



            if (index == 1 && count == 1) return; ;//

            if (index >= 1 && index < count)//       

            {



                shouye.Enabled = false;

                btnUpPage.Enabled = false;

                btnNextPage.Enabled = true;

                weiye.Enabled = true;

                tiaozhuan.Enabled = true;

            }

            if (index >= 2 && index < count)//        

            {



                shouye.Enabled = true;

                btnUpPage.Enabled = true;

                btnNextPage.Enabled = true;

                weiye.Enabled = true;

                tiaozhuan.Enabled = true;

            }

            if (index >= 2 && index == count)

            {

                shouye.Enabled = true;

                btnUpPage.Enabled = true;

                btnNextPage.Enabled = false;

                weiye.Enabled = false;

            }







        }



        #region     

        //  

        protected void shouye_Click(object sender, EventArgs e)

        {

            ViewState["pageIndex"] = 1;



            selctInfo();



            this.btnUpPage.Enabled = false;

            btnNextPage.Enabled = true;



        }

        //  

        protected void weiye_Click(object sender, EventArgs e)

        {

            ViewState["pageIndex"] = ViewState["pageCount"];



            selctInfo();



            this.btnUpPage.Enabled = true;

            btnNextPage.Enabled = false;

        }

        //  

        protected void tiaozhuan_Click(object sender, EventArgs e)

        {

            int page = Convert.ToInt32(currentpage.Value);

            int pageCount = Convert.ToInt32(ViewState["pageCount"]);

            if (page > pageCount)

            {

                currentpage.Value = pageCount.ToString();

                ViewState["pageIndex"] = pageCount;

                selctInfo();



            }

            else

            {



                ViewState["pageIndex"] = page;

                selctInfo();

            }

        }

        //     

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

        {

            ViewState["pageSize"] = DropDownList1.SelectedValue;

            ViewState["pageIndex"] = 1;

            selctInfo();

        }

        //  

        protected void btnUpPage_Click(object sender, EventArgs e)

        {

            int pageindex = Convert.ToInt32(ViewState["pageIndex"]);

            ViewState["pageIndex"] = pageindex - 1;

            if ((pageindex - 1) <= 1)

            {

                ViewState["pageIndex"] = 1;

                this.btnUpPage.Enabled = false;





                selctInfo();

            }

            else

            {

                selctInfo();

            }

            btnNextPage.Enabled = true;





        }

        //  

        protected void btnNextPage_Click(object sender, EventArgs e)

        {



            int pageIndex = Convert.ToInt32(ViewState["pageIndex"]) + 1;

            if (pageIndex == Convert.ToInt32(ViewState["pageCount"]) || pageIndex > Convert.ToInt32(ViewState["pageCount"]))

            {



                ViewState["pageIndex"] = ViewState["pageCount"];

                btnNextPage.Enabled = false;



                selctInfo();

            }

            else

            {

                ViewState["pageIndex"] = pageIndex;

                selctInfo();

            }

            this.btnUpPage.Enabled = true;



        }



        #endregion



        /// <summary>

        ///     

        /// </summary>

        private void selctInfo()

        {

            //ViewState["cName"]

            //ViewState["eName"]

            //      ViewState["where"]

            //          Sql

            string sql = ExcelHelper.GetCountQueryString(ViewState["eName"].ToString(), ViewState["where"].ToString());

            //        

            xb.LoadDome();

            string identity = xb.GetIdentity(ViewState["eName"].ToString(), ViewState["cName"].ToString());

            string sqlPage = ExcelHelper.GetPageQueryStrong(ViewState["eName"].ToString(), ViewState["cName"].ToString(), ViewState["where"].ToString(), identity, Convert.ToInt32(ViewState["pageIndex"]), Convert.ToInt32(ViewState["pageSize"]));

            int recordCount = ExcelHelper.ExecSclaer(sql);

            new GridViewTemplate().LoadInfo(this.gridView, ViewState["eName"].ToString(), ViewState["cName"].ToString(), sqlPage);

            int pageIndex = Convert.ToInt32(ViewState["pageIndex"]);

            int pageSize = Convert.ToInt32(ViewState["pageSize"]);

            ViewState["pageCount"] = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;

            lbl_courrentPage.Text = ViewState["pageCount"].ToString();

            currentpage.Value = pageIndex.ToString();



            ControlManager(pageIndex, Convert.ToInt32(ViewState["pageCount"]));

        }



    }

}

例ではXMLの読み書き検索,データ分割,などの操作,クエリ文の動的形成,文検索文の追加などの一般的な操作文を用いた.
 
最後のページの編集と追加
フロント
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="InsertInfo.aspx.cs" Inherits="ExcelToSqlserver.InsertInfo" %>



<!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>      </title>

    <style type="text/css">

         li {

        display: inline;

        list-style: none;

         display: inline;

        list-style: none;

        padding-left: 15px;

    }

        

    </style>

    <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>

   

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <ul>

                <li>      </li>

                <li>

                    <asp:Button ID="btnEnterExcel" runat="server" Text="      " OnClick="btnEnterExcel_Click" /></li>



            </ul>

        </div>

        <br />

        <input type="hidden" runat="server" id="hiddEname" />

        <input type="hidden" runat="server" id="hiddCname" />

         <input type="hidden" runat="server" id="hiddCmd" />

        <input type="hidden" runat="server" id="hiddRecordId" />



        <div>

            <table>

                <tbody id="tbody" runat="server">

                </tbody>

                <tfoot>

                    <tr>

                        <td>

                            <input type="reset" id="reset" value="  " /></td>

                        <td style="margin-left: 30px;">

                            <input type="button" runat="server" id="btnOK" value="  " />&nbsp;</td>

                    </tr>

                </tfoot>

            </table>

        </div>

    </form>

</body>

</html>

<script type="text/javascript">



    var Values = "";

    //          

    function checkInput() {

        $(".txtVal").each(function () {

            var val = $(this).val();

            if (val == "") {

                $(this).parent("td").next(".mess").css("color", "red").html("         ");

                return false;

            } else {

                $(this).parent("td").next(".mess").css("color", "green").html("     ");

                Values += "'" + $(this).val() + "',";

                return true;

            }

        });

    }



    $(function () {

        checkInput();

        $(".txtVal").blur(function () {

            var va = $(this).val();

            if (va == "") {

                $(this).parent("td").next(".mess").css("color", "red").html("      ");



                return false;

            } else {

                $(this).parent("td").next(".mess").css("color", "green").html("     ");

            }

        });

        $("#reset").click(function () {

            $(".mess").html("");

        });



        $("#btnOK").click(function () {



            //       

            var i = 1 * 1;

            var values = "";

            var res =true;

            $(".mess").each(function () {

                var t = $(this).html().trim();

                if (t != "     ") {

                    var ask = confirm(" " + i + "       ");

                    res = false;

                    return;

                  

                }

                i++;

            });



            //    

            $(".txtVal").each(function () {

                values += "'" + $(this).val() + "' ¦";//             

            });



            //    

            if (values != "") {

                values = values.substring(0, values.length - 1);

            }

            //    

            //   

            var eName = $("#hiddEname").val();

            var cName = $("#hiddCname").val();

            var cmd = $("#hiddCmd").val();

            var id = $("#hiddRecordId").val();

            if (!res) 

                return;

            $.get("Ajax/AjaxDateToSql.ashx", { eName: eName, cName: cName, values: values,id:id,cmd: cmd }, function (date) {

                if (date != "NO") {

                    alert(date);

                    $("#reset").click();

                } else {

                    alert("");

                }

            });



        });

    });

</script>

 
バックグラウンド
/*2014-02-27

 *               。

 *         

 * **/

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

//

using CommonLib;



namespace ExcelToSqlserver

{

    public partial class InsertInfo : System.Web.UI.Page

    {

        XMLBase xBase = new XMLBase();

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                string eName = Request.QueryString["eName"].ToString();

                string cName = Request.QueryString["cName"].ToString();

                string cmd = Request.QueryString["cmd"].ToString();

                hiddCmd.Value = cmd;

                hiddEname.Value = eName;

                hiddCname.Value = cName;

                if (Request.QueryString["id"]!=null)

                {

                    hiddRecordId.Value = Request.QueryString["id"].ToString();

                    //    

                    LoadDocument(eName, cName, hiddRecordId.Value);

                }

                else

                {

                    LoadDocument(eName, cName, "");

                }

               

            }

        }

        /// <summary>

        ///         n 

        /// </summary>

        /// <param name="eName"></param>

        /// <param name="cName"></param>

        private void LoadDocument(string eName, string cName, string id)

        {

            xBase.LoadDome();

            string che = xBase.Check(eName, cName);

            string[] colums = che.Split('¦')[0].Split(',');

            string[] showInfo = che.Split('¦')[1].Split('[');



            //   

            if (id == "")

            {

                for (int i = 0; i < showInfo.Length; i++)

                {

                    string tr = "<tr> <td style='text-align:right;'>" + showInfo[i] + ":</td> <td><input class='txtVal' type='text' /></td> <td class='mess'></td><td><input class='colu' type='hidden' value='" + colums[i] + "' /></td> </tr>";

                   

                    tbody.InnerHtml += tr;



                }

            }

            else if (id != "")

            {

                //     

                string values = GetModel(eName, cName, id);

                string[] info = values.Split('¦');

                btnOK.Value = "    ";

                for (int i = 0; i < showInfo.Length; i++)

                {

                    string tr = "<tr> <td style='text-align:right;'>" + showInfo[i] + ":</td> <td><input class='txtVal' type='text'  value='" + info[i + 1] + "'/></td> <td class='mess'></td><td><input class='colu' type='hidden' value='" + colums[i] + "' /></td> </tr>";

                    tbody.InnerHtml += tr;



                }

            }





        }





        private string GetModel(string eName, string cName, string id)

        {

            string value = "";

            //      

            string sql = ExcelHelper.GetModelQueryString(eName, cName, Convert.ToInt32(id));

            value = ExcelHelper.SelectToSqlModel(sql);

            return value;

        }



        protected void btnEnterExcel_Click(object sender, EventArgs e)

        {

           string eName= hiddEname.Value;

           string cName = hiddCname.Value; ;

           string url = "EnterExcel.aspx?eName=" + eName + "&cName=" + cName ;

            Response.Redirect(url);

        }



    }

}