C# 将List中的数据导入csv文件中
//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 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;
}

C# 将List中的数据导入csv文件中的更多相关文章
- 如何使用免费控件将Word表格中的数据导入到Excel中
我通常使用MS Excel来存储和处理大量数据,但有时候经常会碰到一个问题—我需要的数据存储在word表格中,而不是在Excel中,这样处理起来非常麻烦,尤其是在数据比较庞大的时候, 这时我迫切地需要 ...
- phpexcel的写操作将数据库中的数据导入到excel中
这个版本据说是可以支持excel2007,但是我使用2007编辑的xlsx是无法获得该库的支持.于是乎我就将它转化为2003.感觉支持地很好. 下面介绍一下具体的使用: require_once('. ...
- 如何将数据库中的数据导入到Solr中
要使用solr实现网站中商品搜索,需要将mysql数据库中数据在solr中创建索引. 1.需要在solr的schema.xml文件定义要存储的商品Field. 商品表中的字段为: 配置内容是: < ...
- 小技巧之“将Text文件中的数据导入到Excel中,这里空格为分割符为例”
1.使用场景 将数据以文本导出后,想录入到Excel中,的简便方案, 起因:对于Excel的导出,Text导出明显会更方便些 2.将Text文件中的数据导入到Excel中,这里空格为分割符为例的步骤 ...
- MongoDB:数据导入CSV文件之错误记录
测试主机1:Windows 10,MongoDB 3.6.3,WPS 10.1,Notepad++ 7.5.3, 测试主机2:Ubuntu 16.04,MongoDB 4, 今天测试了将数据从文件—— ...
- Jmeter beanshell把数据写入csv文件中,最后清除csv数据
有时候我们需要使用jmeter去结合csv文件去做一些简单的数据驱动处理: 例如把数据库数据黏贴到csv文件中或者把网页上的数据填入到csv文件中: 直接我一般是用手自己黏贴复制过csv文件中,比较麻 ...
- mysql 导入 csv文件中数据,只能导入第一行
用workbench导入csv数据,只能导入数据的第一行,也就是标注每一列的列名的那一行.但问题是,每次导入完成时,系统提示已经导入了500条记录(这个文件中的确有500条记录),可是刷新数据库后打开 ...
- Jmeter自动化测试 数据驱动测试,将数据存入csv文件中来调用,或将数据存在DB中进行调用
1. 将测试的用例名称,测试请求方式,测试链接,预置数据,断言等都放到excel中,然后转成csv格式,在用Jmeter带的csv数据配置文件导入 运行之前将线程组中配置,线程数设置为1,循环的次数设 ...
- python将oracle中的数据导入到mysql中。
一.导入表结构.使用工具:navicate premium 和PowerDesinger 1. 先用navicate premium把oracle中的数据库导出为oracle脚本. 2. 在Power ...
随机推荐
- WEB典型应用
- Java模拟post-get提交
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...
- Git之”make sure you have the correct access…”
git 命令在windows下无法使用pull.fetch.push等命令,提示 “please make sure you have the correct access and the repos ...
- POJ 3414 Pots(BFS)
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu Description You are g ...
- ap143 led修改
以前的硬件版本只使用了一个eth口,新的板子增加了一个eth口,并且增加了响应的通信时使用的灯. led修改涉及到一下的内容: (1)led 对应的gpio口(这个需要根据原理图来定义) 需要修改的源 ...
- 小例子解释wait与notify的区别
系统慢可能有很多种原因,硬件资源不足,语句不优化,结构设计不合理,缺少必要的运维方式.所有的这些问题都可以在阻塞与等待中看出端倪,发现并解决问题. 首先是下载开发工具,磨刀不误砍材工.点此下载 这是一 ...
- Request for the permission of type异常
调用wcf调用的时候引发一个错误,错误信息如下: <Message>Request for the permission of type 'System.Configuration.Con ...
- adb shell dumpsys
adb shell dumpsys activity activities -- class/packagename adb shell dumpsys batterystate --reset ...
- Jmeter学习笔记
Jmeter安装 Jmeter组件介绍 Jmeter
- iosTableView 局部全部刷新以及删除编辑操作
局部刷新方法 添加数据 NSArray *indexPaths = @[ [NSIndexPath indexPathForRow:0 inSection:0], [NSIndexPath index ...