需求:有一个log文件,需要整理成Excel,日志文件里面的数据都是json字符串

思路是,把Json字符串转换成DataTable,然后导出到Excel

在网上找了一些资料,整理了以下三种类型的Json

一、Json转换DataTable

1.处理简单Json:

[{"mac":"20:f1:7c:c5:cd:80","rssi":"-86","ch":""},{"mac":"20:f1:7c:c5:cd:85","rssi":"-91","ch":""}]
        /// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static DataTable ToDataTableTwo(string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > )
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == )
{
result = dataTable;
return result;
}
//Columns
if (dataTable.Columns.Count == )
{
foreach (string current in dictionary.Keys)
{
dataTable.Columns.Add(current, dictionary[current].GetType());
}
}
//Rows
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
}
dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
}
}
}
catch
{
}
result = dataTable;
return result;
}

2.处理复杂Json

[{"id":"00e58d51","data":[{"mac":"20:f1:7c:c5:cd:80","rssi":"-86","ch":""},{"mac":"20:f1:7c:c5:cd:85","rssi":"-91","ch":""}]},
{"id":"00e58d53","data":[{"mac":"bc:d1:77:8e:26:78","rssi":"-94","ch":""},{"mac":"14:d1:1f:3e:bb:ac","rssi":"-76","ch":""},{"mac":"20:f1:7c:d4:05:41","rssi":"-86","ch":""}]}]
        /// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static DataTable ToDataTable(string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > )
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == )
{
result = dataTable;
return result;
}
//Columns
if (dataTable.Columns.Count == )
{
foreach (string current in dictionary.Keys)
{
if (current != "data")
dataTable.Columns.Add(current, dictionary[current].GetType());
else
{
ArrayList list = dictionary[current] as ArrayList;
foreach (Dictionary<string, object> dic in list)
{
foreach (string key in dic.Keys)
{
dataTable.Columns.Add(key, dic[key].GetType());
}
break;
}
}
}
}
//Rows
string root = "";
foreach (string current in dictionary.Keys)
{
if (current != "data")
root = current;
else
{
ArrayList list = dictionary[current] as ArrayList;
foreach (Dictionary<string, object> dic in list)
{
DataRow dataRow = dataTable.NewRow();
dataRow[root] = dictionary[root];
foreach (string key in dic.Keys)
{
dataRow[key] = dic[key];
}
dataTable.Rows.Add(dataRow);
}
}
}
}
}
}
catch
{
}
result = dataTable;
return result;
}

3.处理不规则Json,因为列并不确定,所以直接定义列,不动态生成

[{"id":"00e58d53","data":[{"mac":"34:b3:54:89:86:64","rssi":"-86","ch":""},{"mac":"50:bd:5f:02:80:44","rssi":"-90","ch":""}]},
{"id":"00ccda81","data":[{"mac":"bc:46:99:4e:96:c8","rssi":"-92","ch":""},{"mac":"bc:3a:ea:fc:77:6c","rssi":"-93","ch":"","ds":"Y","essid":"vienna hotel WIFI"}]}]
       /// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static DataTable ToDataTable(string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
dataTable.Columns.Add("id");
dataTable.Columns.Add("mac");
dataTable.Columns.Add("rssi");
dataTable.Columns.Add("ch");
dataTable.Columns.Add("ts");
dataTable.Columns.Add("tmc");
dataTable.Columns.Add("tc");
dataTable.Columns.Add("ds");
dataTable.Columns.Add("essid");
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > )
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == )
{
result = dataTable;
return result;
}//Rows
string root = "";
foreach (string current in dictionary.Keys)
{
if (current != "data")
root = current;
else
{
ArrayList list = dictionary[current] as ArrayList;
foreach (Dictionary<string, object> dic in list)
{
DataRow dataRow = dataTable.NewRow();
dataRow[root] = dictionary[root];
foreach (string key in dic.Keys)
{
dataRow[key] = dic[key];
}
dataTable.Rows.Add(dataRow);
}
}
}
}
}
}
catch
{
}
result = dataTable;
return result;
}

二、导出Excel

        /// <summary>
/// 导出Excel
/// </summary>
/// <param name="table"></param>
/// <param name="file"></param>
public void dataTableToCsv(DataTable table, string file)
{
string title = "";
FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
for (int i = ; i < table.Columns.Count; i++)
{
title += table.Columns[i].ColumnName + "\t"; //栏位:自动跳到下一单元格
}
title = title.Substring(, title.Length - ) + "\n";
sw.Write(title);
foreach (DataRow row in table.Rows)
{
string line = "";
for (int i = ; i < table.Columns.Count; i++)
{
line += row[i].ToString().Trim() + "\t"; //内容:自动跳到下一单元格
}
line = line.Substring(, line.Length - ) + "\n";
sw.Write(line);
}
sw.Close();
fs.Close();
}

三、调用实现,数据导出到Excel

        protected void Button1_Click(object sender, EventArgs e)
{
string str = File.ReadAllText(@"C:\Users\Admin\Desktop\json.txt");
DataTable dt = ToDataTable(str);
this.dataTableToCsv(dt, @"E:\json.xls"); //调用函数
}

C#Json转DataTable的更多相关文章

  1. #region Json转DataTable

    #region  Json转DataTable        private DataTable Json2Dtb(string json)        {            JavaScrip ...

  2. DateTable与List<T>相互转换 及JSON与DataTable(DataSet)相互转化

    http://www.360doc.com/content/13/0712/09/10504424_299336674.shtml Linq处理List数据 http://blog.163.com/l ...

  3. json转datatable(正则表达式的方法)

    /// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson" ...

  4. DataTable转Json,Json转DataTable

    // 页面加载时 /// </summary> /// <param name="sender"></param> /// <param ...

  5. c# 将json转换为DataTable

    /// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson" ...

  6. json与DataTable相互转换

    首先我们看看 Newtonsoft.Json.JsonConvert 是怎么完成的: DataTable table = new DataTable(); table.Columns.Add(&quo ...

  7. PCB MS SQL 存储过程(CLR) 实现Json转DataTable表的方法

    一.准备需转为DataTable的json字符串 原json字符串数据 [{"TechName":"ECN","TechNo":" ...

  8. c#常用的Datable转换为json,以及json转换为DataTable操作方法

    #region  DataTable 转换为Json字符串实例方法 /// <summary> /// GetClassTypeJosn 的摘要说明 /// </summary> ...

  9. JSON与DataTable(DataSet)相互转化

    public static string CreateJsonParameters(DataTable dt)        {            /* /******************** ...

随机推荐

  1. 原生js移动端滑动事件

    移动端触屏滑动的效果其实就是图片轮播,在PC的页面上很好实现,绑定click和mouseover等事件来完成.但是在移动设备上,要实现这种轮播的效果,就需要用到核心的touch事件.处理touch事件 ...

  2. 十倍效能提升——Web 基础研发体系的建立

    1 导读 web 基础研发体系指的是, web 研发中一线工程师所直接操作的技术.工具,以及所属组织架构的总和.在过去提升企业研发效能的讨论中,围绕的主题基本都是——”通过云计算.云存储等方式将底层核 ...

  3. selenium-01 搭建环境

    很老套,但是不得不做的事. selenium的发展史,具体的虫师大大已经写得很具体了:http://www.cnblogs.com/fnng/p/3653793.html 1.第一种使用的姿势就是ID ...

  4. 深入java虚拟机学习 -- 内存管理机制

    前面说过了类的加载机制,里面讲到了类的初始化中时用到了一部分内存管理的知识,这里让我们来看下Java虚拟机是如何管理内存的. 先让我们来看张图 有些文章中对线程隔离区还称之为线程独占区,其实是一个意思 ...

  5. Android开发从GC root分析内存泄漏

    我们常说的垃圾回收机制中会提到GC Roots这个词,也就是Java虚拟机中所有引用的根对象.我们都知道,垃圾回收器不会回收GC Roots以及那些被它们间接引用的对象.但是,对于GC Roots的定 ...

  6. Django+xadmin打造在线教育平台(六)

    九.课程章节信息 9.1.模板和urls 拷贝course-comments.html 和 course-video.html放入 templates目录下 先改course-video.html,同 ...

  7. linux服务器中毒可疑进程sfewfesfs CPU80%

    我用的是wdlinux, 难免会有漏洞,不知怎么就被莫名其妙地给入侵了,而且还频繁发包.下面是我查看攻击机器的整个过程. 首先跟客户要了root密码登录看,第一个命令是就top cd /proc/25 ...

  8. 数据库 --> SQL 和 NoSQL 的区别

    SQL 和 NoSQL 的区别   一.概念 SQL (Structured Query Language) 数据库,指关系型数据库.主要代表:SQL Server,Oracle,MySQL(开源), ...

  9. sqlite语句主页

    因为现在android手机用sqlite数据,但是sql语句很多和sqlserver不同..所以还是把官网记下以便开发:http://www.sqlite.org/lang.html

  10. phpcms v9 搜索结果列表页时间显示1970问题解决方案

    对于喜欢用phpcms v9 的小伙伴来说,在调用时间时,总会出现时间1970这样的问题,对于这个问题,网上的说法很多,内容页时间显示通常不会问题,搜索结果页就不行了,通过总结,发现使用{format ...