//http://www.cnblogs.com/mingmingruyuedlut/archive/2013/01/20/2849906.html

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<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 namefor(int i = 0; i < studentList.Count; i++){strValue.Remove(0, strValue.Length); //clear the temp row valuestrValue.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;}

转载于:https://www.cnblogs.com/TNSSTAR/p/4283855.html

C# 将List中的数据导入csv文件中相关推荐

  1. mysql导入csv文件 第一行有问题_mysql 导入 csv文件中数据,只能导入第一行

    用workbench导入csv数据,只能导入数据的第一行,也就是标注每一列的列名的那一行. 但问题是,每次导入完成时,系统提示已经导入了500条记录(这个文件中的确有500条记录),可是刷新数据库后打 ...

  2. python获取mysql中的数据供js调用_python 读取mysql数据至csv文件中,并发送邮件

    test 代码: #coding:utf-8 ''' Created on 2019年2月18日 @author: Administrator ''' import ConfigParser impo ...

  3. 如何在ex表格导入php_怎么使用php把表格中的数据导入到excel中,php如何快速导入excel表格数据...

    php怎么导入大量数据的excel php导出数据的Excel: PHP从数据库分多次读取100万行记录,和分将100万入文本文件都没问题 Excel可以支100万行记录,Excel 2003最大支持 ...

  4. python爬虫案例分析:爬取肯德基门店地址数据导入csv文件并最终用excel文档呈现

    1.用到的模块: requests pprint csv 2.找到肯德基门店网站进入门店位置页面后,打开抓包工具,找到response中包含所需信息的正确的url信息 3. 导入地址url 4.为防止 ...

  5. lisp倒入excel数据画图_如何将EXCEL中的数据导入到CAD中,绘制成曲线|

    如何将EXCEL中的数据导入到CAD中,绘制成曲线 如果不用软件,只用CAD自身功能的话可以通过多段线生成你需要的曲线.你给出你的曲线函数,我给你生成曲线坐标以及CAD能自动绘制的文件格式 怎样将ca ...

  6. lisp倒入excel数据画图_Excel表格数据在cad画出图形-如何将EXCEL中的数据导入到CAD中,绘制成曲线...

    如何实现excel的数据与cad图形的关联 举个例 假如根据B2单元格中的半径画一个圆 : 打开EXCEL,在B2单元格中输个圆的半径100 按快捷Alt F11打开VBA编辑器并插入一个模块 引用C ...

  7. 将DataTable中的数据导入到数据库中

    上次在根据excel的文件的路径提取其中表的数据到DataSet中 一文中介绍了将Excel文件中的数据读取到DataSet中的方法,今天我来介绍下我曾经在项目中用到的一个将DataTable中的数据 ...

  8. 查询oracle数据库的表格数据类型,excel表格中如何查询数据库数据类型-我想把excel表格中的数据导入oracle数据库中,想在......

    在excel表里,什么是:字段.记录.数据类型.多工... declare @t table(id numeric(18,2)) insert into @t SELECT   col1 FROM   ...

  9. 将mysql中的数据导入到sqlite3中

    不知道如何创建数据库的可以先看这篇: https://blog.csdn.net/blackei/article/details/80403272 当我们使用固定的信息时,比如省市信息,区划代码,物品 ...

最新文章

  1. 一口气说出 5 种 IO 模型,蒙圈了!
  2. 黄聪:基于Linq to edmx的实体数据模型(EDM)类名批量修改工具
  3. c#读取xml文件配置文件Winform及WebForm-Demo具体解释
  4. python实现文件夹增量同步
  5. ubuntu 16.04 安装MySQL Workbench
  6. 网页滚动条上下滚动固定元素左右不固定之sticky
  7. Power Designer逆向工程连接数据库创建pdm-oracle
  8. 有序关系中的极大元与极小元
  9. java 加入音乐_如何实现java插入背景音乐
  10. mathtype 7.4.10.53中文版安装教程,以及如何将MathType嵌入到word中
  11. 高阶面试官应掌握哪些面试技巧
  12. 酷派+k1+rom+android+4.4,酷派新品牌怎么样?ivvi K1全面评测
  13. mac M1安装SVN错误Error: Command failed with exit 128: git
  14. 白盒测试和黑盒测试(感谢东子哥作答)
  15. BAT大牛带你深度剖析Android10大开源框架
  16. 绿幕背景视频抠图替换
  17. Android强制竖屏
  18. SCM工具-Git的相关指令
  19. DB 查询分析器 6.03 在Windows 8 上安装与运行演示
  20. MOS管一级代理 功成半导体 CPD50R1K1G3

热门文章

  1. px4原生源码学习三--Nuttx实时操作系统的使用
  2. 滑动窗口 - 替换后的最长重复字符
  3. tcp三次握手四次挥手(及原因)详解
  4. java 2wei shuzu_JavaScript 2维数组(JavaScript 2 dimension array)
  5. 计算机hub体系部件,原来如此!USB Hub接口为啥都是4个7个或10个?
  6. oracle中如何调用存储过程
  7. Xquery 被设计用来查询 XML 数据
  8. 201803-2碰撞的小球
  9. 用Python操作Redis
  10. dax 计算某一列重复出现次数