十七、EnterpriseFrameWork框架核心类库之Web控制器

 

回《【开源】EnterpriseFrameWork框架系列文章索引》       

EFW框架源代码下载:http://pan.baidu.com/s/1qWJjo3U

 

       EFW框架中的WebController就是解决JqueryEasyUI与逻辑层的交互,之间的数据是通过Json字符串来传递;值得注意的是WebController的代码一定不要和EFWWeb项目放在一起,你可以单独建一个项目类库,也可以和逻辑层项目放一起;在EFWWeb项目不要编写任何C#代码,这个在前面的文章中就提过,可以让你的Web项目发布更省事一点,免去编译EFWWeb项目的痛苦;

控制器可以调用分层一下的所有代码,包括ObjectModel、Dao、Entity,甚至可以直接用oleDb编写SQL语句操作数据库;还有控制器与控制器之间是不能存在任何依赖关系的;

本章主要内容通过解读框架源代码来学习WebController是怎么实现的,以及思考这样实现会给我们开发带来什么好处;

本文要点:

1.如何使用Web控制器

2.Web控制器的设计思路

3.Web控制器基类AbstractController的实现

4.Web控制器的自定义标签WebControllerAttribute和WebMethodAttribute

5.基于JqueryEasyUI封装的Web控制器的实现

6.Web常用组件封装成控制器

Web控制器源代码目录

 

 

EFW框架控制器设计图

 

 

1.如何使用Web控制器

讲解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>
View Code

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 }
View Code

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 }
View Code

 

我们先说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这种格式,调试的时候控制器中打了断点没有进来,首先查看指定的控制器名称和方法名称是否正确;

 

2.Web控制器的设计思路

       上文中举的实例是利用JqueryEasyUI开发的,如果我的项目不想要JqueryEasyUI,用更专业的Extjs或其他界面框架怎么办,EFW框架设计的时候充分的考虑到了这一点,我们看最上的“EFW框架控制器设计图”,bookController继承的是AbstractJqueryController对象,AbstractJqueryController对象又继承的AbstractController对象,AbstractController是Web控制器的核心基类,AbstractJqueryController就是针对JqueryEasyUI框架实现的控制器,我们要实现Extjs框架,就只要想只要像AbstractJqueryController一样编写一个适合Extjs框架的控制器基类,我们的bookController继承它就行了;

还有比如我们还开发手机上运行的网页程序,同样可以用这种方式来实现,下一个版本会把jquery.mobile引入到EFW框架中;

 

 

3.Web控制器基类AbstractController的实现

这里讲解一下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     }
View Code

AbstractController基类封装了三方面的内容:

1)数据库操作对象,这个我们之前第十章也讲过为什么要在控制器开放oleDb,这也是为了让框架分层使用起来更灵活,且兼容性强;

2)系统登录用户信息SysLoginRight,此属性封装了用户登录后的姓名、部门、机构等信息;这样在控制器中查询当前登录用户的数据时候会很简单;

3)网页中的数据,如请求参数、Session数据、表单数据等;从界面传进来的数据都可以从中获取;

 

4.Web控制器的自定义标签WebControllerAttribute和WebMethodAttribute

为了能让系统根据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     }
View Code

 

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     }
View Code

值得注意的就是,控制器的名称在整个系统中不能重复,如果出现相同名称的控制器,系统就可能无法正确调用对应的控制器;

 

5.基于JqueryEasyUI封装的Web控制器的实现

       接下来讲解一下基于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     }
View Code

 

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     }
View Code

 

开发一个新界面框架的Web控制器,一定要先设计好数据转换接口,因为到时候继承它的所有控制器都会使用这些封装的方法进行数据转换,到时候再改动此接口影响的代码就多啦;

还有就是TxtJson这个属性,系统就是把此属性中的数据输出到界面上的;

为什么要再EFW框架中默认使用JqueryEasyUI了,最主要的是学习成本底,基本上花的几个小时属性一下Demo中的控件就会用了;还有就是它是基于Jquery开发的,所以自己也可以再基础上进行一些扩展开发,能够满足一些特殊的需求;刚开始项目中是用的Extjs开发,就是因为学习成本太高了,一个新手一开始根本摸不到边,特别是设计界面与操作数据都是用JS代码,代码编写得规范的还好,编写得不好的,真的是太难看了;而我选择JqueryeasyUI另一点就是设计界面不用js代码,用html标签代码就可以搞定,非常方便;

6.Web常用组件封装成控制器

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     }
View Code

 

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     }
View Code

 

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     }
View Code

 

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     }
View Code

 

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     }
View Code

 

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     }
View Code

 

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     }
View Code

 

更多组件持续封装中!

posted @ 2014-09-18 22:05  kakake  阅读(2232)  评论(3编辑  收藏  举报