json 转成 csv (-使用WPF做的demo,利用datatable和序列化转换数据)

1.打开文件路径选择文件

   var openFileDialog = new Microsoft.Win32.OpenFileDialog();
            var result = openFileDialog.ShowDialog();
            if (result == true)
            {
                save_csv_path = openFileDialog.FileName;
            }
2.创建datatable
   DataTable tb = new DataTable();         
        tb.Columns.Add("No", typeof(string)); // 添加列名
   DataRow dr = tb.NewRow();
        dr["No"] = i.ToString();//添加行,
        tb.Rows.Add(dr); //千万别忘记这句话,把一行的数据添加到datatable中
3. json转csv  click点击事件
private void to_csv_Click(object sender, RoutedEventArgs e) //WPF项目的click 点击事件
        {
            using (System.IO.StreamReader file = System.IO.File.OpenText(open_json_path))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JObject o = (JObject)JToken.ReadFrom(reader);
                   //将json文件中的数据转成JObject对象
                    foreach (var x in o)
                    {
                       
                        if (x.Key.Equals("webReport"))
                        {
                            json_datatable = x.Value.ToString();
 
                        }
      //在页面显示json数据
                        all_data.Text = all_data.Text + "\r\n" + "***" + string.Format("{0} : {1}", x.Key, x.Value);
                    }
                 
                }
            }
   //序列化
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
   //创建一个类,和json中需要提取出来的数据类型保持一直,BaseInformation请参考4.数据类型
            BaseInformation baseInformation=new BaseInformation();
            List<ExecutedStep> executedStep=new List<ExecutedStep>();
            //TO DO json_datatable需要做异常处理
            JObject obj = JObject.Parse(json_datatable);
            foreach (var item in obj)
            {
                if (item.Key.Equals("BasicInfo"))
                {
                  //<BaseInformation>序列化的类型很重要,要和json中的数据对应上
                    baseInformation = javaScriptSerializer.Deserialize<BaseInformation>(item.Value.ToString());
                }
                if (item.Key.Equals("ExecutionDetails"))
                {
                    executedStep = javaScriptSerializer.Deserialize<List<ExecutedStep>>(item.Value.ToString());
                }
            }
            //创建列名
            DataTable tb = new DataTable();         
            tb.Columns.Add("No", typeof(string));
            tb.Columns.Add("Title", typeof(string));
            tb.Columns.Add("TaskType", typeof(string));
            tb.Columns.Add("Condition", typeof(string));
            tb.Columns.Add("Status", typeof(string));
            tb.Columns.Add("Elapsed", typeof(string));
            tb.Columns.Add("ActualBeginTime", typeof(string));
            tb.Columns.Add("ActualEndTime", typeof(string));
            tb.Columns.Add("Result", typeof(string) );//typeof(JObject)
   // 向表中添加数据
            for (int i = 0; i < executedStep.Count; i++)
            {
              //executedStep中的ExecutedStep中的数据存入datatable中
                DataRow dr = tb.NewRow();
                dr["No"] = i.ToString();
                dr["Title"]= executedStep[i].Title;
                dr["TaskType"]=executedStep[i].TaskType;
                dr["Condition"]=executedStep[i].Condition;
                dr["Status"]=executedStep[i].Status;
                dr["Elapsed"] = executedStep[i].ExecTime ;
                dr["ActualBeginTime"]=executedStep[i].StartTime;
                dr["ActualEndTime"]= executedStep[i].EndTime;
                Dictionary<string, string> dict_Result = executedStep[i].Result;
                dr["Result"]= "result:"+dict_Result["result"] + "mediaFile:" + dict_Result["mediaFile"];//typeof(JObject)
                tb.Rows.Add(dr);
            }
            Tools.jsonToCsv(baseInformation, tb, this.open_json_path);        
        }
4.工具类Tools中jsonToCsv
       public static void jsonToCsv(BaseInformation baseInformation,DataTable table, string file)
        {
            try
            {
            DirectoryInfo json_pathInfo = new DirectoryInfo(file);
            file = json_pathInfo.Parent.FullName+"\\" + baseInformation.TFName.ToString() + ".csv";
            string title = baseInformation.TFName.ToString();
            FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
            //编写第一行数据
            sw.WriteLine(baseInformation.TFName);
            //编写第二行数据
            string baseInfo = constant_Info.Priority.ToString() + ":" + baseInformation.Priority + " "+ baseInformation.AssignedTime;//中间省略n个字段
            sw.WriteLine(baseInfo);
            for (int i = 0; i < table.Columns.Count; i++)
            {
                sw.Write(table.Columns[i].ColumnName);
                sw.Write(","); //分割列
            }
            sw.WriteLine("");
            sw.Write("\t");
            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    sw.Write(row[i].ToString());
                    sw.Write(",");
                }
                sw.WriteLine("");
                sw.Write("\t");
            }
            sw.Close();
            fs.Close();
               
            }
           
            catch (Exception)
            {
                throw;
            }
        }
5.BaseInformation 类
public class BaseInformation
    {
        private string siteId;
        private string reportId;
        private string assignedTFID;
        private string version;
       ///。。。省略中间n个字段
        private string zipfilename;
        public string SiteId { get { return this.siteId; } set{ this.siteId = value; } }
        public string ReportId { get { return this.reportId; } set { this.reportId = value; } }
        public string AssignedTFID { get { return this.assignedTFID; } set { this.assignedTFID = value; } }
        public string Version { get { return this.version; } set { this.version = value; } }
       ///。。。省略中间n个字段
        public string ZipFileName { get { return this.zipfilename; } set { this.zipfilename = value; } }
    }
6.ExecutedStep类
public class ExecutedStep
    {
        private String no;
        private String taskid;
       ///。。。省略中间n个字段
        private String title;
        private Dictionary<string, string> result;
        public String No { get { return no; } set { this.no = value; } }
        public String TaskID { get {return  this.taskid; } set {this.taskid=value; } }
       ///。。。省略中间n个字段
        public String Title { get { return this.title; } set { this.title = value; } }
        public Dictionary<string,string> Result { get { return result; } set { this.result = value; } }
    }
posted @ 2019-07-31 09:43  婧秋-fool  阅读(312)  评论(0编辑  收藏  举报