首页 > 代码库 > Datatable 生成json格式
Datatable 生成json格式
?
1 | |
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | public string GetJsonFromDataTable(DataTable dt, int total, bool ShowFooter, string fields, string inputfiled, string ShowMessage = "合计:" , string filter = "" ) { StringBuilder stringBuilder = new StringBuilder(); if (dt.Rows.Count == 0) { stringBuilder.Append( "{ " ); stringBuilder.Append( "\"rows\":[ " ); stringBuilder.Append( "]" ); stringBuilder.Append( "," ); stringBuilder.Append( "\"total\":" ); stringBuilder.Append(total); stringBuilder.Append( ",\"footer\":[" ); stringBuilder.Append( "]" ); stringBuilder.Append( "}" ); return stringBuilder.ToString(); } stringBuilder.Append( "{ " ); stringBuilder.Append( "\"rows\":[ " ); for ( int i = 0; i < dt.Rows.Count; i++) { stringBuilder.Append( "{ " ); for ( int j = 0; j < dt.Columns.Count; j++) { if (j < dt.Columns.Count - 1) { stringBuilder.Append( string .Concat( new string [] { "\"" , dt.Columns[j].ColumnName.ToString().ToLower(), "\":\"" , this .JsonCharFilter(dt.Rows[i][j].ToString()), "\"," })); } else { if (j == dt.Columns.Count - 1) { stringBuilder.Append( string .Concat( new string [] { "\"" , dt.Columns[j].ColumnName.ToString().ToLower(), "\":\"" , this .JsonCharFilter(dt.Rows[i][j].ToString()), "\"" })); } } } if (i == dt.Rows.Count - 1) { stringBuilder.Append( "} " ); } else { stringBuilder.Append( "}, " ); } } stringBuilder.Append( "]" ); stringBuilder.Append( "," ); stringBuilder.Append( "\"total\":" ); stringBuilder.Append(total); if (ShowFooter && fields.Length > 0 && inputfiled.Length > 0) { stringBuilder.Append( ",\"footer\":[{" ); stringBuilder.Append( string .Concat( new string [] { "\"" , inputfiled, "\":\"<span style=‘color:red; font-weight:bold‘>" , ShowMessage, "</span>\"," })); string [] array = fields.Split( new char [] { ‘,‘ }); for ( int k = 0; k < array.Length; k++) { if (k < array.Length - 1) { stringBuilder.Append( string .Concat( new object [] { "\"" , array[k], "\":\"" , dt.Compute( "sum(" + array[k] + ")" , filter), "\"," })); } else { stringBuilder.Append( string .Concat( new object [] { "\"" , array[k], "\":\"" , dt.Compute( "sum(" + array[k] + ")" , filter), "\"" })); } } stringBuilder.Append( "}]" ); } stringBuilder.Append( "}" ); return stringBuilder.ToString(); } |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。