One Is All 2019-08-01 13:07 采纳率: 0%
浏览 2490

C#保存数组的数据到csv文件

图片说明图片说明
连接设备读取数据,以动态生成的textbox写数据,一共有25个box,对应写入25个数据,现在将数据生成csv文件,只能写入头一个数据,其余的24个数据也是第一个数据,怎么生成正确的25个数据。谢谢。

  • 写回答

2条回答 默认 最新

  • donghe1234566 2019-08-01 13:15
    关注

    C# 将List中的数据导入csv文件中
    将数据保存至文件中,是一个比较常用的功能,数据源可以是多种形式,文件也可以是多种。

    这里简单的介绍将List数据导入到CSV文件中的方法。

    代码如下所示:

    Student类:

    复制代码
    public class Student
    {
    private string id;
    public string Id { get { return id; } set { id = value; } }

        private string name;
        public string Name { get { return name; } set { name = value; } }
    
        private string age;
        public string Age { get { return age; } set { age = value; } }
    }
    

    复制代码

    模拟一个简单的List数据源:

    复制代码
    private List GetStudentData()
    {
    List studentList = new List();

            Student s1 = new Student();
            s1.Id = "1";
            s1.Name = "haha";
            s1.Age = "10";
    
            Student s2 = new Student();
            s2.Id = "2";
            s2.Name = "xixi";
            s2.Age = "20";
    
            Student s3 = new Student();
            s3.Id = "3";
            s3.Name = "lolo";
            s3.Age = "30";
    
            studentList.Add(s1);
            studentList.Add(s2);
            studentList.Add(s3);
    
            return studentList;
        }
    

    复制代码

    根据文件路径创建相应的文件:

    复制代码
    ///
    /// Create target file
    ///
    /// folder
    /// folder name
    /// file extension
    /// file path
    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文件中(宗旨就是在一行数据中以逗号进行分割):

    复制代码
    ///
    /// Save the List data to CSV file
    ///
    /// data source
    /// file path
    /// success flag
    private bool SaveDataToCSVFile(List 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 studentList = GetStudentData();
    string filePath = CreateFile(folder, fileName, fileExtension);
    bool flag = SaveDataToCSVFile(studentList, filePath);
    return flag;
    }
    复制代码

    评论

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入