回《【開源】EnterpriseFrameWork框架系列文章索引》 javascript
EFW框架源代碼下載:http://pan.baidu.com/s/1qWJjo3Ucss
EFW框架中的WebController就是解決JqueryEasyUI與邏輯層的交互,之間的數據是經過Json字符串來傳遞;值得注意的是WebController的代碼必定不要和EFWWeb項目放在一塊兒,你能夠單獨建一個項目類庫,也能夠和邏輯層項目放一塊兒;在EFWWeb項目不要編寫任何C#代碼,這個在前面的文章中就提過,可讓你的Web項目發佈更省事一點,免去編譯EFWWeb項目的痛苦;html
控制器能夠調用分層一下的全部代碼,包括ObjectModel、Dao、Entity,甚至能夠直接用oleDb編寫SQL語句操做數據庫;還有控制器與控制器之間是不能存在任何依賴關係的;java
本章主要內容經過解讀框架源代碼來學習WebController是怎麼實現的,以及思考這樣實現會給咱們開發帶來什麼好處;jquery
本文要點:數據庫
1.如何使用Web控制器json
2.Web控制器的設計思路數組
3.Web控制器基類AbstractController的實現session
4.Web控制器的自定義標籤WebControllerAttribute和WebMethodAttributeapp
5.基於JqueryEasyUI封裝的Web控制器的實現
6.Web經常使用組件封裝成控制器
Web控制器源代碼目錄
EFW框架控制器設計圖
講解EFW框架中的Web控制器的使用以前先看看傳統的Web系統是如何開發的;
如上圖,傳統方式一個aspx文件對應一個cs文件,開發方式跟Winform桌面程序相同,都是事件響應的模式;咱們再看看EFW框架中是如何開放的;
如上圖,有兩個項目EFWWeb項目和Books項目,EFWWeb項目裏面只有界面HTML代碼和JS代碼,後臺CS代碼在另外的Books項目中;接着看裏面的詳細代碼,界面層是如何調用後臺的Web控制器的;
Book.aspx文件
1 <%@ Page Language="C#" %> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head runat="server"> 4 <title>書籍管理</title> 5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 6 <link rel="stylesheet" type="text/css" href="../../../WebPlugin/jquery-easyui-1.3.4/themes/default/easyui.css"/> 7 <link rel="stylesheet" type="text/css" href="../../../WebPlugin/jquery-easyui-1.3.4/themes/icon.css"/> 8 <script type="text/javascript" src="../../../WebPlugin/jquery-1.8.0.min.js"></script> 9 <script type="text/javascript" src="../../../WebPlugin/jquery-easyui-1.3.4/jquery.easyui.min.js"></script> 10 <script type="text/javascript" src="../../../WebPlugin/jquery-easyui-1.3.4/locale/easyui-lang-zh_CN.js"></script> 11 <script src="../../../WebPlugin/JQueryCommon2.0.js" type="text/javascript"></script> 12 <script src="Book.js" type="text/javascript"></script> 13 </head> 14 <body class="easyui-layout"> 15 <div region="center" style="overflow:hidden;"> 16 <div id="grid-tool"> 17 <table cellpadding="0" cellspacing="0" style="width:100%"> 18 <tr> 19 <td style="padding-left:2px"> 20 <a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-add" onclick="btn_add();">新增</a> 21 <a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-edit" onclick="btn_alter();">修改</a> 22 </td> 23 <td style="text-align:right;padding-right:2px"> 24 <input class="easyui-searchbox" data-options="prompt:'請輸入書籍名稱'" style="width:250px"></input> 25 </td> 26 </tr> 27 </table> 28 </div> 29 <table id="bookGird" class="easyui-datagrid" toolbar="#grid-tool" fit="true" border="false" singleSelect="true"> 30 <thead> 31 <tr> 32 <th field="Id" width="100">序號</th> 33 <th field="BookName" width="80">書籍名稱</th> 34 <th field="BuyPrice" width="120">購書價格</th> 35 <th field="BuyDate" width="200">購書時間</th> 36 <th field="Flag" width="80">是否丟失</th> 37 </tr> 38 </thead> 39 </table> 40 </div> 41 42 <%--彈出窗界面--%> 43 <div id="dialog-book" title="新增書籍" class="easyui-dialog" icon="icon-save" style="background:#fafafa;padding:10px;width:350px;height:250px;" buttons="#dlg-buttons1" resizable="true" modal="true"> 44 <form id="bookform" method="post"> 45 <table> 46 <tr> 47 <td><label>書籍名稱:</label></td> 48 <td><input name="BookName" class="easyui-validatebox" style="width:200px;" type="text" required="true"></input></td> 49 </tr> 50 <tr> 51 <td><label>購書價格:</label></td> 52 <td><input name="BuyPrice" class="easyui-validatebox" style="width:200px;" type="text" required="true"></input></td> 53 </tr> 54 <tr> 55 <td><label>購書日期:</label></td> 56 <td><input name="BuyDate" class="easyui-datebox" style="width:200px;" type="text" required="true"></input></td> 57 </tr> 58 <tr> 59 <td><label>是否丟失:</label></td> 60 <td><input id="_flag" type="checkbox"/></td> 61 </tr> 62 </table> 63 <input id="book_id" type="hidden" name="Id" ></input> 64 <input id="book_flag" type="hidden" name="Flag" ></input> 65 </form> 66 </div> 67 <div id="dlg-buttons1"> 68 <a href="#" class="easyui-linkbutton" onclick="btn_save();">肯定</a> 69 <a href="#" class="easyui-linkbutton" onclick="$('#dialog-book').dialog('close');">取消</a> 70 </div> 71 </body> 72 </html>
Book.js文件
1 //初始化入口 2 $(function() { 3 $('#dialog-book').dialog('close'); 4 //加載網格數據 5 $('#bookGird').datagrid('options').url = 'Controller.aspx?controller=bookController&method=SearchBook&schar=&flag=0'; 6 //$('#bookGird').datagrid('reload'); 7 }); 8 //添加 9 function btn_add(){ 10 $('#dialog-book').dialog({ title: '新增書籍' }); 11 $("#bookform").form('clear'); 12 $("#book_id").val(0); 13 $("#book_flag").val(0); 14 $("#_flag").removeAttr("checked"); 15 } 16 //修改 17 function btn_alter(){ 18 $('#dialog-book').dialog({ title: '修改書籍' }); 19 var selected = $('#bookGird').datagrid('getSelected'); 20 if (selected) { 21 $("#bookform").form("load", selected); 22 23 if (selected.Flag == "1") 24 $("#_flag").attr("checked", "true"); 25 else 26 $("#_flag").removeAttr("checked"); 27 } 28 } 29 //保存 30 function btn_save() { 31 var ckval=$("#_flag").attr("checked")=="checked"?1:0; 32 $('#book_flag').val(ckval); 33 formSubmit('#bookform', 'Controller.aspx?controller=bookController&method=SaveBook', function() { 34 $('#dialog-book').dialog('close'); 35 $('#bookGird').datagrid('reload'); 36 }); 37 }
bookController.cs文件
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using EFWCoreLib.WebFrame.Controller; 6 using Books.Entity; 7 using Books.Dao; 8 using System.Data; 9 10 namespace Books.WebController 11 { 12 [WebController] 13 public class bookController : EFWCoreLib.WebFrame.Controller.AbstractJqueryController 14 { 15 [WebMethod] 16 public void SaveBook() 17 { 18 Book book = GetModel<Book>(); 19 book.save(); 20 TxtJson = ReturnSuccess("保存書籍成功!"); 21 } 22 [WebMethod] 23 public void SearchBook() 24 { 25 string schar = ParamsData["schar"]; 26 int flag = Convert.ToInt32(ParamsData["flag"]); 27 28 IBookDao bdao = NewDao<IBookDao>(); 29 DataTable dt = bdao.GetBooks(schar, flag); 30 TxtJson = ToGridJson(dt); 31 } 32 33 public void TestEntity() 34 { 35 //建立實體對象實例 36 Book book = NewObject<Book>(); 37 38 //1.根據id獲取一條記錄 39 book= book.getmodel(1) as Book; 40 41 //2.修改或者新增一條記錄 42 book.BookName = "人月神話"; 43 book.BuyPrice = 23; 44 book.BuyDate = Convert.ToDateTime("2014-01-01"); 45 book.save(); 46 47 //3.根據id刪除表數據 48 book.delete(1); 49 50 //4.獲取表全部記錄轉換爲List實體對象 51 List<Book> booklist = book.getlist<Book>(); 52 53 //5.獲取表全部記錄轉換爲DataTable 54 DataTable dt = book.gettable(); 55 } 56 } 57 }
咱們先說Book.aspx文件,裏面的代碼是基於JqueryEasyUI框架編寫的,實現了一個網格數據,上面有添加、修改工具欄按鈕,點擊按鈕彈出維護界面;這些代碼沒有什麼好講得,等你熟悉JqueryEasyUI的相關控件後,就能很快的開發各類複雜界面;咱們接着看Book.js腳本文件,是採用Jquery的方式編寫javascript腳本;
界面加載後就會執行這段代碼,實現網格的數據顯示,給datagrid控件設置url地址就會自動向後臺發送Ajax請求,請求返回的Json數據datagrid控件解析後顯示在界面;重點說一下這個url的參數意思,這是通日後臺控制器的橋樑;controller指定後臺控制器的名稱bookController,method指定控制器內的方法名SearchBook,注意名稱的大小寫別搞錯了;
總結一下,Ajax向後臺發送請求的URL必須採用Controller.aspx?controller=XXX&method=XXX這種格式,調試的時候控制器中打了斷點沒有進來,首先查看指定的控制器名稱和方法名稱是否正確;
上文中舉的實例是利用JqueryEasyUI開發的,若是個人項目不想要JqueryEasyUI,用更專業的Extjs或其餘界面框架怎麼辦,EFW框架設計的時候充分的考慮到了這一點,咱們看最上的「EFW框架控制器設計圖」,bookController繼承的是AbstractJqueryController對象,AbstractJqueryController對象又繼承的AbstractController對象,AbstractController是Web控制器的核心基類,AbstractJqueryController就是針對JqueryEasyUI框架實現的控制器,咱們要實現Extjs框架,就只要想只要像AbstractJqueryController同樣編寫一個適合Extjs框架的控制器基類,咱們的bookController繼承它就好了;
還有好比咱們還開發手機上運行的網頁程序,一樣能夠用這種方式來實現,下一個版本會把jquery.mobile引入到EFW框架中;
這裏講解一下Web控制器的核心基類AbstractController的代碼實現;
AbstractController文件
1 public abstract class AbstractController:AbstractBusines 2 { 3 public AbstractDatabase oleDb 4 { 5 get 6 { 7 return _oleDb; 8 } 9 } 10 11 public SysLoginRight GetSysLoginRight 12 { 13 get 14 { 15 if (sessionData != null && sessionData.ContainsKey("RoleUser")) 16 { 17 return (SysLoginRight)sessionData["RoleUser"]; 18 } 19 else 20 { 21 return new SysLoginRight(); 22 } 23 } 24 } 25 26 public HttpContext context { get; set; } 27 28 private System.Collections.Generic.Dictionary<string, Object> _sessionData; 29 /// <summary> 30 /// Session數據傳入後臺 31 /// </summary> 32 public System.Collections.Generic.Dictionary<string, Object> sessionData 33 { 34 get 35 { 36 return _sessionData; 37 } 38 set 39 { 40 _sessionData = value; 41 } 42 } 43 44 private System.Collections.Generic.Dictionary<string, Object> _putOutData; 45 /// <summary> 46 /// 後臺傳出數據到Session數據 47 /// </summary> 48 public System.Collections.Generic.Dictionary<string, Object> PutOutData 49 { 50 get 51 { 52 return _putOutData; 53 } 54 set 55 { 56 _putOutData = value; 57 } 58 } 59 60 private List<string> _clearKey; 61 /// <summary> 62 /// 清除Session的數據 63 /// </summary> 64 public List<string> ClearKey 65 { 66 get { return _clearKey; } 67 set { _clearKey = value; } 68 } 69 70 private System.Collections.Generic.Dictionary<string, string> _paramsData; 71 /// <summary> 72 /// Url參數傳遞數據 73 /// </summary> 74 public System.Collections.Generic.Dictionary<string, string> ParamsData 75 { 76 get { return _paramsData; } 77 set { _paramsData = value; } 78 } 79 80 private System.Collections.Generic.Dictionary<string, string> _formData; 81 /// <summary> 82 /// Form提交的數據 83 /// </summary> 84 public System.Collections.Generic.Dictionary<string, string> FormData 85 { 86 get { return _formData; } 87 set { _formData = value; } 88 } 89 90 91 }
AbstractController基類封裝了三方面的內容:
1)數據庫操做對象,這個咱們以前第十章也講過爲何要在控制器開放oleDb,這也是爲了讓框架分層使用起來更靈活,且兼容性強;
2)系統登陸用戶信息SysLoginRight,此屬性封裝了用戶登陸後的姓名、部門、機構等信息;這樣在控制器中查詢當前登陸用戶的數據時候會很簡單;
3)網頁中的數據,如請求參數、Session數據、表單數據等;從界面傳進來的數據均可以從中獲取;
爲了能讓系統根據url中控制器名稱和方法名稱找到對應的代碼執行,就像Webservice服務同樣須要對Web控制器的類名和方法名上加上上面兩個自定義標籤;
WebControllerAttribute文件
1 [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] 2 public class WebControllerAttribute : Attribute 3 { 4 string _memo; 5 public string Memo 6 { 7 get { return _memo; } 8 set { _memo = value; } 9 } 10 }
WebMethodAttribute文件
1 [AttributeUsageAttribute(AttributeTargets.Method, Inherited = true, AllowMultiple = false)] 2 public class WebMethodAttribute : Attribute 3 { 4 private string _openDBNames; 5 /// <summary> 6 /// 打開數據庫,中間用,號隔開 7 /// </summary> 8 public string OpenDBKeys 9 { 10 get { return _openDBNames; } 11 set { _openDBNames = value; } 12 } 13 14 string _memo; 15 public string Memo 16 { 17 get { return _memo; } 18 set { _memo = value; } 19 } 20 }
值得注意的就是,控制器的名稱在整個系統中不能重複,若是出現相同名稱的控制器,系統就可能沒法正確調用對應的控制器;
接下來說解一下基於JqueryEasyUI封裝的AbstractJqueryController的代碼是如何實現的;AbstractJqueryController類繼承了IToJqueryEasyUIJson接口,IToJqueryEasyUIJson接口就是提取出了把數據對象轉換爲符合JqueryEasyUI控件的Json字符串的方法;如:datagrid控件、Tree控件、treegrid控件等
IToJqueryEasyUIJson接口文件
1 /// <summary> 2 /// 對象轉與JqueryEasyUI匹配的Json格式 3 /// </summary> 4 public interface IToJqueryEasyUIJson 5 { 6 7 string TxtJson { get; set; } 8 string FilterJson(string json);//過濾json字符串中全部特殊字符 9 10 string ToJson(object model); 11 string ToJson(System.Data.DataTable dt);//轉json字符串,combobox控件用此方法 12 string ToJson(Hashtable hash); 13 14 string ToGridJson(string tojson, int totalCount); 15 string ToGridJson(string rowsjson, string footjson, int totalCount); 16 17 string ToGridJson(System.Data.DataTable dt); 18 string ToGridJson(System.Data.DataTable dt, int totalCount); 19 string ToGridJson(System.Data.DataTable dt, int totalCount, System.Collections.Hashtable[] footers); 20 21 22 string ToGridJson(System.Collections.IList list); 23 string ToGridJson(System.Collections.IList list, int totalCount); 24 string ToGridJson(System.Collections.IList list, int totalCount, System.Collections.Hashtable[] footers); 25 26 string ToFloorJson(List<floorclass> floor); 27 string ToFloorJson(List<floorclass> floor, int totalCount); 28 29 string ToTreeJson(List<treeNode> list); 30 31 string ToTreeGridJson(List<treeNodeGrid> list); 32 string ToTreeGridJson(List<treeNodeGrid> list, System.Collections.Hashtable[] footers); 33 string ToTreeGridJson(DataTable dt, string IdName, string _parentIdName); 34 string ToTreeGridJson(DataTable dt, string IdName, string _parentIdName, System.Collections.Hashtable[] footers); 35 string ToTreeGridJson(string rowsjson, string footjson, int totalCount); 36 37 T GetModel<T>();//從form表單提交的數據轉爲實體對象 38 T GetModel<T>(T model);//從form表單提交的數據賦值給model 39 40 41 DataTable ToDataTable(string json); 42 List<T> ToList<T>(string json); 43 44 string ReturnSuccess(); 45 string ReturnSuccess(string info); 46 string ReturnSuccess(string info, string data); 47 string ReturnError(string errmsg); 48 49 string ToView();//回退 50 string ToView(string info);//提示後再回退 51 string ToView(string info, string Url);//提示後調整到執行頁面 52 53 54 55 }
AbstractJqueryController文件
1 /// <summary> 2 /// 基於JqueryEasyUI框架的Web控制器基類 3 /// </summary> 4 public abstract class AbstractJqueryController : AbstractController, IToJqueryEasyUIJson 5 { 6 private string _txtJson; 7 8 public string TxtJson 9 { 10 get { return _txtJson; } 11 set { _txtJson = value; } 12 } 13 14 #region IController2 成員 15 16 public string FilterJson(string json) 17 { 18 throw new NotImplementedException(); 19 } 20 21 public string ToJson(object model) 22 { 23 string value = JavaScriptConvert.SerializeObject(model, new AspNetDateTimeConverter()); 24 return value; 25 } 26 27 public string ToJson(System.Data.DataTable dt) 28 { 29 string value = JavaScriptConvert.SerializeObject(dt); 30 return value; 31 } 32 33 public string ToJson(System.Collections.Hashtable hash) 34 { 35 string value = JavaScriptConvert.SerializeObject(hash, new AspNetDateTimeConverter()); 36 return value; 37 } 38 39 public string ToGridJson(string rowsjson, int totalCount) 40 { 41 return ToGridJson(rowsjson, null, totalCount); 42 } 43 44 public string ToGridJson(string rowsjson, string footjson, int totalCount) 45 { 46 if (footjson == null) 47 return "{\"total\":" + totalCount + ",\"rows\":" + rowsjson + "}"; 48 else 49 return "{\"total\":" + totalCount + ",\"rows\":" + rowsjson + ",\"footer\":" + footjson + "}"; 50 } 51 52 public string ToGridJson(System.Data.DataTable dt) 53 { 54 return ToGridJson(dt, -1, null); 55 } 56 57 public string ToGridJson(System.Data.DataTable dt, int totalCount) 58 { 59 return ToGridJson(dt, totalCount, null); 60 } 61 62 public string ToGridJson(System.Data.DataTable dt, int totalCount, System.Collections.Hashtable[] footers) 63 { 64 totalCount = totalCount == -1 ? dt.Rows.Count : totalCount; 65 string rowsjson = ToJson(dt); 66 string footjson = footers == null ? null : ToJson(footers); 67 return ToGridJson(rowsjson, footjson, totalCount); 68 } 69 70 public string ToGridJson(System.Collections.IList list) 71 { 72 return ToGridJson(list, -1, null); 73 } 74 75 public string ToGridJson(System.Collections.IList list, int totalCount) 76 { 77 return ToGridJson(list, totalCount, null); 78 } 79 80 public string ToGridJson(System.Collections.IList list, int totalCount, System.Collections.Hashtable[] footers) 81 { 82 totalCount = totalCount == -1 ? list.Count : totalCount; 83 string rowsjson = ToJson(list); 84 string footjson = footers == null ? null : ToJson(footers); 85 return ToGridJson(rowsjson, footjson, totalCount); 86 87 } 88 89 90 public string ToFloorJson(List<floorclass> floor) 91 { 92 return ToFloorJson(floor, floor.Count); 93 } 94 95 public string ToFloorJson(List<floorclass> floor, int totalCount) 96 { 97 string Json = "{\"total\":" + totalCount + ",\"rows\":["; 98 string str = ""; 99 for (int i = 0; i < floor.Count; i++) 100 { 101 if (str == "") 102 { 103 str += "{\"floorid\":" + floor[i].floorid + ",\"floortext\":\"" + floor[i].floortext + "\",\"room\":"; 104 } 105 else 106 { 107 str += ",{\"floorid\":" + floor[i].floorid + ",\"floortext\":\"" + floor[i].floortext + "\",\"room\":"; 108 } 109 str += JavaScriptConvert.SerializeObject(floor[i].room); 110 str += "}"; 111 } 112 Json += str; 113 Json += "]}"; 114 115 return Json; 116 } 117 118 public string ToTreeJson(List<treeNode> list) 119 { 120 JsonConverter converter = new AspNetDateTimeConverter(); 121 string value = JavaScriptConvert.SerializeObject(list, converter); 122 value = value.Replace("check", "checked"); 123 return value; 124 } 125 126 public string ToTreeGridJson(List<treeNodeGrid> list) 127 { 128 return ToTreeGridJson(list, null); 129 } 130 131 public string ToTreeGridJson(List<treeNodeGrid> list, System.Collections.Hashtable[] footers) 132 { 133 List<Hashtable> hashlist = new List<Hashtable>(); 134 for (int i = 0; i < list.Count; i++) 135 { 136 Hashtable hash = new Hashtable(); 137 hash.Add("id", list[i].id); 138 if (list[i]._parentId > 0) 139 hash.Add("_parentId", list[i]._parentId); 140 if (!string.IsNullOrEmpty(list[i].state)) 141 hash.Add("state", list[i].state); 142 if (!string.IsNullOrEmpty(list[i].iconCls)) 143 hash.Add("iconCls", list[i].iconCls); 144 if (list[i].check) 145 hash.Add("check", list[i].check); 146 if (list[i].model != null) 147 { 148 PropertyInfo[] propertys = list[i].model.GetType().GetProperties(); 149 for (int j = 0; j < propertys.Length; j++) 150 { 151 if (!hash.ContainsKey(propertys[j].Name)) 152 hash.Add(propertys[j].Name, propertys[j].GetValue(list[i].model, null)); 153 } 154 } 155 156 hashlist.Add(hash); 157 } 158 159 int totalCount = hashlist.Count; 160 string rowsjson = ToJson(hashlist); 161 string footjson = footers == null ? null : ToJson(footers); 162 return ToTreeGridJson(rowsjson, footjson, totalCount); 163 } 164 165 public string ToTreeGridJson(System.Data.DataTable dt, string IdName, string _parentIdName) 166 { 167 return ToTreeGridJson(dt, IdName, _parentIdName, null); 168 } 169 170 public string ToTreeGridJson(System.Data.DataTable dt, string IdName, string _parentIdName, System.Collections.Hashtable[] footers) 171 { 172 List<Hashtable> hashlist = new List<Hashtable>(); 173 for (int i = 0; i < dt.Rows.Count; i++) 174 { 175 Hashtable hash = new Hashtable(); 176 hash.Add("id", dt.Rows[i][IdName]); 177 if (Convert.ToInt32(dt.Rows[i][_parentIdName]) > 0) 178 hash.Add("_parentId", dt.Rows[i][_parentIdName]); 179 for (int j = 0; j < dt.Columns.Count; j++) 180 { 181 if (dt.Columns[j].ColumnName.ToLower() == IdName.ToLower()) continue; 182 if (dt.Columns[j].ColumnName.ToLower() == _parentIdName.ToLower()) continue; 183 184 hash.Add(dt.Columns[j].ColumnName, dt.Rows[i][j]); 185 } 186 hashlist.Add(hash); 187 } 188 189 int totalCount = hashlist.Count; 190 string rowsjson = ToJson(hashlist); 191 string footjson = footers == null ? null : ToJson(footers); 192 return ToTreeGridJson(rowsjson, footjson, totalCount); 193 } 194 195 public string ToTreeGridJson(string rowsjson, string footjson, int totalCount) 196 { 197 if (footjson == null) 198 return "{\"total\":" + totalCount + ",\"rows\":" + rowsjson + "}"; 199 else 200 return "{\"total\":" + totalCount + ",\"rows\":" + rowsjson + ",\"footer\":" + footjson + "}"; 201 } 202 203 public T GetModel<T>() 204 { 205 T model = NewObject<T>(); 206 return GetModel<T>(model); 207 } 208 209 public T GetModel<T>(T model) 210 { 211 System.Reflection.PropertyInfo[] propertys = model.GetType().GetProperties(); 212 for (int j = 0; j < propertys.Length; j++) 213 { 214 if (propertys[j].Name == "WorkId") break; 215 if (FormData.ContainsKey(propertys[j].Name) == true) 216 { 217 if (propertys[j].PropertyType.Equals(typeof(Int32))) 218 propertys[j].SetValue(model, Convert.ToInt32(FormData[propertys[j].Name].Trim() == "" ? "0" : FormData[propertys[j].Name]), null); 219 else if (propertys[j].PropertyType.Equals(typeof(Int64))) 220 propertys[j].SetValue(model, Convert.ToInt64(FormData[propertys[j].Name].Trim() == "" ? "0" : FormData[propertys[j].Name]), null); 221 else if (propertys[j].PropertyType.Equals(typeof(decimal))) 222 propertys[j].SetValue(model, Convert.ToDecimal(FormData[propertys[j].Name].Trim() == "" ? "0" : FormData[propertys[j].Name]), null); 223 else if (propertys[j].PropertyType.Equals(typeof(DateTime))) 224 propertys[j].SetValue(model, Convert.ToDateTime(FormData[propertys[j].Name].Trim() == "" ? DateTime.Now.ToString() : FormData[propertys[j].Name]), null); 225 else 226 propertys[j].SetValue(model, FormData[propertys[j].Name], null); 227 } 228 } 229 230 return model; 231 } 232 233 public System.Data.DataTable ToDataTable(string json) 234 { 235 throw new NotImplementedException(); 236 } 237 238 public List<T> ToList<T>(string json) 239 { 240 Newtonsoft.Json.JavaScriptArray jsonArray = (Newtonsoft.Json.JavaScriptArray)Newtonsoft.Json.JavaScriptConvert.DeserializeObject(json); 241 242 List<T> list = new List<T>(); 243 T model = NewObject<T>(); 244 245 System.Reflection.PropertyInfo[] propertys = model.GetType().GetProperties(); 246 247 for (int i = 0; i < jsonArray.Count; i++) 248 { 249 T _model = (T)((ICloneable)model).Clone(); 250 251 Newtonsoft.Json.JavaScriptObject Jobject = ((Newtonsoft.Json.JavaScriptObject)((Newtonsoft.Json.JavaScriptArray)jsonArray)[i]); 252 for (int n = 0; n < Jobject.Count; n++) 253 { 254 for (int j = 0; j < propertys.Length; j++) 255 { 256 if (propertys[j].Name == "WorkId") break; 257 if (Jobject.ToList()[n].Key.Trim().ToUpper() == propertys[j].Name.ToUpper()) 258 { 259 260 if (propertys[j].PropertyType.Equals(typeof(Int32))) 261 propertys[j].SetValue(_model, Convert.ToInt32(Jobject.ToList()[n].Value.ToString().Trim() == "" ? 0 : Jobject.ToList()[n].Value), null); 262 else if (propertys[j].PropertyType.Equals(typeof(Int64))) 263 propertys[j].SetValue(_model, Convert.ToInt64(Jobject.ToList()[n].Value.ToString().Trim() == "" ? 0 : Jobject.ToList()[n].Value), null); 264 else if (propertys[j].PropertyType.Equals(typeof(decimal))) 265 propertys[j].SetValue(_model, Convert.ToDecimal(Jobject.ToList()[n].Value.ToString().Trim() == "" ? 0 : Jobject.ToList()[n].Value), null); 266 else if (propertys[j].PropertyType.Equals(typeof(DateTime))) 267 propertys[j].SetValue(_model, Convert.ToDateTime(Jobject.ToList()[n].Value.ToString().Trim() == "" ? DateTime.Now.ToString() : Jobject.ToList()[n].Value), null); 268 else 269 propertys[j].SetValue(_model, Jobject.ToList()[n].Value.ToString(), null); 270 break; 271 } 272 } 273 } 274 list.Add(_model); 275 } 276 277 return list; 278 } 279 280 public string ReturnSuccess() 281 { 282 return ReturnSuccess(null, null); 283 } 284 285 public string ReturnSuccess(string info) 286 { 287 return ReturnSuccess(info, null); 288 } 289 290 public string ReturnSuccess(string info, string data) 291 { 292 info = info == null ? "" : info; 293 data = data == null ? "\"\"" : data; 294 return "{\"ret\":0,\"msg\":" + "\"" + info + "\"" + ",\"data\":" + data + "}"; 295 } 296 297 public string ReturnError(string errmsg) 298 { 299 return "{\"ret\":1,\"msg\":" + "\"" + errmsg + "\"" + "}"; 300 } 301 302 public string ToView() 303 { 304 return ToView(null, null); 305 } 306 307 public string ToView(string info) 308 { 309 return ToView(info, null); 310 } 311 312 public string ToView(string info, string Url) 313 { 314 StringBuilder sb = new StringBuilder(); 315 sb.Append("<script language=\"javascript\" type=\"text/javascript\">\n"); 316 if (info != null) 317 sb.Append("alert('" + info + "');\n"); 318 if (Url != null) 319 sb.Append("window.location.href='" + Url + "'\n"); 320 sb.Append("history.back();\n"); 321 sb.Append("</script>\n"); 322 return sb.ToString(); 323 } 324 325 #endregion 326 }
開發一個新界面框架的Web控制器,必定要先設計好數據轉換接口,由於到時候繼承它的全部控制器都會使用這些封裝的方法進行數據轉換,到時候再改動此接口影響的代碼就多啦;
還有就是TxtJson這個屬性,系統就是把此屬性中的數據輸出到界面上的;
爲何要再EFW框架中默認使用JqueryEasyUI了,最主要的是學習成本底,基本上花的幾個小時屬性一下Demo中的控件就會用了;還有就是它是基於Jquery開發的,因此本身也能夠再基礎上進行一些擴展開發,可以知足一些特殊的需求;剛開始項目中是用的Extjs開發,就是由於學習成本過高了,一個新手一開始根本摸不到邊,特別是設計界面與操做數據都是用JS代碼,代碼編寫得規範的還好,編寫得很差的,真的是太難看了;而我選擇JqueryeasyUI另外一點就是設計界面不用js代碼,用html標籤代碼就能夠搞定,很是方便;
Web系統中一些經常使用到的組件也封裝成獨立的控制器方便使用:
1)調試控制器DebugController
1 /// <summary> 2 /// 控制器調試 3 /// </summary> 4 [WebController] 5 public class DebugController : AbstractController 6 { 7 private List<Hashtable> getHashList(string[] str) 8 { 9 List<Hashtable> hashlist = new List<Hashtable>(); 10 for (int i = 0; i < str.Length; i++) 11 { 12 Hashtable hash = new Hashtable(); 13 hash.Add("code", i); 14 hash.Add("Name", str[i]); 15 hashlist.Add(hash); 16 } 17 return hashlist; 18 } 19 20 [WebMethod] 21 public void GetControllerClassNameData() 22 { 23 List<Cmd_Controller> cmd = (List<Cmd_Controller>)AppGlobal.cache.GetData("cmdWebController"); 24 List<string> classlist =new List<string>(); 25 for (int i = 0; i < cmd.Count; i++) 26 { 27 classlist.Add(cmd[i].controllerName); 28 } 29 context.Response.Charset = "UTF-8"; 30 //把數據輸出到頁面 31 context.Response.Write(JavaScriptConvert.SerializeObject(getHashList(classlist.ToArray()))); 32 } 33 34 [WebMethod] 35 public void GetControllerMethodNameData() 36 { 37 List<string> methodlist = new List<string>(); 38 39 string ClassName = ParamsData["ClassName"]; 40 List<Cmd_Controller> cmd = (List<Cmd_Controller>)AppGlobal.cache.GetData("cmdWebController"); 41 Cmd_Controller cmdC = cmd.Find(x => x.controllerName == ClassName); 42 if (cmdC != null) 43 { 44 for (int i = 0; i < cmdC.cmdMethod.Count; i++) 45 { 46 methodlist.Add(cmdC.cmdMethod[i].methodName); 47 } 48 } 49 50 context.Response.Charset = "UTF-8"; 51 //把數據輸出到頁面 52 context.Response.Write(JavaScriptConvert.SerializeObject(getHashList(methodlist.ToArray()))); 53 } 54 }
2)登陸驗證碼ImageUniqueCode
1 /// <summary> 2 /// 登陸驗證碼控制器 3 /// </summary> 4 public class ImageUniqueCode : AbstractController 5 { 6 public static readonly string ImageUniqueCode_Session = "ImageUniqueCode"; 7 8 public void CreateCode() 9 { 10 context.Response.ContentType = "image/gif"; 11 //創建Bitmap對象,繪圖 12 Bitmap basemap = new Bitmap(160, 60); 13 Graphics graph = Graphics.FromImage(basemap); 14 graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 160, 60); 15 Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel); 16 Random r = new Random(); 17 string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789"; 18 string letter; 19 StringBuilder s = new StringBuilder(); 20 21 //添加隨機字符 22 for (int x = 0; x < 4; x++) 23 { 24 letter = letters.Substring(r.Next(0, letters.Length - 1), 1); 25 s.Append(letter); 26 graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15)); 27 } 28 29 //混淆背景 30 Pen linePen = new Pen(new SolidBrush(Color.Black), 2); 31 for (int x = 0; x < 6; x++) 32 graph.DrawLine(linePen, new Point(r.Next(0, 159), r.Next(0, 59)), new Point(r.Next(0, 159), r.Next(0, 59))); 33 34 //將圖片保存到輸出流中 35 basemap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif); 36 context.Session[ImageUniqueCode_Session] = s.ToString(); 37 } 38 39 public void CreateNumCode() 40 { 41 context.Response.ContentType = "image/gif"; 42 //創建Bitmap對象,繪圖 43 Bitmap basemap = new Bitmap(160, 60); 44 Graphics graph = Graphics.FromImage(basemap); 45 graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 160, 60); 46 Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel); 47 Random r = new Random(); 48 string letters = "0123456789"; 49 string letter; 50 StringBuilder s = new StringBuilder(); 51 52 //添加隨機字符 53 for (int x = 0; x < 4; x++) 54 { 55 letter = letters.Substring(r.Next(0, letters.Length - 1), 1); 56 s.Append(letter); 57 graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15)); 58 } 59 60 //混淆背景 61 Pen linePen = new Pen(new SolidBrush(Color.Black), 2); 62 for (int x = 0; x < 6; x++) 63 graph.DrawLine(linePen, new Point(r.Next(0, 159), r.Next(0, 59)), new Point(r.Next(0, 159), r.Next(0, 59))); 64 65 //將圖片保存到輸出流中 66 basemap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif); 67 context.Session[ImageUniqueCode_Session] = s.ToString(); 68 } 69 70 public void CheckCode() 71 { 72 string code = ParamsData["UniqueCode"]; 73 if (code.ToUpper() == sessionData[ImageUniqueCode_Session].ToString().ToUpper()) 74 { 75 context.Response.Write("0"); 76 } 77 else 78 { 79 context.Response.Write("1"); 80 } 81 } 82 }
3)上傳下載文件kindeditorUpload
1 /// <summary> 2 /// kindeditor控件上傳下載的操做控制器 3 /// </summary> 4 public class kindeditorUpload : AbstractController 5 { 6 public void uploadfile() 7 { 8 //String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1); 9 10 //文件保存目錄路徑 11 String savePath = @"~/userfiles/"; 12 13 //文件保存目錄URL 14 String saveUrl = @"/userfiles/"; 15 16 //定義容許上傳的文件擴展名 17 Hashtable extTable = new Hashtable(); 18 extTable.Add("image", "gif,jpg,jpeg,png,bmp"); 19 extTable.Add("flash", "swf,flv"); 20 extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); 21 extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); 22 23 //最大文件大小 24 int maxSize = 1000000; 25 this.context = context; 26 27 HttpPostedFile imgFile = context.Request.Files["imgFile"]; 28 if (imgFile == null) 29 { 30 showError("請選擇文件。"); 31 } 32 33 String dirPath = context.Server.MapPath(savePath); 34 if (!Directory.Exists(dirPath)) 35 { 36 showError("上傳目錄不存在。"); 37 } 38 39 String dirName = context.Request.QueryString["dir"]; 40 if (String.IsNullOrEmpty(dirName)) 41 { 42 dirName = "image"; 43 } 44 if (!extTable.ContainsKey(dirName)) 45 { 46 showError("目錄名不正確。"); 47 } 48 49 String fileName = imgFile.FileName; 50 String fileExt = Path.GetExtension(fileName).ToLower(); 51 52 if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) 53 { 54 showError("上傳文件大小超過限制。"); 55 } 56 57 if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1) 58 { 59 showError("上傳文件擴展名是不容許的擴展名。\n只容許" + ((String)extTable[dirName]) + "格式。"); 60 } 61 62 //建立文件夾 63 dirPath += dirName + "/"; 64 saveUrl += dirName + "/"; 65 if (!Directory.Exists(dirPath)) 66 { 67 Directory.CreateDirectory(dirPath); 68 } 69 String ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo); 70 dirPath += ymd + "/"; 71 saveUrl += ymd + "/"; 72 if (!Directory.Exists(dirPath)) 73 { 74 Directory.CreateDirectory(dirPath); 75 } 76 77 String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo) + fileExt; 78 String filePath = dirPath + newFileName; 79 80 imgFile.SaveAs(filePath); 81 82 String fileUrl = saveUrl + newFileName; 83 84 Hashtable hash = new Hashtable(); 85 hash["error"] = 0; 86 hash["url"] = fileUrl; 87 context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); 88 context.Response.Write(JavaScriptConvert.SerializeObject(hash)); 89 context.Response.End(); 90 91 } 92 93 public void filemanager() 94 { 95 //String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1); 96 97 //根目錄路徑,相對路徑 98 String rootPath = @"~/userfiles/"; 99 //根目錄URL,能夠指定絕對路徑,好比 http://www.yoursite.com/attached/ 100 String rootUrl = @"/userfiles/"; 101 //圖片擴展名 102 String fileTypes = "gif,jpg,jpeg,png,bmp"; 103 104 String currentPath = ""; 105 String currentUrl = ""; 106 String currentDirPath = ""; 107 String moveupDirPath = ""; 108 109 String dirPath = context.Server.MapPath(rootPath); 110 String dirName = context.Request.QueryString["dir"]; 111 if (!String.IsNullOrEmpty(dirName)) 112 { 113 if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -1) 114 { 115 context.Response.Write("Invalid Directory name."); 116 context.Response.End(); 117 } 118 dirPath += dirName + "/"; 119 rootUrl += dirName + "/"; 120 if (!Directory.Exists(dirPath)) 121 { 122 Directory.CreateDirectory(dirPath); 123 } 124 } 125 126 //根據path參數,設置各路徑和URL 127 String path = context.Request.QueryString["path"]; 128 path = String.IsNullOrEmpty(path) ? "" : path; 129 if (path == "") 130 { 131 currentPath = dirPath; 132 currentUrl = rootUrl; 133 currentDirPath = ""; 134 moveupDirPath = ""; 135 } 136 else 137 { 138 currentPath = dirPath + path; 139 currentUrl = rootUrl + path; 140 currentDirPath = path; 141 moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1"); 142 } 143 144 //排序形式,name or size or type 145 String order = context.Request.QueryString["order"]; 146 order = String.IsNullOrEmpty(order) ? "" : order.ToLower(); 147 148 //不容許使用..移動到上一級目錄 149 if (Regex.IsMatch(path, @"\.\.")) 150 { 151 context.Response.Write("Access is not allowed."); 152 context.Response.End(); 153 } 154 //最後一個字符不是/ 155 if (path != "" && !path.EndsWith("/")) 156 { 157 context.Response.Write("Parameter is not valid."); 158 context.Response.End(); 159 } 160 //目錄不存在或不是目錄 161 if (!Directory.Exists(currentPath)) 162 { 163 context.Response.Write("Directory does not exist."); 164 context.Response.End(); 165 } 166 167 //遍歷目錄取得文件信息 168 string[] dirList = Directory.GetDirectories(currentPath); 169 string[] fileList = Directory.GetFiles(currentPath); 170 171 switch (order) 172 { 173 case "size": 174 Array.Sort(dirList, new NameSorter()); 175 Array.Sort(fileList, new SizeSorter()); 176 break; 177 case "type": 178 Array.Sort(dirList, new NameSorter()); 179 Array.Sort(fileList, new TypeSorter()); 180 break; 181 case "name": 182 default: 183 Array.Sort(dirList, new NameSorter()); 184 Array.Sort(fileList, new NameSorter()); 185 break; 186 } 187 188 Hashtable result = new Hashtable(); 189 result["moveup_dir_path"] = moveupDirPath; 190 result["current_dir_path"] = currentDirPath; 191 result["current_url"] = currentUrl; 192 result["total_count"] = dirList.Length + fileList.Length; 193 List<Hashtable> dirFileList = new List<Hashtable>(); 194 result["file_list"] = dirFileList; 195 for (int i = 0; i < dirList.Length; i++) 196 { 197 DirectoryInfo dir = new DirectoryInfo(dirList[i]); 198 Hashtable hash = new Hashtable(); 199 hash["is_dir"] = true; 200 hash["has_file"] = (dir.GetFileSystemInfos().Length > 0); 201 hash["filesize"] = 0; 202 hash["is_photo"] = false; 203 hash["filetype"] = ""; 204 hash["filename"] = dir.Name; 205 hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"); 206 dirFileList.Add(hash); 207 } 208 for (int i = 0; i < fileList.Length; i++) 209 { 210 FileInfo file = new FileInfo(fileList[i]); 211 Hashtable hash = new Hashtable(); 212 hash["is_dir"] = false; 213 hash["has_file"] = false; 214 hash["filesize"] = file.Length; 215 hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0); 216 hash["filetype"] = file.Extension.Substring(1); 217 hash["filename"] = file.Name; 218 hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"); 219 dirFileList.Add(hash); 220 } 221 context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8"); 222 context.Response.Write(JavaScriptConvert.SerializeObject(result)); 223 context.Response.End(); 224 225 } 226 227 private void showError(string message) 228 { 229 Hashtable hash = new Hashtable(); 230 hash["error"] = 1; 231 hash["message"] = message; 232 context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); 233 context.Response.Write(JavaScriptConvert.SerializeObject(hash)); 234 context.Response.End(); 235 } 236 237 }
4)圖表顯示WebFusionChart
1 public delegate object DelegateChart(XmlDocument xmldoc); 2 3 public static class WebFusionChart 4 { 5 public static XmlDocument CreateChartXML() 6 { 7 StringBuilder sb = new StringBuilder(); 8 sb.Append("<graph>"); 9 sb.Append("</graph>"); 10 XmlDocument _xmlDoc = new XmlDocument(); 11 _xmlDoc.LoadXml(sb.ToString()); 12 13 return _xmlDoc; 14 } 15 16 /// <summary> 17 /// 根據XML數據文件建立對象 18 /// </summary> 19 /// <param name="filename"></param> 20 /// <returns></returns> 21 public static XmlDocument CreateChartXML(string filename) 22 { 23 XmlDocument _xmlDoc = new XmlDocument(); 24 _xmlDoc.Load(filename); 25 return _xmlDoc; 26 } 27 /// <summary> 28 /// 29 /// </summary> 30 /// <param name="chartXML"></param> 31 /// <param name="AttributeName"></param> 32 /// <param name="AttributeValue"></param> 33 public static void AddgraphAttribute(XmlDocument chartXML, string AttributeName, string AttributeValue) 34 { 35 chartXML.DocumentElement.SetAttribute(AttributeName, AttributeValue); 36 } 37 38 public static void Addcategories(XmlDocument chartXML) 39 { 40 XmlElement xmlcategories = chartXML.CreateElement("categories"); 41 chartXML.DocumentElement.AppendChild(xmlcategories); 42 } 43 44 public static void AddcategoriesAttribute(XmlDocument chartXML, int index, string AttributeName, string AttributeValue) 45 { 46 ((XmlElement)chartXML.DocumentElement.SelectNodes("categories")[index]).SetAttribute(AttributeName, AttributeValue); 47 } 48 49 public static void Addcategory(XmlDocument chartXML, int index) 50 { 51 XmlElement xmlcategory = chartXML.CreateElement("category"); 52 chartXML.DocumentElement.SelectNodes("categories")[index].AppendChild(xmlcategory); 53 } 54 55 public static void AddcategoryAttribute(XmlDocument chartXML, int index, int index2, string AttributeName, string AttributeValue) 56 { 57 ((XmlElement)chartXML.DocumentElement.SelectNodes("categories")[index].SelectNodes("category")[index2]).SetAttribute(AttributeName, AttributeValue); 58 } 59 60 public static void Adddataset(XmlDocument chartXML) 61 { 62 XmlElement xmldataset = chartXML.CreateElement("dataset"); 63 chartXML.DocumentElement.AppendChild(xmldataset); 64 } 65 66 public static void AdddatasetAttribute(XmlDocument chartXML, int index, string AttributeName, string AttributeValue) 67 { 68 ((XmlElement)chartXML.DocumentElement.SelectNodes("dataset")[index]).SetAttribute(AttributeName, AttributeValue); 69 } 70 71 public static void Addset(XmlDocument chartXML, int index) 72 { 73 XmlElement xmlset = chartXML.CreateElement("set"); 74 chartXML.DocumentElement.SelectNodes("dataset")[index].AppendChild(xmlset); 75 } 76 77 public static void AddsetAttribute(XmlDocument chartXML, int index, int index2, string AttributeName, string AttributeValue) 78 { 79 ((XmlElement)chartXML.DocumentElement.SelectNodes("dataset")[index].SelectNodes("set")[index2]).SetAttribute(AttributeName, AttributeValue); 80 } 81 82 public static string chartXMLtoJson(XmlDocument chartXML) 83 { 84 System.IO.StringWriter sw = new System.IO.StringWriter(); 85 chartXML.Save(sw); 86 string xmlstr = sw.ToString(); 87 xmlstr = xmlstr.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "").Replace("\r\n", "").Replace("\"", "'"); 88 return "{\"data\":\"" + xmlstr + "\"}"; 89 } 90 91 public static string chartXMLtoJson(XmlDocument chartXML, int rowNum) 92 { 93 System.IO.StringWriter sw = new System.IO.StringWriter(); 94 chartXML.Save(sw); 95 string xmlstr = sw.ToString(); 96 xmlstr = xmlstr.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "").Replace("\r\n", "").Replace("\"", "'"); 97 return "{\"data\":\"" + xmlstr + "\",\"rowNum\":\"" + rowNum.ToString() + "\"}"; 98 } 99 100 public static string GetLineChartXmlDataDemo1() 101 { 102 XmlDocument xmlchart = CreateChartXML(); 103 104 AddgraphAttribute(xmlchart, "numdivlines", "4"); 105 AddgraphAttribute(xmlchart, "lineThickness", "3"); 106 AddgraphAttribute(xmlchart, "showValues", "0"); 107 AddgraphAttribute(xmlchart, "numVDivLines", "10"); 108 AddgraphAttribute(xmlchart, "formatNumberScale", "1"); 109 AddgraphAttribute(xmlchart, "rotateNames", "1"); 110 AddgraphAttribute(xmlchart, "decimalPrecision", "1"); 111 AddgraphAttribute(xmlchart, "anchorRadius", "2"); 112 AddgraphAttribute(xmlchart, "anchorBgAlpha", "0"); 113 AddgraphAttribute(xmlchart, "numberPrefix", "$"); 114 AddgraphAttribute(xmlchart, "divLineAlpha", "30"); 115 AddgraphAttribute(xmlchart, "showAlternateHGridColor", "1"); 116 AddgraphAttribute(xmlchart, "yAxisMinValue", "800000"); 117 AddgraphAttribute(xmlchart, "shadowAlpha", "50"); 118 119 Addcategories(xmlchart); 120 Addcategory(xmlchart, 0); 121 AddcategoryAttribute(xmlchart, 0, 0, "Name", "Jan"); 122 Addcategory(xmlchart, 0); 123 AddcategoryAttribute(xmlchart, 0, 1, "Name", "Feb"); 124 Addcategory(xmlchart, 0); 125 AddcategoryAttribute(xmlchart, 0, 2, "Name", "Mar"); 126 127 Adddataset(xmlchart); 128 AdddatasetAttribute(xmlchart, 0, "seriesName", "Current Year"); 129 AdddatasetAttribute(xmlchart, 0, "color", "A66EDD"); 130 AdddatasetAttribute(xmlchart, 0, "anchorBorderColor", "A66EDD"); 131 AdddatasetAttribute(xmlchart, 0, "anchorRadius", "4"); 132 Addset(xmlchart, 0); 133 AddsetAttribute(xmlchart, 0, 0, "value", "927654"); 134 Addset(xmlchart, 0); 135 AddsetAttribute(xmlchart, 0, 1, "value", "917654"); 136 Addset(xmlchart, 0); 137 AddsetAttribute(xmlchart, 0, 2, "value", "987654"); 138 139 Adddataset(xmlchart); 140 AdddatasetAttribute(xmlchart, 1, "seriesName", "Current Year"); 141 AdddatasetAttribute(xmlchart, 1, "color", "A66EDD"); 142 AdddatasetAttribute(xmlchart, 1, "anchorBorderColor", "A66EDD"); 143 AdddatasetAttribute(xmlchart, 1, "anchorRadius", "4"); 144 Addset(xmlchart, 1); 145 AddsetAttribute(xmlchart, 1, 0, "value", "827654"); 146 Addset(xmlchart, 1); 147 AddsetAttribute(xmlchart, 1, 1, "value", "817654"); 148 Addset(xmlchart, 1); 149 AddsetAttribute(xmlchart, 1, 2, "value", "887654"); 150 151 152 153 154 return chartXMLtoJson(xmlchart); 155 } 156 157 public static string GetLineChartXmlDataDemo2() 158 { 159 DataTable dt = new DataTable(); 160 DelegateChart chart = delegate(XmlDocument xmlchart) 161 { 162 AddgraphAttribute(xmlchart, "numdivlines", "4"); 163 AddgraphAttribute(xmlchart, "lineThickness", "3"); 164 AddgraphAttribute(xmlchart, "showValues", "0"); 165 AddgraphAttribute(xmlchart, "numVDivLines", "10"); 166 AddgraphAttribute(xmlchart, "formatNumberScale", "1"); 167 AddgraphAttribute(xmlchart, "rotateNames", "1"); 168 AddgraphAttribute(xmlchart, "decimalPrecision", "1"); 169 AddgraphAttribute(xmlchart, "anchorRadius", "2"); 170 AddgraphAttribute(xmlchart, "anchorBgAlpha", "0"); 171 AddgraphAttribute(xmlchart, "numberPrefix", "$"); 172 AddgraphAttribute(xmlchart, "divLineAlpha", "30"); 173 AddgraphAttribute(xmlchart, "showAlternateHGridColor", "1"); 174 AddgraphAttribute(xmlchart, "yAxisMinValue", "800000"); 175 AddgraphAttribute(xmlchart, "shadowAlpha", "50"); 176 return xmlchart;//? 177 }; 178 return CreateLineXMLData(dt, chart); 179 } 180 181 public static string CreateLineXMLData(DataTable dt, DelegateChart chart) 182 { 183 XmlDocument xmlchart = CreateChartXML(); 184 185 AddgraphAttribute(xmlchart, "numdivlines", "4"); 186 AddgraphAttribute(xmlchart, "lineThickness", "3"); 187 AddgraphAttribute(xmlchart, "showValues", "0"); 188 AddgraphAttribute(xmlchart, "numVDivLines", "10"); 189 AddgraphAttribute(xmlchart, "formatNumberScale", "1"); 190 AddgraphAttribute(xmlchart, "rotateNames", "1"); 191 AddgraphAttribute(xmlchart, "decimalPrecision", "1"); 192 AddgraphAttribute(xmlchart, "anchorRadius", "2"); 193 AddgraphAttribute(xmlchart, "anchorBgAlpha", "0"); 194 AddgraphAttribute(xmlchart, "numberPrefix", "$"); 195 AddgraphAttribute(xmlchart, "divLineAlpha", "30"); 196 AddgraphAttribute(xmlchart, "showAlternateHGridColor", "1"); 197 AddgraphAttribute(xmlchart, "yAxisMinValue", "800000"); 198 AddgraphAttribute(xmlchart, "shadowAlpha", "50"); 199 200 Addcategories(xmlchart); 201 //建立X軸 202 for (int i = 0; i < dt.Rows.Count; i++) 203 { 204 Addcategory(xmlchart, 0); 205 AddcategoryAttribute(xmlchart, 0, 0, "Name", dt.Rows[i][0].ToString()); 206 } 207 208 //畫線 209 for (int i = 1; i < dt.Columns.Count; i++)//多少條線 210 { 211 Adddataset(xmlchart); 212 AdddatasetAttribute(xmlchart, i - 1, "seriesName", "Current Year"); 213 AdddatasetAttribute(xmlchart, i - 1, "color", "A66EDD"); 214 AdddatasetAttribute(xmlchart, i - 1, "anchorBorderColor", "A66EDD"); 215 AdddatasetAttribute(xmlchart, i - 1, "anchorRadius", "4"); 216 217 for (int j = 0; j < dt.Rows.Count; j++)//畫每條線的點的位置 218 { 219 Addset(xmlchart, j); 220 AddsetAttribute(xmlchart, i - 1, j, "value", dt.Rows[j][i].ToString()); 221 } 222 } 223 224 if (chart != null) 225 chart(xmlchart); 226 227 return chartXMLtoJson(xmlchart); 228 } 229 230 public static string CreateLineXMLData(DataTable dt, Hashtable chartAttribute, string categoriesColumn, string[] valueColumns, Hashtable[] valueAttributes) 231 { 232 DelegateChart chart = delegate(XmlDocument xmlchart) 233 { 234 AddgraphAttribute(xmlchart, "numdivlines", "4"); 235 AddgraphAttribute(xmlchart, "lineThickness", "3"); 236 AddgraphAttribute(xmlchart, "showValues", "0"); 237 AddgraphAttribute(xmlchart, "numVDivLines", "10"); 238 AddgraphAttribute(xmlchart, "formatNumberScale", "1"); 239 AddgraphAttribute(xmlchart, "rotateNames", "1"); 240 AddgraphAttribute(xmlchart, "decimalPrecision", "1"); 241 AddgraphAttribute(xmlchart, "anchorRadius", "2"); 242 AddgraphAttribute(xmlchart, "anchorBgAlpha", "0"); 243 AddgraphAttribute(xmlchart, "numberPrefix", "$"); 244 AddgraphAttribute(xmlchart, "divLineAlpha", "30"); 245 AddgraphAttribute(xmlchart, "showAlternateHGridColor", "1"); 246 AddgraphAttribute(xmlchart, "yAxisMinValue", "800000"); 247 AddgraphAttribute(xmlchart, "shadowAlpha", "50"); 248 return xmlchart;//? 249 }; 250 return CreateLineXMLData(dt, chart, chartAttribute, categoriesColumn, valueColumns, valueAttributes); 251 } 252 /// <summary> 253 /// 建立圖表線數據源的方法 254 /// </summary> 255 /// <param name="dt">數據集</param> 256 /// <param name="chart">回調函數用來數據源屬性</param> 257 /// <param name="chartAttribute">數據源根節點屬性</param> 258 /// <param name="categoriesColumn">指定dt數據集中列名一致的列值爲X軸內容</param> 259 /// <param name="valueColumns">指定dt數據集中列名一致的數組列值爲線的值,能夠有多條線</param> 260 /// <param name="valueAttributes">給每條線賦相關屬性值</param> 261 /// <returns></returns> 262 public static string CreateLineXMLData(DataTable dt, DelegateChart chart, Hashtable chartAttribute, string categoriesColumn, string[] valueColumns, Hashtable[] valueAttributes) 263 { 264 XmlDocument xmlchart = CreateChartXML(); 265 AddgraphAttribute(xmlchart, "caption", "XXXXXX統計");//主標題 266 AddgraphAttribute(xmlchart, "subcaption", "2009年");//子標題 267 AddgraphAttribute(xmlchart, "xAxisName", "月份");//x軸標題 268 AddgraphAttribute(xmlchart, "yAxisName", "銷售額");//y軸標題 269 AddgraphAttribute(xmlchart, "yAxisMinValue", "800000");//y軸最小值 270 AddgraphAttribute(xmlchart, "numVDivLines", "10");//y抽分隔線條數 271 AddgraphAttribute(xmlchart, "numdivlines", "4"); 272 AddgraphAttribute(xmlchart, "numberPrefix", "$");//y軸值得單位 273 AddgraphAttribute(xmlchart, "lineThickness", "3");//折線的粗細 274 AddgraphAttribute(xmlchart, "showValues", "0"); 275 AddgraphAttribute(xmlchart, "formatNumberScale", "1"); 276 AddgraphAttribute(xmlchart, "rotateNames", "1"); 277 AddgraphAttribute(xmlchart, "decimalPrecision", "1"); 278 AddgraphAttribute(xmlchart, "anchorRadius", "2"); 279 AddgraphAttribute(xmlchart, "anchorBgAlpha", "0"); 280 AddgraphAttribute(xmlchart, "divLineAlpha", "30"); 281 AddgraphAttribute(xmlchart, "showAlternateHGridColor", "1"); 282 AddgraphAttribute(xmlchart, "shadowAlpha", "50"); 283 284 285 if (chartAttribute != null) 286 { 287 foreach (DictionaryEntry de in chartAttribute) 288 { 289 AddgraphAttribute(xmlchart, de.Key.ToString(), de.Value.ToString()); 290 } 291 } 292 293 Addcategories(xmlchart); 294 //建立X軸 295 for (int i = 0; i < dt.Rows.Count; i++) 296 { 297 Addcategory(xmlchart, 0); 298 AddcategoryAttribute(xmlchart, 0, i, "Name", dt.Rows[i][categoriesColumn].ToString()); 299 } 300 301 //畫線 302 for (int i = 0; i < valueColumns.Length; i++)//多少條線 303 { 304 Adddataset(xmlchart); 305 AdddatasetAttribute(xmlchart, i, "seriesName", "Current Year"); 306 AdddatasetAttribute(xmlchart, i, "color", "A66EDD"); 307 AdddatasetAttribute(xmlchart, i, "anchorBorderColor", "A66EDD"); 308 AdddatasetAttribute(xmlchart, i, "anchorRadius", "4"); 309 310 if (valueAttributes != null) 311 { 312 foreach (DictionaryEntry de in valueAttributes[i]) 313 { 314 AdddatasetAttribute(xmlchart, i, de.Key.ToString(), de.Value.ToString()); 315 } 316 } 317 318 for (int j = 0; j < dt.Rows.Count; j++)//畫每條線的點的位置 319 { 320 Addset(xmlchart, i); 321 AddsetAttribute(xmlchart, i, j, "value", dt.Rows[j][valueColumns[i]].ToString()); 322 } 323 } 324 325 if (chart != null) 326 chart(xmlchart); 327 328 return chartXMLtoJson(xmlchart, dt.Rows.Count); 329 } 330 331 /// <summary> 332 /// 建立圖表具狀圖數據源的方法 333 /// </summary> 334 /// <param name="dt">數據集</param> 335 /// <param name="chart">回調函數用來數據源屬性</param> 336 /// <param name="chartAttribute">數據源根節點屬性</param> 337 /// <param name="categoriesColumn">指定dt數據集中列名一致的列值爲X軸內容</param> 338 /// <param name="valueColumns">指定dt數據集中列名一致的數組列值爲線的值,能夠有多條線</param> 339 /// <param name="valueAttributes">給每條線賦相關屬性值</param> 340 /// <returns></returns> 341 public static string CreateColumnXMLData(DataTable dt, DelegateChart chart, Hashtable chartAttribute, string categoriesColumn, string[] valueColumns, Hashtable[] valueAttributes) 342 { 343 XmlDocument xmlchart = CreateChartXML(); 344 AddgraphAttribute(xmlchart, "caption", "XXXXXX統計");//主標題 345 AddgraphAttribute(xmlchart, "subcaption", "2009年");//子標題 346 AddgraphAttribute(xmlchart, "xAxisName", "月份");//x軸標題 347 AddgraphAttribute(xmlchart, "yAxisName", "銷售額");//y軸標題 348 AddgraphAttribute(xmlchart, "yAxisMinValue", "800000");//y軸最小值 349 AddgraphAttribute(xmlchart, "numVDivLines", "10");//y抽分隔線條數 350 AddgraphAttribute(xmlchart, "numdivlines", "4"); 351 AddgraphAttribute(xmlchart, "numberPrefix", "$");//y軸值得單位 352 AddgraphAttribute(xmlchart, "lineThickness", "3");//折線的粗細 353 AddgraphAttribute(xmlchart, "showValues", "0"); 354 AddgraphAttribute(xmlchart, "formatNumberScale", "1"); 355 AddgraphAttribute(xmlchart, "rotateNames", "1"); 356 AddgraphAttribute(xmlchart, "decimalPrecision", "1"); 357 AddgraphAttribute(xmlchart, "anchorRadius", "2"); 358 AddgraphAttribute(xmlchart, "anchorBgAlpha", "0"); 359 AddgraphAttribute(xmlchart, "divLineAlpha", "30"); 360 AddgraphAttribute(xmlchart, "showAlternateHGridColor", "1"); 361 AddgraphAttribute(xmlchart, "shadowAlpha", "50"); 362 363 364 if (chartAttribute != null) 365 { 366 foreach (DictionaryEntry de in chartAttribute) 367 { 368 AddgraphAttribute(xmlchart, de.Key.ToString(), de.Value.ToString()); 369 } 370 } 371 372 Addcategories(xmlchart); 373 //建立X軸 374 for (int i = 0; i < dt.Rows.Count; i++) 375 { 376 Addcategory(xmlchart, 0); 377 AddcategoryAttribute(xmlchart, 0, i, "Name", dt.Rows[i][categoriesColumn].ToString()); 378 } 379 380 //畫線 381 for (int i = 0; i < valueColumns.Length; i++)//多少條線 382 { 383 Adddataset(xmlchart); 384 AdddatasetAttribute(xmlchart, i, "seriesName", "Current Year"); 385 AdddatasetAttribute(xmlchart, i, "color", "A66EDD"); 386 AdddatasetAttribute(xmlchart, i, "anchorBorderColor", "A66EDD"); 387 AdddatasetAttribute(xmlchart, i, "anchorRadius", "4"); 388 389 if (valueAttributes != null) 390 { 391 foreach (DictionaryEntry de in valueAttributes[i]) 392 { 393 AdddatasetAttribute(xmlchart, i, de.Key.ToString(), de.Value.ToString()); 394 } 395 } 396 397 for (int j = 0; j < dt.Rows.Count; j++)//畫每條線的點的位置 398 { 399 Addset(xmlchart, i); 400 AddsetAttribute(xmlchart, i, j, "value", dt.Rows[j][valueColumns[i]].ToString()); 401 } 402 } 403 404 if (chart != null) 405 chart(xmlchart); 406 407 return chartXMLtoJson(xmlchart, dt.Rows.Count); 408 } 409 410 /// <summary> 411 /// 建立圖表餅圖數據源的方法 412 /// </summary> 413 /// <param name="dt">數據集</param> 414 /// <param name="chart">回調函數用來數據源屬性</param> 415 /// <param name="chartAttribute">數據源根節點屬性</param> 416 /// <param name="categoriesColumn">指定dt數據集中列名一致的列值爲X軸內容</param> 417 /// <param name="valueColumns">指定dt數據集中列名一致的數組列值爲線的值,能夠有多條線</param> 418 /// <param name="valueAttributes">給每條線賦相關屬性值</param> 419 /// <returns></returns> 420 public static string CreatePieXMLData(DataTable dt, DelegateChart chart, Hashtable chartAttribute, string categoriesColumn, string[] valueColumns, Hashtable[] valueAttributes) 421 { 422 XmlDocument xmlchart = CreateChartXML(); 423 AddgraphAttribute(xmlchart, "caption", "XXXXXX統計");//主標題 424 AddgraphAttribute(xmlchart, "subcaption", "2009年");//子標題 425 AddgraphAttribute(xmlchart, "xAxisName", "月份");//x軸標題 426 AddgraphAttribute(xmlchart, "yAxisName", "銷售額");//y軸標題 427 AddgraphAttribute(xmlchart, "yAxisMinValue", "800000");//y軸最小值 428 AddgraphAttribute(xmlchart, "numVDivLines", "10");//y抽分隔線條數 429 AddgraphAttribute(xmlchart, "numdivlines", "4"); 430 AddgraphAttribute(xmlchart, "numberPrefix", "$");//y軸值得單位 431 AddgraphAttribute(xmlchart, "lineThickness", "3");//折線的粗細 432 AddgraphAttribute(xmlchart, "showValues", "0"); 433 AddgraphAttribute(xmlchart, "formatNumberScale", "1"); 434 AddgraphAttribute(xmlchart, "rotateNames", "1"); 435 AddgraphAttribute(xmlchart, "decimalPrecision", "1"); 436 AddgraphAttribute(xmlchart, "anchorRadius", "2"); 437 AddgraphAttribute(xmlchart, "anchorBgAlpha", "0"); 438 AddgraphAttribute(xmlchart, "divLineAlpha", "30"); 439 AddgraphAttribute(xmlchart, "showAlternateHGridColor", "1"); 440 AddgraphAttribute(xmlchart, "shadowAlpha", "50"); 441 442 443 if (chartAttribute != null) 444 { 445 foreach (DictionaryEntry de in chartAttribute) 446 { 447 AddgraphAttribute(xmlchart, de.Key.ToString(), de.Value.ToString()); 448 } 449 } 450 451 Addcategories(xmlchart); 452 //建立X軸 453 for (int i = 0; i < dt.Rows.Count; i++) 454 { 455 Addcategory(xmlchart, 0); 456 AddcategoryAttribute(xmlchart, 0, i, "Name", dt.Rows[i][categoriesColumn].ToString()); 457 } 458 459 //畫線 460 for (int i = 0; i < valueColumns.Length; i++)//多少條線 461 { 462 Adddataset(xmlchart); 463 AdddatasetAttribute(xmlchart, i, "seriesName", "Current Year"); 464 AdddatasetAttribute(xmlchart, i, "color", "A66EDD"); 465 AdddatasetAttribute(xmlchart, i, "anchorBorderColor", "A66EDD"); 466 AdddatasetAttribute(xmlchart, i, "anchorRadius", "4"); 467 468 if (valueAttributes != null) 469 { 470 foreach (DictionaryEntry de in valueAttributes[i]) 471 { 472 AdddatasetAttribute(xmlchart, i, de.Key.ToString(), de.Value.ToString()); 473 } 474 } 475 476 for (int j = 0; j < dt.Rows.Count; j++)//畫每條線的點的位置 477 { 478 Addset(xmlchart, i); 479 AddsetAttribute(xmlchart, i, j, "value", dt.Rows[j][valueColumns[i]].ToString()); 480 } 481 } 482 483 if (chart != null) 484 chart(xmlchart); 485 486 return chartXMLtoJson(xmlchart, dt.Rows.Count); 487 } 488 }
5)報表開發WebReportAll
1 /// <summary> 2 /// Web報表封裝幫助類 3 /// </summary> 4 public static class WebReportAll 5 { 6 /// <summary> 7 /// 轉換爲報表數據 8 /// </summary> 9 /// <param name="dtDetail">明細數據內容</param> 10 /// <returns></returns> 11 public static string ToReportData(DataTable dtDetail) 12 { 13 RAXmlDataSource xmlData = new RAXmlDataSource(); 14 //xmlData.SetMaster(dtMaster, ""); 15 xmlData.AddDetail("Detail1", dtDetail, "", ""); 16 return xmlData.ExportToJson(); 17 } 18 /// <summary> 19 /// 轉換爲報表數據 20 /// </summary> 21 /// <param name="dtMaster">報表頁眉數據內容</param> 22 /// <param name="dtDetail">明細數據內容</param> 23 /// <returns></returns> 24 public static string ToReportData(DataTable dtMaster, DataTable dtDetail) 25 { 26 RAXmlDataSource xmlData = new RAXmlDataSource(); 27 xmlData.SetMaster(dtMaster, ""); 28 xmlData.AddDetail("Detail1", dtDetail, "", ""); 29 return xmlData.ExportToJson(); 30 } 31 /// <summary> 32 /// 轉換爲報表數據 33 /// </summary> 34 /// <param name="dtMaster">報表頁眉數據內容</param> 35 /// <param name="dtDetails">多個明細數據內容</param> 36 /// <returns></returns> 37 public static string ToReportData(DataTable dtMaster, DataTable[] dtDetails) 38 { 39 RAXmlDataSource xmlData = new RAXmlDataSource(); 40 xmlData.SetMaster(dtMaster, ""); 41 for (int i = 0; i < dtDetails.Length; i++) 42 { 43 xmlData.AddDetail("Detail" + (i + 1).ToString(), dtDetails[i], "", ""); 44 } 45 return xmlData.ExportToJson(); 46 } 47 }
6)Excel導入導出ExcelHelper
1 /// <summary> 2 /// 導出Excel 3 /// </summary> 4 public class ExcelHelper 5 { 6 /// <summary> 7 /// DataTable導出到Excel文件 8 /// </summary> 9 /// <param name="dtSource">源DataTable</param> 10 /// <param name="strHeaderText">表頭文本</param> 11 /// <param name="strFileName">保存位置</param> 12 /// <Author></Author> 13 public static void Export(DataTable dtSource, string strHeaderText, string strFileName) 14 { 15 using (MemoryStream ms = Export(dtSource, strHeaderText, new Dictionary<string, string>())) 16 { 17 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) 18 { 19 byte[] data = ms.ToArray(); 20 fs.Write(data, 0, data.Length); 21 fs.Flush(); 22 } 23 } 24 } 25 26 public static void Export(DataTable dtSource, string strHeaderText, Dictionary<string, string> columnNames, string strFileName) 27 { 28 using (MemoryStream ms = Export(dtSource, strHeaderText, columnNames)) 29 { 30 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) 31 { 32 byte[] data = ms.ToArray(); 33 fs.Write(data, 0, data.Length); 34 fs.Flush(); 35 } 36 } 37 } 38 39 /// <summary> 40 /// DataTable導出到Excel的MemoryStream 41 /// </summary> 42 /// <param name="dtSource">源DataTable</param> 43 /// <param name="strHeaderText">表頭文本</param> 44 /// <Author> 2010-5-8 22:21:41</Author> 45 public static MemoryStream Export(DataTable dtSource, string strHeaderText, Dictionary<string, string> columnNames) 46 { 47 HSSFWorkbook workbook = new HSSFWorkbook(); 48 HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); 49 50 #region 右擊文件 屬性信息 51 { 52 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 53 dsi.Company = ""; 54 workbook.DocumentSummaryInformation = dsi; 55 56 SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); 57 si.Author = "曾浩"; //填加xls文件做者信息 58 si.ApplicationName = ""; //填加xls文件建立程序信息 59 si.LastAuthor = ""; //填加xls文件最後保存者信息 60 si.Comments = "說明信息"; //填加xls文件做者信息 61 si.Title = ""; //填加xls文件標題信息 62 si.Subject = "";//填加文件主題信息 63 si.CreateDateTime = DateTime.Now; 64 workbook.SummaryInformation = si; 65 } 66 #endregion 67 68 HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle(); 69 HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat(); 70 dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); 71 72 //取得列寬 73 int[] arrColWidth = new int[dtSource.Columns.Count]; 74 foreach (DataColumn item in dtSource.Columns) 75 { 76 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; 77 } 78 for (int i = 0; i < dtSource.Rows.Count; i++) 79 { 80 for (int j = 0; j < dtSource.Columns.Count; j++) 81 { 82 int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; 83 if (intTemp > arrColWidth[j]) 84 { 85 arrColWidth[j] = intTemp; 86 } 87 } 88 } 89 90 91 92 int rowIndex = 0; 93 int index = 0; 94 foreach (DataRow row in dtSource.Rows) 95 { 96 #region 新建表,填充表頭,填充列頭,樣式 97 if (rowIndex == 65535 || rowIndex == 0) 98 { 99 if (rowIndex != 0) 100 { 101 sheet = (HSSFSheet)workbook.CreateSheet(); 102 } 103 104 #region 表頭及樣式 105 { 106 HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); 107 headerRow.HeightInPoints = 25; 108 headerRow.CreateCell(0).SetCellValue(strHeaderText); 109 110 HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); 111 headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER; 112 HSSFFont font = (HSSFFont)workbook.CreateFont(); 113 font.FontHeightInPoints = 20; 114 font.Boldweight = 700; 115 headStyle.SetFont(font); 116 117 headerRow.GetCell(0).CellStyle = headStyle; 118 if (columnNames.Count > 0) 119 { 120 sheet.AddMergedRegion(new Region(0, 0, 0, columnNames.Count - 1)); 121 } 122 else 123 sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); 124 //headerRow.Dispose(); 125 } 126 #endregion 127 128 129 #region 列頭及樣式 130 { 131 HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1); 132 133 134 HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); 135 headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER; 136 HSSFFont font = (HSSFFont)workbook.CreateFont(); 137 font.FontHeightInPoints = 10; 138 font.Boldweight = 700; 139 headStyle.SetFont(font); 140 141 index = 0; 142 foreach (DataColumn column in dtSource.Columns) 143 { 144 if (columnNames.Count > 0) 145 { 146 if (columnNames.ContainsKey(column.ColumnName)) 147 { 148 149 headerRow.CreateCell(index).SetCellValue(columnNames[column.ColumnName]); 150 headerRow.GetCell(index).CellStyle = headStyle; 151 152 //設置列寬 153 sheet.SetColumnWidth(index, (Encoding.GetEncoding(936).GetBytes(columnNames[column.ColumnName]).Length + 1) * 256); 154 155 index++; 156 } 157 } 158 else 159 { 160 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); 161 headerRow.GetCell(column.Ordinal).CellStyle = headStyle; 162 163 //設置列寬 164 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 165 } 166 } 167 //headerRow.Dispose(); 168 } 169 #endregion 170 171 rowIndex = 2; 172 } 173 #endregion 174 175 176 #region 填充內容 177 index = 0; 178 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); 179 foreach (DataColumn column in dtSource.Columns) 180 { 181 if (columnNames.Count > 0) 182 { 183 if (columnNames.ContainsKey(column.ColumnName)) 184 { 185 HSSFCell newCell = (HSSFCell)dataRow.CreateCell(index); 186 187 string drValue = row[column].ToString(); 188 189 switch (column.DataType.ToString()) 190 { 191 case "System.String"://字符串類型 192 newCell.SetCellValue(drValue); 193 break; 194 case "System.DateTime"://日期類型 195 DateTime dateV; 196 DateTime.TryParse(drValue, out dateV); 197 newCell.SetCellValue(dateV); 198 199 newCell.CellStyle = dateStyle;//格式化顯示 200 break; 201 case "System.Boolean"://布爾型 202 bool boolV = false; 203 bool.TryParse(drValue, out boolV); 204 newCell.SetCellValue(boolV); 205 break; 206 case "System.Int16"://整型 207 case "System.Int32": 208 case "System.Int64": 209 case "System.Byte": 210 int intV = 0; 211 int.TryParse(drValue, out intV); 212 newCell.SetCellValue(intV); 213 break; 214 case "System.Decimal"://浮點型 215 case "System.Double": 216 double doubV = 0; 217 double.TryParse(drValue, out doubV); 218 newCell.SetCellValue(doubV); 219 break; 220 case "System.DBNull"://空值處理 221 newCell.SetCellValue(""); 222 break; 223 default: 224 newCell.SetCellValue(""); 225 break; 226 } 227 228 index++; 229 } 230 } 231 else 232 { 233 HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal); 234 235 string drValue = row[column].ToString(); 236 237 switch (column.DataType.ToString()) 238 { 239 case "System.String"://字符串類型 240 newCell.SetCellValue(drValue); 241 break; 242 case "System.DateTime"://日期類型 243 DateTime dateV; 244 DateTime.TryParse(drValue, out dateV); 245 newCell.SetCellValue(dateV); 246 247 newCell.CellStyle = dateStyle;//格式化顯示 248 break; 249 case "System.Boolean"://布爾型 250 bool boolV = false; 251 bool.TryParse(drValue, out boolV); 252 newCell.SetCellValue(boolV); 253 break; 254 case "System.Int16"://整型 255 case "System.Int32": 256 case "System.Int64": 257 case "System.Byte": 258 int intV = 0; 259 int.TryParse(drValue, out intV); 260 newCell.SetCellValue(intV); 261 break; 262 case "System.Decimal"://浮點型 263 case "System.Double": 264 double doubV = 0; 265 double.TryParse(drValue, out doubV); 266 newCell.SetCellValue(doubV); 267 break; 268 case "System.DBNull"://空值處理 269 newCell.SetCellValue(""); 270 break; 271 default: 272 newCell.SetCellValue(""); 273 break; 274 } 275 } 276 } 277 #endregion 278 279 rowIndex++; 280 } 281 282 283 using (MemoryStream ms = new MemoryStream()) 284 { 285 workbook.Write(ms); 286 ms.Flush(); 287 ms.Position = 0; 288 289 //sheet.Workbook.Dispose(); 290 //workbook.Dispose();//通常只用寫這一個就OK了,他會遍歷並釋放全部資源,但當前版本有問題因此只釋放 sheet 291 return ms; 292 } 293 294 } 295 296 297 /// <summary> 298 /// 用於Web導出 299 /// </summary> 300 /// <param name="dtSource">源DataTable</param> 301 /// <param name="strHeaderText">表頭文本</param> 302 /// <param name="strFileName">文件名</param> 303 /// <Author> 2010-5-8 22:21:41</Author> 304 public static void ExportByWeb(HttpContext context, DataTable dtSource, string strHeaderText, Dictionary<string, string> columnNames, string strFileName) 305 { 306 307 HttpContext curContext = context; 308 309 // 設置編碼和附件格式 310 curContext.Response.ContentType = "application/vnd.ms-excel"; 311 curContext.Response.ContentEncoding = Encoding.UTF8; 312 curContext.Response.Charset = ""; 313 curContext.Response.AppendHeader("Content-Disposition", 314 "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); 315 316 curContext.Response.BinaryWrite(Export(dtSource, strHeaderText, columnNames).GetBuffer()); 317 //curContext.Response.End(); 318 } 319 320 321 /// <summary>讀取excel 322 /// 默認第一行爲標頭 323 /// </summary> 324 /// <param name="strFileName">excel文檔路徑</param> 325 /// <returns></returns> 326 public static DataTable Import(string strFileName) 327 { 328 DataTable dt = new DataTable(); 329 330 HSSFWorkbook hssfworkbook; 331 using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) 332 { 333 hssfworkbook = new HSSFWorkbook(file); 334 } 335 HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(0); 336 System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); 337 338 HSSFRow headerRow = (HSSFRow)sheet.GetRow(0); 339 int cellCount = headerRow.LastCellNum; 340 341 for (int j = 0; j < cellCount; j++) 342 { 343 HSSFCell cell = (HSSFCell)headerRow.GetCell(j); 344 dt.Columns.Add(cell.ToString()); 345 } 346 347 for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) 348 { 349 HSSFRow row = (HSSFRow)sheet.GetRow(i); 350 DataRow dataRow = dt.NewRow(); 351 352 for (int j = row.FirstCellNum; j < cellCount; j++) 353 { 354 if (row.GetCell(j) != null) 355 dataRow[j] = row.GetCell(j).ToString(); 356 } 357 358 dt.Rows.Add(dataRow); 359 } 360 return dt; 361 } 362 363 }
7)模板引擎TemplateHelper
1 /// <summary> 2 /// NVelocity模板引擎幫助類 3 /// </summary> 4 public class TemplateHelper 5 { 6 private VelocityEngine velocity = null; 7 private IContext context = null; 8 9 public static string templatePath = "CodeTemplate"; 10 11 public TemplateHelper() 12 { 13 velocity = new VelocityEngine(); 14 15 //使用設置初始化VelocityEngine 16 ExtendedProperties props = new ExtendedProperties(); 17 18 props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath); 19 props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); 20 21 // props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312"); 22 // props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); 23 24 // props.SetProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, "NVelocity.Runtime.Resource.ResourceManagerImpl\\,NVelocity"); 25 26 velocity.Init(props); 27 //RuntimeConstants.RESOURCE_MANAGER_CLASS 28 //爲模板變量賦值 29 context = new VelocityContext(); 30 31 } 32 33 /// <summary> 34 /// 給模板變量賦值 35 /// </summary> 36 /// <param name="key">模板變量</param> 37 /// <param name="value">模板變量值</param> 38 public void Put(string key, object value) 39 { 40 context.Put(key, value); 41 } 42 43 /// <summary> 44 /// 生成字符 45 /// </summary> 46 /// <param name="templatFileName">模板文件名</param> 47 public string BuildString(string templateFile) 48 { 49 //從文件中讀取模板 50 Template template = velocity.GetTemplate(templateFile); 51 52 //合併模板 53 StringWriter writer = new StringWriter(); 54 template.Merge(context, writer); 55 return writer.ToString(); 56 } 57 58 public bool ContainsKey(string keyName) 59 { 60 return context.ContainsKey(keyName); 61 } 62 63 }
更多組件持續封裝中!