C# 将List中的数据导入csv文件中

将数据保存至文件中,是一个比较常用的功能,数据源可以是多种形式,文件也可以是多种。
这里简单的介绍将List数据导入到CSV文件中的方法。
代码如下所示:
Student类:
public class Student
    {
        public string Id { get ; set ; }

        public string Name { get ; set ; }

        public string Age { get ; set ; }
    }
模拟一个简单的List数据源:
private List<Student> GetStudentData()
{
	List<Student> studentList = new List<Student>(){
		new Student(){Id = "1",Name = "haha",Age = "10"},
		new Student(){Id = "2",Name = "xixi",Age = "20"},
		new Student(){Id = "3",Name = "lolo",Age = "30"},
	};
    return studentList;
}
根据文件路径创建相应的文件:
		/// <summary>
        /// Create target file
        /// </summary>
        /// <param name="folder">folder</param>
        /// <param name="fileName">folder name</param>
        /// <param name="fileExtension">file extension</param>
        /// <returns>file path</returns>
        private string CreateFile(string folder, string fileName, string fileExtension)
        {
            FileStream fs = null;
            string filePath = folder + fileName + "." + fileExtension;
            try
            {
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                fs = File.Create(filePath);
            }
            catch (Exception ex)
            { }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
            return filePath;
        }
获取类的属性集合(以便生成CSV文件的所有Column标题):
private PropertyInfo[] GetPropertyInfoArray()
        {
            PropertyInfo[] props = null;
            try
            {
                Type type = typeof(EricSunApp.Student);
                object obj = Activator.CreateInstance(type);
                props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            catch (Exception ex)
            { }
            return props;
        }
对List进行遍历,将数据导入CSV文件中(宗旨就是在一行数据中以逗号进行分割):
/// <summary>
        /// Save the List data to CSV file
        /// </summary>
        /// <param name="studentList">data source</param>
        /// <param name="filePath">file path</param>
        /// <returns>success flag</returns>
        private bool SaveDataToCSVFile(List<Student> studentList, string filePath)
        {
            bool successFlag = true;

            StringBuilder strColumn = new StringBuilder();
            StringBuilder strValue = new StringBuilder();
            StreamWriter sw = null;
            PropertyInfo[] props = GetPropertyInfoArray();

            try
            {
                sw = new StreamWriter(filePath);
                for(int i = 0; i < props.Length; i++)
                {
                    strColumn.Append(props[i].Name);
                    strColumn.Append(",");
                }
                strColumn.Remove(strColumn.Length - 1, 1);
                sw.WriteLine(strColumn);    //write the column name

                for(int i = 0; i < studentList.Count; i++)
                {
                    strValue.Remove(0, strValue.Length); //clear the temp row value
                    strValue.Append(studentList[i].Id);
                    strValue.Append(",");
                    strValue.Append(studentList[i].Name);
                    strValue.Append(",");
                    strValue.Append(studentList[i].Age);
                    sw.WriteLine(strValue); //write the row value
                }
            }
            catch(Exception ex)
            {
                successFlag = false;
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                }
            }

            return successFlag;
        }
简单例举具体的调用:
private bool EricSunExportData(string folder, string fileName, string fileExtension)
        {
            List<Student> studentList = GetStudentData();
            string filePath = CreateFile(folder, fileName, fileExtension);
            bool flag = SaveDataToCSVFile(studentList, filePath);
            return flag;
        }
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值