c# List与Csv文件互转(特性实现)

c# List与Csv文件互转(特性实现)

有个自定义类NPOIMemoryStream ,去见https://blog.csdn.net/Daniel_yka/article/details/124708404?spm=1001.2014.3001.5502

public static class CsvOrTsvHelper
	{
		/// List转流(csv,tsv格式)
        /// </summary>
        /// <param name="fileFormat">文件格式</param>
        /// <returns>success flag</returns>
        public static NPOIMemoryStream SaveDataToCSVFile<T>(this List<T> dataList, string fileFormat) where T : class
        {
            string separator;
            if (fileFormat.ToLower() == "csv")
                separator = ",";
            else
                separator = "\t";

            NPOIMemoryStream stream = new NPOIMemoryStream();
            StreamWriter writer = new StreamWriter(stream);

            StringBuilder strColumn = new StringBuilder();
            StringBuilder strValue = new StringBuilder();
            var tp = typeof(T);
            PropertyInfo[] props = tp.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            int[] filter = new int[props.Length];

            try
            {
                //标题
                for (int i = 0; i < props.Length; i++)
                {
                    var itemPropery = props[i];
                    DescriptionAttribute labelAttr = itemPropery.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault() as DescriptionAttribute;
                    if (null != labelAttr)
                    {
                        strColumn.Append(labelAttr.Description);
                        strColumn.Append(separator);
                    }
                    else
                    {
                        filter[i] = 1;
                    }
                }
                strColumn.Remove(strColumn.Length - 1, 1);
                writer.WriteLine(strColumn.ToString());

                //内容
                for (int i = 0; i < dataList.Count; i++)
                {
                    var model = dataList[i];
                    strValue.Clear();
                    for (int m = 0; m < props.Length; m++)
                    {
                        var itemPropery = props[m];
                        if (filter[m] == 1) continue;

                        var val = itemPropery.GetValue(model, null);
                        if (m == 0)
                        {
                            strValue.Append(val);
                        }
                        else
                        {
                            strValue.Append(separator);
                            strValue.Append(val);
                        }
                    }
                    writer.WriteLine(strValue.ToString());
                }

                writer.Flush();
                stream.Position = 0;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Dispose();
                }
            }

            return stream;
        }
		/// <summary>
        /// 流转list
        /// </summary>
        /// <param name="fileStream">文件流</param>
        /// <returns></returns>
        public static List<T> CsvOrTsvConvertToList<T>(this Stream fileStream, bool isCsv = true)
        {
            List<T> list = new List<T> { };
            StreamReader sr = new StreamReader(fileStream, Encoding.GetEncoding("utf-8"));

            string tempText = "";
            int Rows = 1; //标注第几行
            //缓存列索引对应属性名
            Dictionary<int, string> colIndexMapName = new Dictionary<int, string>();

            while ((tempText = sr.ReadLine()) != null)
            {
                string[] arr = CsvOrTsvstrToArry(tempText, isCsv ? ',' : '\t');
                var obj = Activator.CreateInstance<T>();
                Type type = obj.GetType();
                //获取所有公共字段名
                PropertyInfo[] peroperties = type.GetProperties();
                if (Rows == 1)
                {
                    for (int i = 0; i < arr.Length; i++)
                    {
                        foreach (var property in peroperties)
                        {
                            var proName = property.Name;
                            object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true);
                            if (objs != null && objs.Length > 0)
                            {
                                var description = ((DescriptionAttribute)objs[0]).Description;
                                if (description == arr[i])
                                {
                                    colIndexMapName.Add(i, proName);
                                }
                            }
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < arr.Length; i++)
                    {
                        foreach (var property in peroperties)
                        {
                            if (colIndexMapName.ContainsKey(i) && property.Name == colIndexMapName[i])
                            {
                                ExcelHelper.ConvertByPropTypeName(property, obj, arr[i]);
                            }
                        }
                    }
                    list.Add(obj);
                }
                Rows++;
            }

            return list;
        }

        private static string[] CsvOrTsvstrToArry(string splitStr, char ignoreChar)
        {
            splitStr = splitStr.Replace("\"\"", "'");
            var newstr = string.Empty;
            List<string> sList = new List<string>();

            bool isSplice = false;
            string[] array = splitStr.Split(new char[] { ignoreChar });
            foreach (var str in array)
            {
                if (!string.IsNullOrEmpty(str) && str.IndexOf('"') > -1)
                {
                    var firstchar = str.Substring(0, 1);
                    var lastchar = string.Empty;
                    if (str.Length > 0)
                    {
                        lastchar = str.Substring(str.Length - 1, 1);
                    }
                    if (firstchar.Equals("\"") && !lastchar.Equals("\""))
                    {
                        isSplice = true;
                    }
                    if (lastchar.Equals("\""))
                    {
                        if (!isSplice)
                            newstr += str;
                        else
                            newstr = newstr + ignoreChar + str;

                        isSplice = false;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(newstr))
                        newstr += str;
                }

                if (isSplice)
                {
                    //添加因拆分时丢失的逗号
                    if (string.IsNullOrEmpty(newstr))
                        newstr += str;
                    else
                        newstr = newstr + ignoreChar + str;
                }
                else
                {
                    sList.Add(newstr.Replace("\"", "").Replace("'", "\"").Trim());//去除字符中的双引号和首尾空格
                    newstr = string.Empty;
                }
            }

            return sList.ToArray();
        }
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用 C# 中的 Newtonsoft.Json 库来将 JSON 转换CSV 文件。下面是一个简单的示例代码: ```csharp using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; class Program { static void Main(string[] args) { // 读取 JSON 文件内容 string json = File.ReadAllText("input.json"); // 将 JSON 解析为对象 var data = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json); // 获取所有属性名作为 CSV 的表头 var headers = new List<string>(data[0].Keys); // 创建 CSV 文件并写入表头 using (var writer = new StreamWriter("output.csv")) { writer.WriteLine(string.Join(",", headers)); // 逐行写入数据 foreach (var item in data) { var values = new List<string>(); // 按照表头的顺序获取每个属性的值 foreach (var header in headers) { values.Add(item.ContainsKey(header) ? item[header] : ""); } writer.WriteLine(string.Join(",", values)); } } Console.WriteLine("CSV 文件已生成!"); } } ``` 在这个示例中,我们假设输入的 JSON 数据是一个包含多个对象的数组,每个对象都是一个字典。通过使用 Newtonsoft.Json 库,我们可以将 JSON 字符串反序列化为一个包含字典的列表。然后,我们提取出所有属性名作为 CSV 文件的表头,并逐行写入每个对象的属性值。 记得替换代码中的 `input.json` 和 `output.csv` 分别为你的输入 JSON 文件和输出 CSV 文件的路径。确保你已经将 Newtonsoft.Json 包添加到你的项目中。 希望对你有所帮助!如果有任何进一步的问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值