C# 將List中的資料匯入csv檔案中

來源:互聯網
上載者:User

將資料儲存至檔案中,是一個比較常用的功能,資料來源可以是多種形式,檔案也可以是多種。

這裡簡單的介紹將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<Student> GetStudentData()        {            List<Student> studentList = new List<Student>();            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;        }

 

根據檔案路徑建立相應的檔案:

        /// <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;        }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.