懶人小工具2:T4自動生成Model,Insert,Select,Delete以及導出Excel的方法html
github地址:https://github.com/Jimmey-Jiang/JWorkHelper前端
在開發的過程當中,咱們爲了節約時間,每每會將大量重複機械的代碼封裝,考慮代碼的複用性,這樣咱們能夠節約不少時間來作別的事情。最近跳槽到一節webform開發的公司,主要是開發本身公司用的ERP。開始由於一些誘惑進來的,如今感受其實有些後悔放棄了很好的學習ABP以及新知識點像一些很新穎的前端框架進這個公司。但如今跳槽也不是一個明智之舉,很差意思扯遠了,既來之則安之。最近寫了個小工具。主要針對webform開發過程當中一些重複的代碼處理。git
github地址:https://github.com/Jimmey-Jiang/JWorkHelper
其實沒有什麼特別大的技術難度,其實webform開發貌似也沒有特別大的技術難度。github
而後新建類Program.cs,這裏是做爲主程序入口。web
1 using System; 2 using System.Windows.Forms; 3 4 namespace DevLogHelper 5 { 6 static class Program 7 { 8 /// <summary> 9 /// 應用程序的主入口點。 10 /// </summary> 11 [STAThread] 12 static void Main() 13 { 14 Application.EnableVisualStyles(); 15 Application.SetCompatibleTextRenderingDefault(false); 16 Application.Run(new BaseSqlBuilder()); 17 } 18 19 } 20 }
爲Main()方法加上STAThread標籤。每次只能啓動一個窗口。
new 一個BaseSqlBuilder實例,BaseSqlBuilder實例是什麼呢,就是咱們今天的主題了。sql
其實界面特別簡單的。就是幾個label、多選框、容器。
看下代碼:數據庫
1 using System; 2 using System.Resources; 3 using System.Text; 4 using System.Windows.Forms; 5 using DevLogHelper.Resources; 6 7 namespace DevLogHelper 8 { 9 public partial class BaseSqlBuilder : Form 10 { 11 readonly ResourceManager _rm = new ResourceManager(typeof(ResourceDevCode)); 12 public BaseSqlBuilder() 13 { 14 InitializeComponent(); 15 } 16 17 private void BaseSqlBuilder_Load(object sender, EventArgs e) 18 { 19 20 } 21 /// <summary> 22 /// 生成 23 /// </summary> 24 /// <param name="sender"></param> 25 /// <param name="e"></param> 26 private void btnCreate_Click(object sender, EventArgs e) 27 { 28 string msg = _rm.GetString("BaseSqlTip"); 29 try 30 { 31 BaseSql.BaseSql sq = new BaseSql.BaseSql(); 32 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); 33 txtResult.Text = str.ToString(); 34 Clipboard.SetDataObject(str.ToString()); 35 } 36 catch (Exception ex) 37 { 38 msg = ex.Message; 39 } 40 labTip.Text = msg; 41 } 42 43 } 44 }
窗體BaseSqlBuilder繼承自Form沒必要多說。ResourceManager是什麼呢,ResourceManager就是一個資源文件,用於處理消息,或者路徑什麼。後面補上圖。
新建一個BaseSql用於處理sql。把頁面上的控件消息傳遞過去。封裝一個數據的形式。前端框架
跟蹤BuilderCode到BaseSql類。mvc
首先是對控件傳遞過來值得檢查,參數是否爲空等。框架
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了。
1 #region 封裝實體Model 2 3 #region 封裝實體Model 4 5 strBuilder.AppendLine(@" 6 public class Model 7 { 8 "); 9 for (int i = 0; i < dr.Table.Columns.Count; i++) 10 { 11 if (i == 0) 12 { 13 Id = dr.Table.Columns[0].ToString();//通常狀況第一個字段是主鍵,固然若是第一個字段不是主鍵,那就須要修改了 14 } 15 string Type = dr.Table.Columns[i].DataType.ToString(); 16 switch (Type) 17 { 18 case "System.String": 19 strBuilder.AppendLine(" private string " + "_" + dr.Table.Columns[i] + ";"); 20 strBuilder.AppendLine(" public string " + dr.Table.Columns[i] + ""); 21 strBuilder.AppendLine(" {"); 22 strBuilder.AppendLine(" get { return " + "_" + dr.Table.Columns[i] + "; }"); 23 strBuilder.AppendLine(" set { " + "_" + dr.Table.Columns[i] + " = value; }"); 24 strBuilder.AppendLine(" }"); 25 break; 26 case "System.Int": 27 strBuilder.AppendLine(" private Int " + "_" + dr.Table.Columns[i] + ";"); 28 strBuilder.AppendLine(" public Int " + dr.Table.Columns[i] + ""); 29 strBuilder.AppendLine(" {"); 30 strBuilder.AppendLine(" get { return " + "_" + dr.Table.Columns[i] + "; }"); 31 strBuilder.AppendLine(" set { " + "_" + dr.Table.Columns[i] + " = value; }"); 32 strBuilder.AppendLine(" }"); 33 break; 34 case "System.Int32": 35 strBuilder.AppendLine(" private Int " + "_" + dr.Table.Columns[i] + ";"); 36 strBuilder.AppendLine(" public Int " + dr.Table.Columns[i] + ""); 37 strBuilder.AppendLine(" {"); 38 strBuilder.AppendLine(" get { return " + "_" + dr.Table.Columns[i] + "; }"); 39 strBuilder.AppendLine(" set { " + "_" + dr.Table.Columns[i] + " = value; }"); 40 strBuilder.AppendLine(" }"); 41 break; 42 case "System.DateTime": 43 strBuilder.AppendLine(" private System.DateTime " + "_" + dr.Table.Columns[i] + ";"); 44 strBuilder.AppendLine(" public System.DateTime " + dr.Table.Columns[i] + ""); 45 strBuilder.AppendLine(" {"); 46 strBuilder.AppendLine(" get { return " + "_" + dr.Table.Columns[i] + "; }"); 47 strBuilder.AppendLine(" set { " + "_" + dr.Table.Columns[i] + " = value; }"); 48 strBuilder.AppendLine(" }"); 49 break; 50 case "System.Decimal": 51 strBuilder.AppendLine(" private System.Decimal " + "_" + dr.Table.Columns[i] + ";"); 52 strBuilder.AppendLine(" public System.Decimal " + dr.Table.Columns[i] + ""); 53 strBuilder.AppendLine(" {"); 54 strBuilder.AppendLine(" get { return " + "_" + dr.Table.Columns[i] + "; }"); 55 strBuilder.AppendLine(" set { " + "_" + dr.Table.Columns[i] + " = value; }"); 56 strBuilder.AppendLine(" }"); 57 break; 58 default: 59 strBuilder.AppendLine(" private string " + "_" + dr.Table.Columns[i] + ";"); 60 strBuilder.AppendLine(" public string " + dr.Table.Columns[i] + ""); 61 strBuilder.AppendLine(" {"); 62 strBuilder.AppendLine(" get { return " + "_" + dr.Table.Columns[i] + "; }"); 63 strBuilder.AppendLine(" set { " + "_" + dr.Table.Columns[i] + " = value; }"); 64 strBuilder.AppendLine(" }"); 65 break; 66 } 67 } 68 strBuilder.AppendLine(@" 69 } 70 "); 71 72 #endregion
首先咱們是生成Model。有了Model纔有下面的增刪改查的方法。
其實也很簡單,dr.Table.Columns[i].DataType.ToString(),咱們就是根據DataRow循環table列,判斷字段類型,而後根據對應的字段類型封裝成model.單選框默認勾選的,這裏先去掉勾選,輸入表名,點擊生成,而後和數據庫表對應,看一下效果。
Model 是最實用的,就算之後咱們在用mvc或者ABP等其餘框架底層用codefirst等orm框架的時候,咱們也能夠用這種方式生成Model.
1 public bool InsertAgreement_YNSHigh_Authorize(Model model) 2 { 3 4 string strSql = @" 5 INSERT Agreement_YNSHigh_Authorize( 6 AYA_Code, 7 AYHA_Code, 8 Ctg_ID, 9 HospitalCode, 10 HospitalName, 11 HospitalGrad, 12 HospitalRegionID, 13 DevelopmentLimitTime, 14 EffectiveTime, 15 MarketingManagementFee, 16 BidPrice, 17 DeliveryCode, 18 DeliveryName, 19 AgreeAdjuestType, 20 ChangeContent, 21 Status, 22 DeliveryPrice, 23 BasePrice, 24 CategoryCommodityName, 25 CategorySystemName, 26 CategoryCommName, 27 CategorySpec, 28 Formulation, 29 BusinessModel) 30 VALUES ( 31 @AYA_Code, 32 @AYHA_Code, 33 @Ctg_ID, 34 @HospitalCode, 35 @HospitalName, 36 @HospitalGrad, 37 @HospitalRegionID, 38 @DevelopmentLimitTime, 39 @EffectiveTime, 40 @MarketingManagementFee, 41 @BidPrice, 42 @DeliveryCode, 43 @DeliveryName, 44 @AgreeAdjuestType, 45 @ChangeContent, 46 @Status, 47 @DeliveryPrice, 48 @BasePrice, 49 @CategoryCommodityName, 50 @CategorySystemName, 51 @CategoryCommName, 52 @CategorySpec, 53 @Formulation, 54 @BusinessModel) 55 56 "; 57 SqlParameter[] parameters = new SqlParameter[] 58 { 59 new SqlParameter("@AYA_Code", SqlDbType.NVarChar, 255), 60 new SqlParameter("@AYHA_Code", SqlDbType.NVarChar, 255), 61 new SqlParameter("@Ctg_ID", SqlDbType.NVarChar, 255), 62 new SqlParameter("@HospitalCode", SqlDbType.NVarChar, 255), 63 new SqlParameter("@HospitalName", SqlDbType.NVarChar, 255), 64 new SqlParameter("@HospitalGrad", SqlDbType.NVarChar, 255), 65 new SqlParameter("@HospitalRegionID", SqlDbType.NVarChar, 255), 66 new SqlParameter("@DevelopmentLimitTime", SqlDbType.DateTime), 67 new SqlParameter("@EffectiveTime", SqlDbType.DateTime), 68 new SqlParameter("@MarketingManagementFee", SqlDbType.Decimal), 69 new SqlParameter("@BidPrice", SqlDbType.Decimal), 70 new SqlParameter("@DeliveryCode", SqlDbType.NVarChar, 255), 71 new SqlParameter("@DeliveryName", SqlDbType.NVarChar, 255), 72 new SqlParameter("@AgreeAdjuestType", SqlDbType.NVarChar, 255), 73 new SqlParameter("@ChangeContent", SqlDbType.NVarChar, 255), 74 new SqlParameter("@Status", SqlDbType.NVarChar, 255), 75 new SqlParameter("@DeliveryPrice", SqlDbType.Decimal), 76 new SqlParameter("@BasePrice", SqlDbType.Decimal), 77 new SqlParameter("@CategoryCommodityName", SqlDbType.NVarChar, 255), 78 new SqlParameter("@CategorySystemName", SqlDbType.NVarChar, 255), 79 new SqlParameter("@CategoryCommName", SqlDbType.NVarChar, 255), 80 new SqlParameter("@CategorySpec", SqlDbType.NVarChar, 255), 81 new SqlParameter("@Formulation", SqlDbType.NVarChar, 255), 82 new SqlParameter("@BusinessModel", SqlDbType.NVarChar, 255), 83 }; 84 parameters[0].Value = model.AYA_Code; 85 parameters[1].Value = model.AYHA_Code; 86 parameters[2].Value = model.Ctg_ID; 87 parameters[3].Value = model.HospitalCode; 88 parameters[4].Value = model.HospitalName; 89 parameters[5].Value = model.HospitalGrad; 90 parameters[6].Value = model.HospitalRegionID; 91 parameters[7].Value = model.DevelopmentLimitTime; 92 parameters[8].Value = model.EffectiveTime; 93 parameters[9].Value = model.MarketingManagementFee; 94 parameters[10].Value = model.BidPrice; 95 parameters[11].Value = model.DeliveryCode; 96 parameters[12].Value = model.DeliveryName; 97 parameters[13].Value = model.AgreeAdjuestType; 98 parameters[14].Value = model.ChangeContent; 99 parameters[15].Value = model.Status; 100 parameters[16].Value = model.DeliveryPrice; 101 parameters[17].Value = model.BasePrice; 102 parameters[18].Value = model.CategoryCommodityName; 103 parameters[19].Value = model.CategorySystemName; 104 parameters[20].Value = model.CategoryCommName; 105 parameters[21].Value = model.CategorySpec; 106 parameters[22].Value = model.Formulation; 107 parameters[23].Value = model.BusinessModel; 108 109 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString)) 110 { 111 conn.Open(); 112 using (SqlTransaction trans = conn.BeginTransaction()) 113 { 114 try 115 { 116 int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters); 117 if (i > 0) 118 { 119 trans.Commit(); 120 return i > 0; 121 } 122 else 123 { 124 trans.Rollback(); 125 return false; 126 } 127 } 128 catch (System.Exception e) 129 { 130 return false; 131 trans.Rollback(); 132 throw e; 133 } 134 } 135 } 136 137 }
平時咱們在新增數據的時候,就以Agreement_YNSHigh_Authorize爲例,通常都是這樣超作的,加上事務,參數化傳過來的參數,這樣寫起來也很是麻煩。咱們這裏了也對INSERT 作一下封裝。
1 #region 生成插入Insert方法 2 3 #region 生成插入sql語句 4 5 StringBuilder strTmp = new StringBuilder(); 6 try 7 { 8 for (int i = 0; i < dr.Table.Columns.Count; i++)//生成insert 9 { 10 if (i == 0) 11 { 12 strTmp.AppendLine(" INSERT " + Table + "("); 13 } 14 if (i == dr.Table.Columns.Count - 1) 15 { 16 strTmp.AppendLine(" " + dr.Table.Columns[i].ToString() + ")"); 17 } 18 else 19 { 20 strTmp.AppendLine(" " + dr.Table.Columns[i].ToString() + ","); 21 } 22 } 23 24 for (int i = 0; i < dr.Table.Columns.Count; i++) 25 { 26 if (i == 0) 27 { 28 strTmp.AppendLine(" VALUES " + "("); 29 } 30 if (i == dr.Table.Columns.Count - 1) 31 { 32 strTmp.AppendLine(" @" + dr.Table.Columns[i].ToString() + ")"); 33 } 34 else 35 { 36 strTmp.AppendLine(" @" + dr.Table.Columns[i].ToString() + ","); 37 } 38 39 } 40 } 41 catch (System.Exception ex) 42 { 43 44 throw ex; 45 } 46 47 #endregion 48 49 50 51 52 53 strBuilder.AppendLine(" public bool Insert" + Table + "(Model model)"); 54 strBuilder.AppendLine(@" { 55 "); 56 strBuilder.AppendLine(" string strSql = @\""); 57 strBuilder.AppendLine(strTmp.ToString()); 58 strBuilder.AppendLine(" \";"); 59 60 strBuilder.AppendLine(@" SqlParameter[] parameters = new SqlParameter[] 61 {"); 62 //參數類型 63 for (int i = 0; i < dr.Table.Columns.Count; i++) 64 { 65 string Type = dr.Table.Columns[i].DataType.ToString(); 66 switch (Type) 67 { 68 case "System.String": 69 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.NVarChar, 255),"); 70 break; 71 case "System.Int": 72 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Int),"); 73 break; 74 case "System.Int32": 75 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Int),"); 76 break; 77 case "System.DateTime": 78 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.DateTime),"); 79 break; 80 case "System.Decimal": 81 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Decimal),"); 82 break; 83 default: 84 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.NVarChar, 255),"); 85 break; 86 } 87 } 88 strBuilder.AppendLine(@" };"); 89 90 for (int i = 0; i < dr.Table.Columns.Count; i++) 91 { 92 strBuilder.AppendLine(" parameters[" + i + "].Value =" + "model." + dr.Table.Columns[i] + ";"); 93 } 94 95 strBuilder.AppendLine(@" 96 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString)) 97 { 98 conn.Open(); 99 using (SqlTransaction trans = conn.BeginTransaction()) 100 { 101 try 102 { 103 int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters); 104 if (i > 0) 105 { 106 trans.Commit(); 107 return i > 0; 108 } 109 else 110 { 111 trans.Rollback(); 112 return false; 113 } 114 } 115 catch (System.Exception e) 116 { 117 return false; 118 trans.Rollback(); 119 throw e; 120 } 121 } 122 } 123 "); 124 strBuilder.AppendLine("}"); 125 126 #endregion
首先是根據sql生成字段和參數字段。這都是很繁瑣的工做,並且不能出錯。也是對DataRow table的循環和封裝處理。須要注意一下轉義字符處理,注意對事務的處理。另外update,select,delete的處理方式與insert相似,不在累述,放上代碼。
1 if ((bool)inputSql[4]) 2 { 3 returnstr.AppendLine(strBuilder.ToString()); 4 } 5 strBuilder = new StringBuilder(); 6 #region 生成更新Update 方法 7 8 #region 生成更新Update sql語句 9 10 strTmp = new StringBuilder(); //sql 11 try 12 { 13 for (int i = 0; i < dr.Table.Columns.Count; i++)//生成Update 14 { 15 if (i == 0) 16 { 17 strTmp.AppendLine(" Update " + Table + " SET "); 18 } 19 if (i == dr.Table.Columns.Count - 1) 20 { 21 22 23 strTmp.AppendLine(" " + dr.Table.Columns[i].ToString() + "=" + "@" + dr.Table.Columns[i].ToString() + " where " + Id + "=" + "@" + Id + " "); 24 } 25 else 26 { 27 strTmp.AppendLine(" " + dr.Table.Columns[i].ToString() + "=" + "@" + dr.Table.Columns[i].ToString() + ","); 28 } 29 } 30 } 31 catch (System.Exception ex) 32 { 33 34 throw ex; 35 } 36 37 #endregion 38 39 40 41 42 strBuilder.AppendLine(" public bool Update" + Table + "ById(Model model)"); 43 strBuilder.AppendLine(@" { 44 "); 45 strBuilder.AppendLine(" string strSql = @\""); 46 strBuilder.AppendLine(strTmp.ToString()); 47 strBuilder.AppendLine(" \";"); 48 49 strBuilder.AppendLine(@" SqlParameter[] parameters = new SqlParameter[] 50 {"); 51 //參數類型 52 for (int i = 0; i < dr.Table.Columns.Count; i++) 53 { 54 string Type = dr.Table.Columns[i].DataType.ToString(); 55 switch (Type) 56 { 57 case "System.String": 58 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.NVarChar, 255),"); 59 break; 60 case "System.Int": 61 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Int),"); 62 break; 63 case "System.DateTime": 64 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.DateTime),"); 65 break; 66 case "System.Decimal": 67 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.Decimal),"); 68 break; 69 default: 70 strBuilder.AppendLine(" new SqlParameter(\"" + "@" + dr.Table.Columns[i] + "\", SqlDbType.NVarChar, 255),"); 71 break; 72 } 73 } 74 strBuilder.AppendLine(@" };"); 75 76 for (int i = 0; i < dr.Table.Columns.Count; i++) 77 { 78 strBuilder.AppendLine(" parameters[" + i + "].Value =" + "model." + dr.Table.Columns[i] + ";"); 79 } 80 81 strBuilder.AppendLine(@" 82 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString)) 83 { 84 conn.Open(); 85 using (SqlTransaction trans = conn.BeginTransaction()) 86 { 87 try 88 { 89 int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters); 90 if (i > 0) 91 { 92 trans.Commit(); 93 return i > 0; 94 } 95 else 96 { 97 trans.Rollback(); 98 return false; 99 } 100 } 101 catch (System.Exception e) 102 { 103 return false; 104 trans.Rollback(); 105 throw e; 106 } 107 } 108 } 109 "); 110 strBuilder.AppendLine("}"); 111 112 #endregion 113 114 if ((bool)inputSql[5]) 115 { 116 returnstr.AppendLine(strBuilder.ToString()); 117 } 118 strBuilder = new StringBuilder(); 119 #region 生成查詢方法 120 121 strBuilder.AppendLine(" public DataTable GetDataBy" + Table + "(Model model , int pageNo, int pageSize, ref int iRecordCount)"); 122 strBuilder.AppendLine(@" { "); 123 strTmp = new StringBuilder(); 124 strTmp.AppendLine("WITH temp AS ( SELECT rn = ROW_NUMBER() OVER (ORDER BY " + Id + " desc), *FROM " + Table + " WHERE 1=1 {0} )"); 125 strTmp.AppendLine("SELECT *,rc=(select count(1) from temp) FROM temp WHERE rn BETWEEN {1} AND {2}"); 126 127 strBuilder.AppendLine(" List<SqlParameter> parameters = new List<SqlParameter>();"); 128 strBuilder.AppendLine(" StringBuilder sqlWhere = new StringBuilder();"); 129 for (int i = 0; i < dr.Table.Columns.Count; i++) 130 { 131 strBuilder.AppendLine(" if (!string.IsNullOrEmpty(model." + dr.Table.Columns[i].ToString() + ".ToString())) "); 132 strBuilder.AppendLine(" {"); 133 strBuilder.AppendLine(" sqlWhere.Append(\" AND " + dr.Table.Columns[i].ToString() + "=@" + dr.Table.Columns[i].ToString() + "\");"); 134 strBuilder.AppendLine(" parameters.Add(new SqlParameter(\"@" + dr.Table.Columns[i].ToString() + "\", SqlDbType.NVarChar, 255) { SqlValue = model." + dr.Table.Columns[i].ToString() + " });"); 135 strBuilder.AppendLine(" } "); 136 } 137 strBuilder.AppendLine(" string strSql = string.Format(@\""); 138 strBuilder.AppendLine(strTmp.ToString()); 139 strBuilder.AppendLine(" \" ,sqlWhere.ToString(), (pageNo - 1) * pageSize + 1, pageNo * pageSize);"); 140 141 strBuilder.AppendLine(@" 142 143 DataTable dt = SqlHelper.Query(strSql, parameters.ToArray()).Tables[0]; 144 if (dt!=null) 145 {"); 146 strBuilder.AppendLine(" iRecordCount = int.Parse(dt.Rows[0][\"" + "rc" + "\"].ToString());"); 147 strBuilder.AppendLine(@" return dt; 148 } 149 else 150 { 151 iRecordCount = 0; 152 return null; 153 } 154 } "); 155 156 #endregion 157 158 if ((bool)inputSql[6]) 159 { 160 returnstr.AppendLine(strBuilder.ToString()); 161 } 162 strBuilder = new StringBuilder(); 163 #region 生成刪除的方法 164 165 strBuilder.AppendLine(" public bool Delete" + Table + "(string " + Id + ")"); 166 strBuilder.AppendLine(" {"); 167 strBuilder.AppendLine(" List<SqlParameter> parameters = new List<SqlParameter>();"); 168 strTmp = new StringBuilder(); 169 strTmp.AppendLine("DELETE " + Table + " WHERE " + Id + "=" + Id + ""); 170 strBuilder.AppendLine(" string strSql = string.Format(@\""); 171 strBuilder.AppendLine(strTmp.ToString()); 172 strBuilder.AppendLine(" \";"); 173 strBuilder.AppendLine(" int rowAffect =SqlHelper.Query(strSql, parameters.ToArray()).ToInt();;"); 174 strBuilder.AppendLine(" return rowAffect > 0 ? true : false;"); 175 strBuilder.AppendLine(" }"); 176 177 #endregion 178 179 if ((bool)inputSql[7]) 180 { 181 returnstr.AppendLine(strBuilder.ToString()); 182 } 183 strBuilder = new StringBuilder();
if ((bool)inputSql[7])主要是對控件值得判斷,是否勾選上,也就是是否須要生成改方法。導出的方法主要在公司已經封裝好的代碼上提取重複代碼的,平時咱們在作功能的時候只須要寫這些代碼便可。
1 strBuilder.AppendLine(@" protected void btnExcel_Click(object sender, System.EventArgs e) 2 { 3 int intPageNo = 1; 4 int intPageSize = 65535; 5 int recordCount = 0; 6 DataTable dt = GetUnAuthorizeAgreePassedDT( Model model intPageNo, intPageSize, out recordCount); "); 7 strBuilder.AppendLine(" string strFileName = \"" + "導出Excel" + "\" + System.DateTime.Now.ToString(\" " + "yyyyMMddHHmmss" + "\");"); 8 strBuilder.AppendLine(@" ExcelUtility excelUtil = new ExcelUtility(this, strFileName); 9 List<ExcelHeader> headerS = new List<ExcelHeader>() { "); 10 11 for (int i = 0; i < dr.Table.Columns.Count; i++) 12 { 13 string Type = dr.Table.Columns[i].DataType.ToString(); 14 switch (Type) 15 { 16 case "System.DateTime": 17 strBuilder.AppendLine(" new ExcelHeader() { Name = \"字段名稱自行補全\", DataType = EnumColumnDataType.日期, Width = 15 },"); 18 break; 19 default: 20 strBuilder.AppendLine(" new ExcelHeader() { Name = \"字段名稱自行補全\", DataType = EnumColumnDataType.文本, Width = 15 },"); 21 break; 22 } 23 } 24 strBuilder.AppendLine(@" }; 25 excelUtil.CreateHeader(headerS); 26 if (dt != null && dt.Rows.Count > 0) 27 { 28 foreach (DataRow dr in dt.Rows) 29 { 30 List<string> dataVals = new List<string>() { "); 31 32 33 for (int i = 0; i < dr.Table.Columns.Count; i++) 34 { 35 strBuilder.AppendLine(" dr[\" " + dr.Table.Columns[i] + "\"].ToString() "); 36 } 37 38 strBuilder.AppendLine(@" }; 39 excelUtil.CreateItemRow(dataVals); 40 } 41 } 42 excelUtil.Export(); 43 } 44 "); 45 #endregion
另外作了幾個功能,可是不是很好用,感興趣的朋友能夠去下載源碼看一下。
github地址:https://github.com/Jimmey-Jiang/JWorkHelper
而後看一下生成的代碼展現:
1 public class Model 2 { 3 4 private string _Team_code; 5 public string Team_code 6 { 7 get { return _Team_code; } 8 set { _Team_code = value; } 9 } 10 private string _Team_name; 11 public string Team_name 12 { 13 get { return _Team_name; } 14 set { _Team_name = value; } 15 } 16 private string _Team_status; 17 public string Team_status 18 { 19 get { return _Team_status; } 20 set { _Team_status = value; } 21 } 22 private string _Team_user; 23 public string Team_user 24 { 25 get { return _Team_user; } 26 set { _Team_user = value; } 27 } 28 private System.DateTime _Team_date; 29 public System.DateTime Team_date 30 { 31 get { return _Team_date; } 32 set { _Team_date = value; } 33 } 34 35 } 36 37 38 public bool InsertTeam_(Model model) 39 { 40 41 string strSql = @" 42 INSERT Team_( 43 Team_code, 44 Team_name, 45 Team_status, 46 Team_user, 47 Team_date) 48 VALUES ( 49 @Team_code, 50 @Team_name, 51 @Team_status, 52 @Team_user, 53 @Team_date) 54 55 "; 56 SqlParameter[] parameters = new SqlParameter[] 57 { 58 new SqlParameter("@Team_code", SqlDbType.NVarChar, 255), 59 new SqlParameter("@Team_name", SqlDbType.NVarChar, 255), 60 new SqlParameter("@Team_status", SqlDbType.NVarChar, 255), 61 new SqlParameter("@Team_user", SqlDbType.NVarChar, 255), 62 new SqlParameter("@Team_date", SqlDbType.DateTime), 63 }; 64 parameters[0].Value = model.Team_code; 65 parameters[1].Value = model.Team_name; 66 parameters[2].Value = model.Team_status; 67 parameters[3].Value = model.Team_user; 68 parameters[4].Value = model.Team_date; 69 70 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString)) 71 { 72 conn.Open(); 73 using (SqlTransaction trans = conn.BeginTransaction()) 74 { 75 try 76 { 77 int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters); 78 if (i > 0) 79 { 80 trans.Commit(); 81 return i > 0; 82 } 83 else 84 { 85 trans.Rollback(); 86 return false; 87 } 88 } 89 catch (System.Exception e) 90 { 91 return false; 92 trans.Rollback(); 93 throw e; 94 } 95 } 96 } 97 98 } 99 100 public bool UpdateTeam_ById(Model model) 101 { 102 103 string strSql = @" 104 Update Team_ SET 105 Team_code=@Team_code, 106 Team_name=@Team_name, 107 Team_status=@Team_status, 108 Team_user=@Team_user, 109 Team_date=@Team_date where Team_code=@Team_code 110 111 "; 112 SqlParameter[] parameters = new SqlParameter[] 113 { 114 new SqlParameter("@Team_code", SqlDbType.NVarChar, 255), 115 new SqlParameter("@Team_name", SqlDbType.NVarChar, 255), 116 new SqlParameter("@Team_status", SqlDbType.NVarChar, 255), 117 new SqlParameter("@Team_user", SqlDbType.NVarChar, 255), 118 new SqlParameter("@Team_date", SqlDbType.DateTime), 119 }; 120 parameters[0].Value = model.Team_code; 121 parameters[1].Value = model.Team_name; 122 parameters[2].Value = model.Team_status; 123 parameters[3].Value = model.Team_user; 124 parameters[4].Value = model.Team_date; 125 126 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString)) 127 { 128 conn.Open(); 129 using (SqlTransaction trans = conn.BeginTransaction()) 130 { 131 try 132 { 133 int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters); 134 if (i > 0) 135 { 136 trans.Commit(); 137 return i > 0; 138 } 139 else 140 { 141 trans.Rollback(); 142 return false; 143 } 144 } 145 catch (System.Exception e) 146 { 147 return false; 148 trans.Rollback(); 149 throw e; 150 } 151 } 152 } 153 154 } 155 156 public DataTable GetDataByTeam_(Model model, int pageNo, int pageSize, ref int iRecordCount) 157 { 158 List<SqlParameter> parameters = new List<SqlParameter>(); 159 StringBuilder sqlWhere = new StringBuilder(); 160 if (!string.IsNullOrEmpty(model.Team_code.ToString())) 161 { 162 sqlWhere.Append(" AND Team_code=@Team_code"); 163 parameters.Add(new SqlParameter("@Team_code", SqlDbType.NVarChar, 255) { SqlValue = model.Team_code }); 164 } 165 if (!string.IsNullOrEmpty(model.Team_name.ToString())) 166 { 167 sqlWhere.Append(" AND Team_name=@Team_name"); 168 parameters.Add(new SqlParameter("@Team_name", SqlDbType.NVarChar, 255) { SqlValue = model.Team_name }); 169 } 170 if (!string.IsNullOrEmpty(model.Team_status.ToString())) 171 { 172 sqlWhere.Append(" AND Team_status=@Team_status"); 173 parameters.Add(new SqlParameter("@Team_status", SqlDbType.NVarChar, 255) { SqlValue = model.Team_status }); 174 } 175 if (!string.IsNullOrEmpty(model.Team_user.ToString())) 176 { 177 sqlWhere.Append(" AND Team_user=@Team_user"); 178 parameters.Add(new SqlParameter("@Team_user", SqlDbType.NVarChar, 255) { SqlValue = model.Team_user }); 179 } 180 if (!string.IsNullOrEmpty(model.Team_date.ToString())) 181 { 182 sqlWhere.Append(" AND Team_date=@Team_date"); 183 parameters.Add(new SqlParameter("@Team_date", SqlDbType.NVarChar, 255) { SqlValue = model.Team_date }); 184 } 185 string strSql = string.Format(@" 186 WITH temp AS ( SELECT rn = ROW_NUMBER() OVER (ORDER BY Team_code desc), *FROM Team_ WHERE 1=1 {0} ) 187 SELECT *,rc=(select count(1) from temp) FROM temp WHERE rn BETWEEN {1} AND {2} 188 189 ", sqlWhere.ToString(), (pageNo - 1) * pageSize + 1, pageNo * pageSize); 190 191 192 DataTable dt = SqlHelper.Query(strSql, parameters.ToArray()).Tables[0]; 193 if (dt != null) 194 { 195 iRecordCount = int.Parse(dt.Rows[0]["rc"].ToString()); 196 return dt; 197 } 198 else 199 { 200 iRecordCount = 0; 201 return null; 202 } 203 } 204 205 public bool DeleteTeam_(string Team_code) 206 { 207 List<SqlParameter> parameters = new List<SqlParameter>(); 208 string strSql = string.Format(@" 209 DELETE Team_ WHERE Team_code=Team_code 210 211 "; 212 int rowAffect =SqlHelper.Query(strSql, parameters.ToArray()).ToInt();; 213 return rowAffect > 0 ? true : false; 214 } 215 216 protected void btnExcel_Click(object sender, System.EventArgs e) 217 { 218 int intPageNo = 1; 219 int intPageSize = 65535; 220 int recordCount = 0; 221 DataTable dt = GetUnAuthorizeAgreePassedDT( Model model intPageNo, intPageSize, out recordCount); 222 string strFileName = "導出Excel" + System.DateTime.Now.ToString(" yyyyMMddHHmmss"); 223 ExcelUtility excelUtil = new ExcelUtility(this, strFileName); 224 List<ExcelHeader> headerS = new List<ExcelHeader>() { 225 new ExcelHeader() { Name = "字段名稱自行補全", DataType = EnumColumnDataType.文本, Width = 15 }, 226 new ExcelHeader() { Name = "字段名稱自行補全", DataType = EnumColumnDataType.文本, Width = 15 }, 227 new ExcelHeader() { Name = "字段名稱自行補全", DataType = EnumColumnDataType.文本, Width = 15 }, 228 new ExcelHeader() { Name = "字段名稱自行補全", DataType = EnumColumnDataType.文本, Width = 15 }, 229 new ExcelHeader() { Name = "字段名稱自行補全", DataType = EnumColumnDataType.日期, Width = 15 }, 230 }; 231 excelUtil.CreateHeader(headerS); 232 if (dt != null && dt.Rows.Count > 0) 233 { 234 foreach (DataRow dr in dt.Rows) 235 { 236 List<string> dataVals = new List<string>() { 237 dr[" Team_code"].ToString() 238 dr[" Team_name"].ToString() 239 dr[" Team_status"].ToString() 240 dr[" Team_user"].ToString() 241 dr[" Team_date"].ToString() 242 }; 243 excelUtil.CreateItemRow(dataVals); 244 } 245 } 246 excelUtil.Export(); 247 }
有人說這個版本太麻煩,我就作了T4版本