懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法

懒人小工具:T4自动生成Model,Insert,Select,Delete以及导出Excel的方法
在开发的过程中,我们为了节约时间,往往会将大量重复机械的代码封装,考虑代码的复用性,这样我们可以节约很多时间来做别的事情。最近跳槽到一节webform开发的公司,主要是开发自己公司用的ERP。开始因为一些诱惑进来的,现在感觉其实有些后悔放弃了很好的学习ABP以及新知识点像一些很新颖的前端框架进这个公司。但现在跳槽也不是一个明智之举,不好意思扯远了,既来之则安之。最近写了个小工具。主要针对webform开发过程中一些重复的代码处理。
其实没有什么特别大的技术难度,其实webform开发貌似也没有特别大的技术难度。
首先新建一个类库WorkHelper。
然后新建类Program.cs,这里是作为主程序入口。

using System;
using System.Windows.Forms;

namespace DevLogHelper
{
    static class Program
    {
        /// 
        /// 应用程序的主入口点。
        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new BaseSqlBuilder());
        }

    }
}

为Main()方法加上STAThread标签。每次只能启动一个窗口。
new 一个BaseSqlBuilder实例,BaseSqlBuilder实例是什么呢,就是我们今天的主题了。

懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法_第1张图片
1.png

其实界面特别简单的。就是几个label、多选框、容器。
看下代码:

using System;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using DevLogHelper.Resources;

namespace DevLogHelper
{
    public partial class BaseSqlBuilder : Form
    {
        readonly ResourceManager _rm = new ResourceManager(typeof(ResourceDevCode));
        public BaseSqlBuilder()
        {
            InitializeComponent();
        }

        private void BaseSqlBuilder_Load(object sender, EventArgs e)
        {

        }
        /// 
        /// 生成
        /// 
        /// 
        /// 
        private void btnCreate_Click(object sender, EventArgs e)
        {
            string msg = _rm.GetString("BaseSqlTip");
            try
            {
                BaseSql.BaseSql sq = new BaseSql.BaseSql();
                StringBuilder str = sq.BuilderCode(txtInput.Text, cbIsModel, txt_TableName.Text, ckb_Model.Checked, ckb_Insert.Checked,ckb_Update.Checked,ckb_Select.Checked,ckb_Delete.Checked,ckbExcel.Checked);
                txtResult.Text = str.ToString();
                Clipboard.SetDataObject(str.ToString());
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            labTip.Text = msg;
        }

    }
}

窗体BaseSqlBuilder继承自Form不必多说。ResourceManager是什么呢,ResourceManager就是一个资源文件,用于处理消息,或者路径什么。后面补上图。
新建一个BaseSql用于处理sql。把页面上的控件消息传递过去。封装一个数据的形式。

资源文件以及解决方案结构。


懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法_第2张图片
4R9QU1Y7XFDV43BKKBVDUK3.png

跟踪BuilderCode到BaseSql类。


懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法_第3张图片
87C8U$IKXP(%OJ{M~HT2YPA.png

首先是对控件传递过来值得检查,参数是否为空等。

            string Table = inputSql[2].ToString();
            if (string.IsNullOrWhiteSpace(inputCode))
            {
                inputCode = "select *from " + Table;
            }
            StringBuilder returnstr = new StringBuilder();
            StringBuilder strBuilder = new StringBuilder();
            DataSet ds = SqlHelper.Query(inputCode);
            DataRow dr = null;
            DataTable dt = new DataTable();

这里如果传递过来的sql语句为空,我们会根据表名自动生成查询SQL。然后根据ado.net 链接数据库生成DataSet 、DataRow 、DataTable 等。当然这里得有SqlHelper。SqlHelper如果需要可以去我源码上下载,稍后会放上源码。主要是链接数据库。执行SQL了。

     #region 封装实体Model

   #region 封装实体Model

            strBuilder.AppendLine(@"
               public class Model
            {
               ");
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                if (i == 0)
                {
                    Id = dr.Table.Columns[0].ToString();//一般情况第一个字段是主键,当然如果第一个字段不是主键,那就需要修改了
                }
                string Type = dr.Table.Columns[i].DataType.ToString();
                switch (Type)
                {
                    case "System.String":
                        strBuilder.AppendLine("       private string " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public string " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("         {");
                        strBuilder.AppendLine("            get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("            set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("          }");
                        break;
                    case "System.Int":
                        strBuilder.AppendLine("       private Int " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public Int " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("         {");
                        strBuilder.AppendLine("            get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("             set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("         }");
                        break;
                    case "System.Int32":
                        strBuilder.AppendLine("       private Int " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public Int " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("         {");
                        strBuilder.AppendLine("            get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("             set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("         }");
                        break;
                    case "System.DateTime":
                        strBuilder.AppendLine("       private System.DateTime " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public System.DateTime " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("          {");
                        strBuilder.AppendLine("             get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("             set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("          }");
                        break;
                    case "System.Decimal":
                        strBuilder.AppendLine("       private System.Decimal " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public System.Decimal " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("        {");
                        strBuilder.AppendLine("            get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("            set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("         }");
                        break;
                    default:
                        strBuilder.AppendLine("       private string " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public string " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("        {");
                        strBuilder.AppendLine("             get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("             set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("         }");
                        break;
                }
            }
            strBuilder.AppendLine(@"
              }
               ");

            #endregion

首先我们是生成Model。有了Model才有下面的增删改查的方法。
其实也很简单,dr.Table.Columns[i].DataType.ToString(),我们就是根据DataRow循环table列,判断字段类型,然后根据对应的字段类型封装成model.单选框默认勾选的,这里先去掉勾选,输入表名,点击生成,然后和数据库表对应,看一下效果。

懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法_第4张图片
2.png

Model 是最实用的,就算以后我们在用mvc或者ABP等其他框架底层用codefirst等orm框架的时候,我们也可以用这种方式生成Model.

    public bool InsertAgreement_YNSHigh_Authorize(Model model)
        {

            string strSql = @"
               INSERT Agreement_YNSHigh_Authorize(
                 AYA_Code,
                 AYHA_Code,
                 Ctg_ID,
                 HospitalCode,
                 HospitalName,
                 HospitalGrad,
                 HospitalRegionID,
                 DevelopmentLimitTime,
                 EffectiveTime,
                 MarketingManagementFee,
                 BidPrice,
                 DeliveryCode,
                 DeliveryName,
                 AgreeAdjuestType,
                 ChangeContent,
                 Status,
                 DeliveryPrice,
                 BasePrice,
                 CategoryCommodityName,
                 CategorySystemName,
                 CategoryCommName,
                 CategorySpec,
                 Formulation,
                 BusinessModel)
                 VALUES (
                    @AYA_Code,
                    @AYHA_Code,
                    @Ctg_ID,
                    @HospitalCode,
                    @HospitalName,
                    @HospitalGrad,
                    @HospitalRegionID,
                    @DevelopmentLimitTime,
                    @EffectiveTime,
                    @MarketingManagementFee,
                    @BidPrice,
                    @DeliveryCode,
                    @DeliveryName,
                    @AgreeAdjuestType,
                    @ChangeContent,
                    @Status,
                    @DeliveryPrice,
                    @BasePrice,
                    @CategoryCommodityName,
                    @CategorySystemName,
                    @CategoryCommName,
                    @CategorySpec,
                    @Formulation,
                   @BusinessModel)

                     ";
            SqlParameter[] parameters = new SqlParameter[]
                                                  {
                      new SqlParameter("@AYA_Code", SqlDbType.NVarChar, 255),
                     new SqlParameter("@AYHA_Code", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Ctg_ID", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalCode", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalGrad", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalRegionID", SqlDbType.NVarChar, 255),
                     new SqlParameter("@DevelopmentLimitTime", SqlDbType.DateTime),
                     new SqlParameter("@EffectiveTime", SqlDbType.DateTime),
                      new SqlParameter("@MarketingManagementFee", SqlDbType.Decimal),
                      new SqlParameter("@BidPrice", SqlDbType.Decimal),
                     new SqlParameter("@DeliveryCode", SqlDbType.NVarChar, 255),
                     new SqlParameter("@DeliveryName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@AgreeAdjuestType", SqlDbType.NVarChar, 255),
                     new SqlParameter("@ChangeContent", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Status", SqlDbType.NVarChar, 255),
                      new SqlParameter("@DeliveryPrice", SqlDbType.Decimal),
                      new SqlParameter("@BasePrice", SqlDbType.Decimal),
                     new SqlParameter("@CategoryCommodityName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategorySystemName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategoryCommName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategorySpec", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Formulation", SqlDbType.NVarChar, 255),
                     new SqlParameter("@BusinessModel", SqlDbType.NVarChar, 255),
                            };
            parameters[0].Value = model.AYA_Code;
            parameters[1].Value = model.AYHA_Code;
            parameters[2].Value = model.Ctg_ID;
            parameters[3].Value = model.HospitalCode;
            parameters[4].Value = model.HospitalName;
            parameters[5].Value = model.HospitalGrad;
            parameters[6].Value = model.HospitalRegionID;
            parameters[7].Value = model.DevelopmentLimitTime;
            parameters[8].Value = model.EffectiveTime;
            parameters[9].Value = model.MarketingManagementFee;
            parameters[10].Value = model.BidPrice;
            parameters[11].Value = model.DeliveryCode;
            parameters[12].Value = model.DeliveryName;
            parameters[13].Value = model.AgreeAdjuestType;
            parameters[14].Value = model.ChangeContent;
            parameters[15].Value = model.Status;
            parameters[16].Value = model.DeliveryPrice;
            parameters[17].Value = model.BasePrice;
            parameters[18].Value = model.CategoryCommodityName;
            parameters[19].Value = model.CategorySystemName;
            parameters[20].Value = model.CategoryCommName;
            parameters[21].Value = model.CategorySpec;
            parameters[22].Value = model.Formulation;
            parameters[23].Value = model.BusinessModel;

            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters);
                        if (i > 0)
                        {
                            trans.Commit();
                            return i > 0;
                        }
                        else
                        {
                            trans.Rollback();
                            return false;
                        }
                    }
                    catch (System.Exception e)
                    {
                        return false;
                        trans.Rollback();
                        throw e;
                    }
                }
            }

        }

平时我们在新增数据的时候,就以Agreement_YNSHigh_Authorize为例,一般都是这样超做的,加上事务,参数化传过来的参数,这样写起来也非常麻烦。我们这里了也对INSERT 做一下封装。

    #region 生成插入Insert方法

            #region 生成插入sql语句

            StringBuilder strTmp = new StringBuilder();
            try
            {
                for (int i = 0; i < dr.Table.Columns.Count; i++)//生成insert 
                {
                    if (i == 0)
                    {
                        strTmp.AppendLine("               INSERT " + Table + "(");
                    }
                    if (i == dr.Table.Columns.Count - 1)
                    {
                        strTmp.AppendLine("                 " + dr.Table.Columns[i].ToString() + ")");
                    }
                    else
                    {
                        strTmp.AppendLine("                 " + dr.Table.Columns[i].ToString() + ",");
                    }
                }

                for (int i = 0; i < dr.Table.Columns.Count; i++)
                {
                    if (i == 0)
                    {
                        strTmp.AppendLine("                 VALUES " + "(");
                    }
                    if (i == dr.Table.Columns.Count - 1)
                    {
                        strTmp.AppendLine("                   @" + dr.Table.Columns[i].ToString() + ")");
                    }
                    else
                    {
                        strTmp.AppendLine("                    @" + dr.Table.Columns[i].ToString() + ",");
                    }

                }
            }
            catch (System.Exception ex)
            {

                throw ex;
            }

            #endregion





            strBuilder.AppendLine("   public bool Insert" + Table + "(Model model)");
            strBuilder.AppendLine(@"    {   
           ");
            strBuilder.AppendLine("                    string strSql = @\"");
            strBuilder.AppendLine(strTmp.ToString());
            strBuilder.AppendLine("                     \";");

            strBuilder.AppendLine(@"                 SqlParameter[] parameters = new SqlParameter[]
                                                  {");
            //参数类型
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                string Type = dr.Table.Columns[i].DataType.ToString();
                switch (Type)
                {
                    case "System.String":
                        strBuilder.AppendLine("                     new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.NVarChar, 255),");
                        break;
                    case "System.Int":
                        strBuilder.AppendLine("                     new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Int),");
                        break;
                    case "System.Int32":
                        strBuilder.AppendLine("                     new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Int),");
                        break;
                    case "System.DateTime":
                        strBuilder.AppendLine("                     new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.DateTime),");
                        break;
                    case "System.Decimal":
                        strBuilder.AppendLine("                      new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Decimal),");
                        break;
                    default:
                        strBuilder.AppendLine("                      new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.NVarChar, 255),");
                        break;
                }
            }
            strBuilder.AppendLine(@"                            };");

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                strBuilder.AppendLine("                        parameters[" + i + "].Value =" + "model." + dr.Table.Columns[i] + ";");
            }

            strBuilder.AppendLine(@"
            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters);
                          if (i > 0)
                        {
                            trans.Commit();
                            return i > 0;
                        }
                        else
                        {
                            trans.Rollback();
                            return false;
                        }
                    }
                    catch (System.Exception e)
                    {
                         return false;
                        trans.Rollback();
                        throw e;
                    }
                  }
               }
               ");
            strBuilder.AppendLine("}");

            #endregion

首先是根据sql生成字段和参数字段。这都是很繁琐的工作,而且不能出错。也是对DataRow table的循环和封装处理。需要注意一下转义字符处理,注意对事务的处理。另外update,select,delete的处理方式与insert类似,不在累述,放上代码。

            if ((bool)inputSql[4])
            {
                returnstr.AppendLine(strBuilder.ToString());
            }
            strBuilder = new StringBuilder();
            #region 生成更新Update 方法

            #region 生成更新Update sql语句

            strTmp = new StringBuilder(); //sql 
            try
            {
                for (int i = 0; i < dr.Table.Columns.Count; i++)//生成Update 
                {
                    if (i == 0)
                    {
                        strTmp.AppendLine("               Update " + Table + "  SET ");
                    }
                    if (i == dr.Table.Columns.Count - 1)
                    {


                        strTmp.AppendLine("                 " + dr.Table.Columns[i].ToString() + "=" + "@" + dr.Table.Columns[i].ToString() + " where " + Id + "=" + "@" + Id + "  ");
                    }
                    else
                    {
                        strTmp.AppendLine("                  " + dr.Table.Columns[i].ToString() + "=" + "@" + dr.Table.Columns[i].ToString() + ",");
                    }
                }
            }
            catch (System.Exception ex)
            {

                throw ex;
            }

            #endregion




            strBuilder.AppendLine("   public bool Update" + Table + "ById(Model model)");
            strBuilder.AppendLine(@"    {   
           ");
            strBuilder.AppendLine("                    string strSql = @\"");
            strBuilder.AppendLine(strTmp.ToString());
            strBuilder.AppendLine("                     \";");

            strBuilder.AppendLine(@"                 SqlParameter[] parameters = new SqlParameter[]
                                                  {");
            //参数类型
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                string Type = dr.Table.Columns[i].DataType.ToString();
                switch (Type)
                {
                    case "System.String":
                        strBuilder.AppendLine("                     new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.NVarChar, 255),");
                        break;
                    case "System.Int":
                        strBuilder.AppendLine("                     new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Int),");
                        break;
                    case "System.DateTime":
                        strBuilder.AppendLine("                     new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.DateTime),");
                        break;
                    case "System.Decimal":
                        strBuilder.AppendLine("                      new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Decimal),");
                        break;
                    default:
                        strBuilder.AppendLine("                      new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.NVarChar, 255),");
                        break;
                }
            }
            strBuilder.AppendLine(@"                            };");

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                strBuilder.AppendLine("                        parameters[" + i + "].Value =" + "model." + dr.Table.Columns[i] + ";");
            }

            strBuilder.AppendLine(@"
            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters);
                          if (i > 0)
                        {
                            trans.Commit();
                            return i > 0;
                        }
                        else
                        {
                            trans.Rollback();
                            return false;
                        }
                    }
                    catch (System.Exception e)
                    {
                        return false;
                        trans.Rollback();
                        throw e;
                    }
                  }
               }
               ");
            strBuilder.AppendLine("}");

            #endregion

            if ((bool)inputSql[5])
            {
                returnstr.AppendLine(strBuilder.ToString());
            }
            strBuilder = new StringBuilder();
            #region 生成查询方法

            strBuilder.AppendLine("   public DataTable GetDataBy" + Table + "(Model model , int pageNo, int pageSize, ref int iRecordCount)");
            strBuilder.AppendLine(@"    {    ");
            strTmp = new StringBuilder();
            strTmp.AppendLine("WITH temp AS ( SELECT rn =  ROW_NUMBER() OVER (ORDER BY " + Id + "  desc), *FROM  " + Table + " WHERE 1=1 {0} )");
            strTmp.AppendLine("SELECT *,rc=(select count(1) from temp) FROM temp WHERE rn BETWEEN {1} AND {2}");

            strBuilder.AppendLine("        List parameters = new List();");
            strBuilder.AppendLine("        StringBuilder sqlWhere = new StringBuilder();");
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                strBuilder.AppendLine("       if (!string.IsNullOrEmpty(model." + dr.Table.Columns[i].ToString() + ".ToString())) ");
                strBuilder.AppendLine("       {");
                strBuilder.AppendLine("          sqlWhere.Append(\" AND " + dr.Table.Columns[i].ToString() + "=@" + dr.Table.Columns[i].ToString() + "\");");
                strBuilder.AppendLine("          parameters.Add(new SqlParameter(\"@" + dr.Table.Columns[i].ToString() + "\", SqlDbType.NVarChar, 255) { SqlValue = model." + dr.Table.Columns[i].ToString() + " });");
                strBuilder.AppendLine("       } ");
            }
            strBuilder.AppendLine("                    string strSql = string.Format(@\"");
            strBuilder.AppendLine(strTmp.ToString());
            strBuilder.AppendLine("                     \" ,sqlWhere.ToString(), (pageNo - 1) * pageSize + 1, pageNo * pageSize);");

            strBuilder.AppendLine(@"    

                   DataTable dt = SqlHelper.Query(strSql, parameters.ToArray()).Tables[0];
                  if (dt!=null)
                   {");
            strBuilder.AppendLine("        iRecordCount = int.Parse(dt.Rows[0][\"" + "rc" + "\"].ToString());");
            strBuilder.AppendLine(@"      return dt;
                            }
                           else
                          {
                              iRecordCount = 0;
                            return null;
                        }
                }    ");

            #endregion

            if ((bool)inputSql[6])
            {
                returnstr.AppendLine(strBuilder.ToString());
            }
            strBuilder = new StringBuilder();
            #region 生成删除的方法

            strBuilder.AppendLine("    public bool Delete" + Table + "(string " + Id + ")");
            strBuilder.AppendLine("   {");
            strBuilder.AppendLine("        List parameters = new List();");
            strTmp = new StringBuilder();
            strTmp.AppendLine("DELETE " + Table + " WHERE " + Id + "=" + Id + "");
            strBuilder.AppendLine("                    string strSql = string.Format(@\"");
            strBuilder.AppendLine(strTmp.ToString());
            strBuilder.AppendLine("                     \";");
            strBuilder.AppendLine("     int rowAffect =SqlHelper.Query(strSql, parameters.ToArray()).ToInt();;");
            strBuilder.AppendLine("      return rowAffect > 0 ? true : false;");
            strBuilder.AppendLine("      }");

            #endregion

            if ((bool)inputSql[7])
            {
                returnstr.AppendLine(strBuilder.ToString());
            }
            strBuilder = new StringBuilder();

if ((bool)inputSql[7])主要是对控件值得判断,是否勾选上,也就是是否需要生成改方法。导出的方法主要在公司已经封装好的代码上提取重复代码的,平时我们在做功能的时候只需要写这些代码即可。

      #region 导出excel方法

            strBuilder.AppendLine(@"     protected void btnExcel_Click(object sender, System.EventArgs e)
        {
            int intPageNo = 1;
            int intPageSize = 65535;
            int recordCount = 0;
            DataTable dt = GetUnAuthorizeAgreePassedDT( Model model intPageNo, intPageSize, out recordCount); ");
            strBuilder.AppendLine("     string strFileName = \"" + "导出Excel" + "\" + System.DateTime.Now.ToString(\" " + "yyyyMMddHHmmss" + "\");");
            strBuilder.AppendLine(@"        ExcelUtility excelUtil = new ExcelUtility(this, strFileName);
            List headerS = new List() { ");

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                string Type = dr.Table.Columns[i].DataType.ToString();
                switch (Type)
                {
                    case "System.DateTime":
                        strBuilder.AppendLine("           new ExcelHeader() { Name = \"字段名称自行补全\", DataType = EnumColumnDataType.日期, Width = 15 },");
                        break;
                    default:
                        strBuilder.AppendLine("           new ExcelHeader() { Name = \"字段名称自行补全\", DataType = EnumColumnDataType.文本, Width = 15 },");
                        break;
                }
            }
            strBuilder.AppendLine(@"          };
            excelUtil.CreateHeader(headerS);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    List dataVals = new List() { ");


            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                strBuilder.AppendLine("                            dr[\" " + dr.Table.Columns[i] + "\"].ToString()  ");
            }

            strBuilder.AppendLine(@"          };       
                    excelUtil.CreateItemRow(dataVals);
                }
            }
            excelUtil.Export();
            }
           "); 
            #endregion
懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法_第5张图片
3.png
懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法_第6张图片
4.png
懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法_第7张图片
5.png

另外做了几个功能,但是不是很好用,感兴趣的朋友可以去下载源码看一下。
github地址:https://github.com/Jimmey-Jiang/JWorkHelper

然后看一下生成的代码展示:


        public class Model
        {

            private Int _AYA_Code;
            public Int AYA_Code
            {
                get { return _AYA_Code; }
                set { _AYA_Code = value; }
            }
            private string _AYHA_Code;
            public string AYHA_Code
            {
                get { return _AYHA_Code; }
                set { _AYHA_Code = value; }
            }
            private string _Ctg_ID;
            public string Ctg_ID
            {
                get { return _Ctg_ID; }
                set { _Ctg_ID = value; }
            }
            private string _HospitalCode;
            public string HospitalCode
            {
                get { return _HospitalCode; }
                set { _HospitalCode = value; }
            }
            private string _HospitalName;
            public string HospitalName
            {
                get { return _HospitalName; }
                set { _HospitalName = value; }
            }
            private string _HospitalGrad;
            public string HospitalGrad
            {
                get { return _HospitalGrad; }
                set { _HospitalGrad = value; }
            }
            private string _HospitalRegionID;
            public string HospitalRegionID
            {
                get { return _HospitalRegionID; }
                set { _HospitalRegionID = value; }
            }
            private System.DateTime _DevelopmentLimitTime;
            public System.DateTime DevelopmentLimitTime
            {
                get { return _DevelopmentLimitTime; }
                set { _DevelopmentLimitTime = value; }
            }
            private System.DateTime _EffectiveTime;
            public System.DateTime EffectiveTime
            {
                get { return _EffectiveTime; }
                set { _EffectiveTime = value; }
            }
            private System.Decimal _MarketingManagementFee;
            public System.Decimal MarketingManagementFee
            {
                get { return _MarketingManagementFee; }
                set { _MarketingManagementFee = value; }
            }
            private System.Decimal _BidPrice;
            public System.Decimal BidPrice
            {
                get { return _BidPrice; }
                set { _BidPrice = value; }
            }
            private string _DeliveryCode;
            public string DeliveryCode
            {
                get { return _DeliveryCode; }
                set { _DeliveryCode = value; }
            }
            private string _DeliveryName;
            public string DeliveryName
            {
                get { return _DeliveryName; }
                set { _DeliveryName = value; }
            }
            private string _AgreeAdjuestType;
            public string AgreeAdjuestType
            {
                get { return _AgreeAdjuestType; }
                set { _AgreeAdjuestType = value; }
            }
            private string _ChangeContent;
            public string ChangeContent
            {
                get { return _ChangeContent; }
                set { _ChangeContent = value; }
            }
            private string _Status;
            public string Status
            {
                get { return _Status; }
                set { _Status = value; }
            }
            private System.Decimal _DeliveryPrice;
            public System.Decimal DeliveryPrice
            {
                get { return _DeliveryPrice; }
                set { _DeliveryPrice = value; }
            }
            private System.Decimal _BasePrice;
            public System.Decimal BasePrice
            {
                get { return _BasePrice; }
                set { _BasePrice = value; }
            }
            private string _CategoryCommodityName;
            public string CategoryCommodityName
            {
                get { return _CategoryCommodityName; }
                set { _CategoryCommodityName = value; }
            }
            private string _CategorySystemName;
            public string CategorySystemName
            {
                get { return _CategorySystemName; }
                set { _CategorySystemName = value; }
            }
            private string _CategoryCommName;
            public string CategoryCommName
            {
                get { return _CategoryCommName; }
                set { _CategoryCommName = value; }
            }
            private string _CategorySpec;
            public string CategorySpec
            {
                get { return _CategorySpec; }
                set { _CategorySpec = value; }
            }
            private string _Formulation;
            public string Formulation
            {
                get { return _Formulation; }
                set { _Formulation = value; }
            }
            private string _BusinessModel;
            public string BusinessModel
            {
                get { return _BusinessModel; }
                set { _BusinessModel = value; }
            }

        }


        public bool InsertAgreement_YNSHigh_Authorize(Model model)
        {

            string strSql = @"
               INSERT Agreement_YNSHigh_Authorize(
                 AYA_Code,
                 AYHA_Code,
                 Ctg_ID,
                 HospitalCode,
                 HospitalName,
                 HospitalGrad,
                 HospitalRegionID,
                 DevelopmentLimitTime,
                 EffectiveTime,
                 MarketingManagementFee,
                 BidPrice,
                 DeliveryCode,
                 DeliveryName,
                 AgreeAdjuestType,
                 ChangeContent,
                 Status,
                 DeliveryPrice,
                 BasePrice,
                 CategoryCommodityName,
                 CategorySystemName,
                 CategoryCommName,
                 CategorySpec,
                 Formulation,
                 BusinessModel)
                 VALUES (
                    @AYA_Code,
                    @AYHA_Code,
                    @Ctg_ID,
                    @HospitalCode,
                    @HospitalName,
                    @HospitalGrad,
                    @HospitalRegionID,
                    @DevelopmentLimitTime,
                    @EffectiveTime,
                    @MarketingManagementFee,
                    @BidPrice,
                    @DeliveryCode,
                    @DeliveryName,
                    @AgreeAdjuestType,
                    @ChangeContent,
                    @Status,
                    @DeliveryPrice,
                    @BasePrice,
                    @CategoryCommodityName,
                    @CategorySystemName,
                    @CategoryCommName,
                    @CategorySpec,
                    @Formulation,
                   @BusinessModel)

                     ";
            SqlParameter[] parameters = new SqlParameter[]
                                                  {
                     new SqlParameter("@AYA_Code", SqlDbType.Int),
                     new SqlParameter("@AYHA_Code", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Ctg_ID", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalCode", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalGrad", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalRegionID", SqlDbType.NVarChar, 255),
                     new SqlParameter("@DevelopmentLimitTime", SqlDbType.DateTime),
                     new SqlParameter("@EffectiveTime", SqlDbType.DateTime),
                      new SqlParameter("@MarketingManagementFee", SqlDbType.Decimal),
                      new SqlParameter("@BidPrice", SqlDbType.Decimal),
                     new SqlParameter("@DeliveryCode", SqlDbType.NVarChar, 255),
                     new SqlParameter("@DeliveryName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@AgreeAdjuestType", SqlDbType.NVarChar, 255),
                     new SqlParameter("@ChangeContent", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Status", SqlDbType.NVarChar, 255),
                      new SqlParameter("@DeliveryPrice", SqlDbType.Decimal),
                      new SqlParameter("@BasePrice", SqlDbType.Decimal),
                     new SqlParameter("@CategoryCommodityName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategorySystemName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategoryCommName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategorySpec", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Formulation", SqlDbType.NVarChar, 255),
                     new SqlParameter("@BusinessModel", SqlDbType.NVarChar, 255),
                            };
            parameters[0].Value = model.AYA_Code;
            parameters[1].Value = model.AYHA_Code;
            parameters[2].Value = model.Ctg_ID;
            parameters[3].Value = model.HospitalCode;
            parameters[4].Value = model.HospitalName;
            parameters[5].Value = model.HospitalGrad;
            parameters[6].Value = model.HospitalRegionID;
            parameters[7].Value = model.DevelopmentLimitTime;
            parameters[8].Value = model.EffectiveTime;
            parameters[9].Value = model.MarketingManagementFee;
            parameters[10].Value = model.BidPrice;
            parameters[11].Value = model.DeliveryCode;
            parameters[12].Value = model.DeliveryName;
            parameters[13].Value = model.AgreeAdjuestType;
            parameters[14].Value = model.ChangeContent;
            parameters[15].Value = model.Status;
            parameters[16].Value = model.DeliveryPrice;
            parameters[17].Value = model.BasePrice;
            parameters[18].Value = model.CategoryCommodityName;
            parameters[19].Value = model.CategorySystemName;
            parameters[20].Value = model.CategoryCommName;
            parameters[21].Value = model.CategorySpec;
            parameters[22].Value = model.Formulation;
            parameters[23].Value = model.BusinessModel;

            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters);
                        if (i > 0)
                        {
                            trans.Commit();
                            return i > 0;
                        }
                        else
                        {
                            trans.Rollback();
                            return false;
                        }
                    }
                    catch (System.Exception e)
                    {
                        return false;
                        trans.Rollback();
                        throw e;
                    }
                }
            }

        }

        public bool UpdateAgreement_YNSHigh_AuthorizeById(Model model)
        {

            string strSql = @"
               Update Agreement_YNSHigh_Authorize  SET 
                  AYA_Code=@AYA_Code,
                  AYHA_Code=@AYHA_Code,
                  Ctg_ID=@Ctg_ID,
                  HospitalCode=@HospitalCode,
                  HospitalName=@HospitalName,
                  HospitalGrad=@HospitalGrad,
                  HospitalRegionID=@HospitalRegionID,
                  DevelopmentLimitTime=@DevelopmentLimitTime,
                  EffectiveTime=@EffectiveTime,
                  MarketingManagementFee=@MarketingManagementFee,
                  BidPrice=@BidPrice,
                  DeliveryCode=@DeliveryCode,
                  DeliveryName=@DeliveryName,
                  AgreeAdjuestType=@AgreeAdjuestType,
                  ChangeContent=@ChangeContent,
                  Status=@Status,
                  DeliveryPrice=@DeliveryPrice,
                  BasePrice=@BasePrice,
                  CategoryCommodityName=@CategoryCommodityName,
                  CategorySystemName=@CategorySystemName,
                  CategoryCommName=@CategoryCommName,
                  CategorySpec=@CategorySpec,
                  Formulation=@Formulation,
                 BusinessModel=@BusinessModel where AYA_Code=@AYA_Code  

                     ";
            SqlParameter[] parameters = new SqlParameter[]
                                                  {
                      new SqlParameter("@AYA_Code", SqlDbType.NVarChar, 255),
                     new SqlParameter("@AYHA_Code", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Ctg_ID", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalCode", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalGrad", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalRegionID", SqlDbType.NVarChar, 255),
                     new SqlParameter("@DevelopmentLimitTime", SqlDbType.DateTime),
                     new SqlParameter("@EffectiveTime", SqlDbType.DateTime),
                      new SqlParameter("@MarketingManagementFee", SqlDbType.Decimal),
                      new SqlParameter("@BidPrice", SqlDbType.Decimal),
                     new SqlParameter("@DeliveryCode", SqlDbType.NVarChar, 255),
                     new SqlParameter("@DeliveryName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@AgreeAdjuestType", SqlDbType.NVarChar, 255),
                     new SqlParameter("@ChangeContent", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Status", SqlDbType.NVarChar, 255),
                      new SqlParameter("@DeliveryPrice", SqlDbType.Decimal),
                      new SqlParameter("@BasePrice", SqlDbType.Decimal),
                     new SqlParameter("@CategoryCommodityName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategorySystemName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategoryCommName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategorySpec", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Formulation", SqlDbType.NVarChar, 255),
                     new SqlParameter("@BusinessModel", SqlDbType.NVarChar, 255),
                            };
            parameters[0].Value = model.AYA_Code;
            parameters[1].Value = model.AYHA_Code;
            parameters[2].Value = model.Ctg_ID;
            parameters[3].Value = model.HospitalCode;
            parameters[4].Value = model.HospitalName;
            parameters[5].Value = model.HospitalGrad;
            parameters[6].Value = model.HospitalRegionID;
            parameters[7].Value = model.DevelopmentLimitTime;
            parameters[8].Value = model.EffectiveTime;
            parameters[9].Value = model.MarketingManagementFee;
            parameters[10].Value = model.BidPrice;
            parameters[11].Value = model.DeliveryCode;
            parameters[12].Value = model.DeliveryName;
            parameters[13].Value = model.AgreeAdjuestType;
            parameters[14].Value = model.ChangeContent;
            parameters[15].Value = model.Status;
            parameters[16].Value = model.DeliveryPrice;
            parameters[17].Value = model.BasePrice;
            parameters[18].Value = model.CategoryCommodityName;
            parameters[19].Value = model.CategorySystemName;
            parameters[20].Value = model.CategoryCommName;
            parameters[21].Value = model.CategorySpec;
            parameters[22].Value = model.Formulation;
            parameters[23].Value = model.BusinessModel;

            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters);
                        if (i > 0)
                        {
                            trans.Commit();
                            return i > 0;
                        }
                        else
                        {
                            trans.Rollback();
                            return false;
                        }
                    }
                    catch (System.Exception e)
                    {
                        return false;
                        trans.Rollback();
                        throw e;
                    }
                }
            }

        }

        public DataTable GetDataByAgreement_YNSHigh_Authorize(Model model, int pageNo, int pageSize, ref int iRecordCount)
        {
            List parameters = new List();
            StringBuilder sqlWhere = new StringBuilder();
            if (!string.IsNullOrEmpty(model.AYA_Code.ToString()))
            {
                sqlWhere.Append(" AND AYA_Code=@AYA_Code");
                parameters.Add(new SqlParameter("@AYA_Code", SqlDbType.NVarChar, 255) { SqlValue = model.AYA_Code });
            }
            if (!string.IsNullOrEmpty(model.AYHA_Code.ToString()))
            {
                sqlWhere.Append(" AND AYHA_Code=@AYHA_Code");
                parameters.Add(new SqlParameter("@AYHA_Code", SqlDbType.NVarChar, 255) { SqlValue = model.AYHA_Code });
            }
            if (!string.IsNullOrEmpty(model.Ctg_ID.ToString()))
            {
                sqlWhere.Append(" AND Ctg_ID=@Ctg_ID");
                parameters.Add(new SqlParameter("@Ctg_ID", SqlDbType.NVarChar, 255) { SqlValue = model.Ctg_ID });
            }
            if (!string.IsNullOrEmpty(model.HospitalCode.ToString()))
            {
                sqlWhere.Append(" AND HospitalCode=@HospitalCode");
                parameters.Add(new SqlParameter("@HospitalCode", SqlDbType.NVarChar, 255) { SqlValue = model.HospitalCode });
            }
            if (!string.IsNullOrEmpty(model.HospitalName.ToString()))
            {
                sqlWhere.Append(" AND HospitalName=@HospitalName");
                parameters.Add(new SqlParameter("@HospitalName", SqlDbType.NVarChar, 255) { SqlValue = model.HospitalName });
            }
            if (!string.IsNullOrEmpty(model.HospitalGrad.ToString()))
            {
                sqlWhere.Append(" AND HospitalGrad=@HospitalGrad");
                parameters.Add(new SqlParameter("@HospitalGrad", SqlDbType.NVarChar, 255) { SqlValue = model.HospitalGrad });
            }
            if (!string.IsNullOrEmpty(model.HospitalRegionID.ToString()))
            {
                sqlWhere.Append(" AND HospitalRegionID=@HospitalRegionID");
                parameters.Add(new SqlParameter("@HospitalRegionID", SqlDbType.NVarChar, 255) { SqlValue = model.HospitalRegionID });
            }
            if (!string.IsNullOrEmpty(model.DevelopmentLimitTime.ToString()))
            {
                sqlWhere.Append(" AND DevelopmentLimitTime=@DevelopmentLimitTime");
                parameters.Add(new SqlParameter("@DevelopmentLimitTime", SqlDbType.NVarChar, 255) { SqlValue = model.DevelopmentLimitTime });
            }
            if (!string.IsNullOrEmpty(model.EffectiveTime.ToString()))
            {
                sqlWhere.Append(" AND EffectiveTime=@EffectiveTime");
                parameters.Add(new SqlParameter("@EffectiveTime", SqlDbType.NVarChar, 255) { SqlValue = model.EffectiveTime });
            }
            if (!string.IsNullOrEmpty(model.MarketingManagementFee.ToString()))
            {
                sqlWhere.Append(" AND MarketingManagementFee=@MarketingManagementFee");
                parameters.Add(new SqlParameter("@MarketingManagementFee", SqlDbType.NVarChar, 255) { SqlValue = model.MarketingManagementFee });
            }
            if (!string.IsNullOrEmpty(model.BidPrice.ToString()))
            {
                sqlWhere.Append(" AND BidPrice=@BidPrice");
                parameters.Add(new SqlParameter("@BidPrice", SqlDbType.NVarChar, 255) { SqlValue = model.BidPrice });
            }
            if (!string.IsNullOrEmpty(model.DeliveryCode.ToString()))
            {
                sqlWhere.Append(" AND DeliveryCode=@DeliveryCode");
                parameters.Add(new SqlParameter("@DeliveryCode", SqlDbType.NVarChar, 255) { SqlValue = model.DeliveryCode });
            }
            if (!string.IsNullOrEmpty(model.DeliveryName.ToString()))
            {
                sqlWhere.Append(" AND DeliveryName=@DeliveryName");
                parameters.Add(new SqlParameter("@DeliveryName", SqlDbType.NVarChar, 255) { SqlValue = model.DeliveryName });
            }
            if (!string.IsNullOrEmpty(model.AgreeAdjuestType.ToString()))
            {
                sqlWhere.Append(" AND AgreeAdjuestType=@AgreeAdjuestType");
                parameters.Add(new SqlParameter("@AgreeAdjuestType", SqlDbType.NVarChar, 255) { SqlValue = model.AgreeAdjuestType });
            }
            if (!string.IsNullOrEmpty(model.ChangeContent.ToString()))
            {
                sqlWhere.Append(" AND ChangeContent=@ChangeContent");
                parameters.Add(new SqlParameter("@ChangeContent", SqlDbType.NVarChar, 255) { SqlValue = model.ChangeContent });
            }
            if (!string.IsNullOrEmpty(model.Status.ToString()))
            {
                sqlWhere.Append(" AND Status=@Status");
                parameters.Add(new SqlParameter("@Status", SqlDbType.NVarChar, 255) { SqlValue = model.Status });
            }
            if (!string.IsNullOrEmpty(model.DeliveryPrice.ToString()))
            {
                sqlWhere.Append(" AND DeliveryPrice=@DeliveryPrice");
                parameters.Add(new SqlParameter("@DeliveryPrice", SqlDbType.NVarChar, 255) { SqlValue = model.DeliveryPrice });
            }
            if (!string.IsNullOrEmpty(model.BasePrice.ToString()))
            {
                sqlWhere.Append(" AND BasePrice=@BasePrice");
                parameters.Add(new SqlParameter("@BasePrice", SqlDbType.NVarChar, 255) { SqlValue = model.BasePrice });
            }
            if (!string.IsNullOrEmpty(model.CategoryCommodityName.ToString()))
            {
                sqlWhere.Append(" AND CategoryCommodityName=@CategoryCommodityName");
                parameters.Add(new SqlParameter("@CategoryCommodityName", SqlDbType.NVarChar, 255) { SqlValue = model.CategoryCommodityName });
            }
            if (!string.IsNullOrEmpty(model.CategorySystemName.ToString()))
            {
                sqlWhere.Append(" AND CategorySystemName=@CategorySystemName");
                parameters.Add(new SqlParameter("@CategorySystemName", SqlDbType.NVarChar, 255) { SqlValue = model.CategorySystemName });
            }
            if (!string.IsNullOrEmpty(model.CategoryCommName.ToString()))
            {
                sqlWhere.Append(" AND CategoryCommName=@CategoryCommName");
                parameters.Add(new SqlParameter("@CategoryCommName", SqlDbType.NVarChar, 255) { SqlValue = model.CategoryCommName });
            }
            if (!string.IsNullOrEmpty(model.CategorySpec.ToString()))
            {
                sqlWhere.Append(" AND CategorySpec=@CategorySpec");
                parameters.Add(new SqlParameter("@CategorySpec", SqlDbType.NVarChar, 255) { SqlValue = model.CategorySpec });
            }
            if (!string.IsNullOrEmpty(model.Formulation.ToString()))
            {
                sqlWhere.Append(" AND Formulation=@Formulation");
                parameters.Add(new SqlParameter("@Formulation", SqlDbType.NVarChar, 255) { SqlValue = model.Formulation });
            }
            if (!string.IsNullOrEmpty(model.BusinessModel.ToString()))
            {
                sqlWhere.Append(" AND BusinessModel=@BusinessModel");
                parameters.Add(new SqlParameter("@BusinessModel", SqlDbType.NVarChar, 255) { SqlValue = model.BusinessModel });
            }
            string strSql = string.Format(@"
WITH temp AS ( SELECT rn =  ROW_NUMBER() OVER (ORDER BY AYA_Code  desc), *FROM  Agreement_YNSHigh_Authorize WHERE 1=1 {0} )
SELECT *,rc=(select count(1) from temp) FROM temp WHERE rn BETWEEN {1} AND {2}

                     ", sqlWhere.ToString(), (pageNo - 1) * pageSize + 1, pageNo * pageSize);


            DataTable dt = SqlHelper.Query(strSql, parameters.ToArray()).Tables[0];
            if (dt != null)
            {
                iRecordCount = int.Parse(dt.Rows[0]["rc"].ToString());
                return dt;
            }
            else
            {
                iRecordCount = 0;
                return null;
            }
        }

        public bool DeleteAgreement_YNSHigh_Authorize(string AYA_Code)
   {
        List parameters = new List();
                    string strSql = string.Format(@"
DELETE Agreement_YNSHigh_Authorize WHERE AYA_Code=AYA_Code

                     ";
     int rowAffect =SqlHelper.Query(strSql, parameters.ToArray()).ToInt();;
      return rowAffect > 0 ? true : false;
      }

        protected void btnExcel_Click(object sender, System.EventArgs e)
        {
            int intPageNo = 1;
            int intPageSize = 65535;
            int recordCount = 0;
            DataTable dt = GetUnAuthorizeAgreePassedDT( Model model intPageNo, intPageSize, out recordCount); 
     string strFileName = "导出Excel" + System.DateTime.Now.ToString(" yyyyMMddHHmmss");
        ExcelUtility excelUtil = new ExcelUtility(this, strFileName);
            List headerS = new List() { 
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.日期, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.日期, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
          };
            excelUtil.CreateHeader(headerS);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    List dataVals = new List() { 
                            dr[" AYA_Code"].ToString()  
                            dr[" AYHA_Code"].ToString()  
                            dr[" Ctg_ID"].ToString()  
                            dr[" HospitalCode"].ToString()  
                            dr[" HospitalName"].ToString()  
                            dr[" HospitalGrad"].ToString()  
                            dr[" HospitalRegionID"].ToString()  
                            dr[" DevelopmentLimitTime"].ToString()  
                            dr[" EffectiveTime"].ToString()  
                            dr[" MarketingManagementFee"].ToString()  
                            dr[" BidPrice"].ToString()  
                            dr[" DeliveryCode"].ToString()  
                            dr[" DeliveryName"].ToString()  
                            dr[" AgreeAdjuestType"].ToString()  
                            dr[" ChangeContent"].ToString()  
                            dr[" Status"].ToString()  
                            dr[" DeliveryPrice"].ToString()  
                            dr[" BasePrice"].ToString()  
                            dr[" CategoryCommodityName"].ToString()  
                            dr[" CategorySystemName"].ToString()  
                            dr[" CategoryCommName"].ToString()  
                            dr[" CategorySpec"].ToString()  
                            dr[" Formulation"].ToString()  
                            dr[" BusinessModel"].ToString()  
          };       
                    excelUtil.CreateItemRow(dataVals);
                }
            }
            excelUtil.Export();
            }




你可能感兴趣的:(懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法)