C#CSV文件读写的实现.docx
第
C#CSV文件读写的实现
目录为什么要用csv文件一、DataTable数据写入CSV文件二、读取CSV文件到DataTable三、修改文件名称四、CSV文件的数据写入CSV是一种通用的、相对简单的文件格式,最广泛的应用是在程序之间转移表格数据,而这些程序本身是在不兼容的格式上进行操作的。那么,C#如何读取和写入csv格式文件呢?CSV数据格式并没有非常统一的标准但是为了避免出错我们在开发的时候统一格式是这样的:
name,pwd,date
张三,123,2015-09-30
接下来代码处理中默认格式都是这样的
为什么要用csv文件
这就涉及到数据互通的问题,有些程序支持的表格数据另一些程序并不见得支持,而csv格式的却被大多数的应用程序支持,所以在交换保存数据的时候是个不错的选择。
注意的点:
文件处理完的时候一定记得关闭释放数据流否则文件会被占用csv并没有严格的标准,多人开发的时候必须规定好格式,统一开发
一、DataTable数据写入CSV文件
publicstaticvoidSaveCSV(DataTabledt,stringfullPath)//table数据写入csv
System.IO.FileInfofi=newSystem.IO.FileInfo(fullPath);
if(!fi.Directory.Exists)
fi.Directory.Create();
System.IO.FileStreamfs=newSystem.IO.FileStream(fullPath,System.IO.FileMode.Create,
System.IO.FileAccess.Write);
System.IO.StreamWritersw=newSystem.IO.StreamWriter(fs,System.Text.Encoding.UTF8);
stringdata=;
for(inti=0;idt.Columns.Count;i++)//写入列名
data+=dt.Columns[i].ColumnName.ToString();
if(idt.Columns.Count-1)
data+=,;
sw.WriteLine(data);
for(inti=0;idt.Rows.Count;i++)//写入各行数据
data=;
for(intj=0;jdt.Columns.Count;j++)
stringstr=dt.Rows[i][j].ToString();
str=str.Replace(\,\\);//替换英文冒号英文冒号需要换成两个冒号
if(str.Contains(,)||str.Contains()
||str.Contains(\r)||str.Contains(\n))//含逗号冒号换行符的需要放到引号中
str=string.Format(\{0}\,str);
data+=str;
if(jdt.Columns.Count-1)
data+=,;
sw.WriteLine(data);
sw.Close();
fs.Close();
}
二、读取CSV文件到DataTable
publicstaticDataTableOpenCSV(stringfilePath)//从csv读取数据返回table
System.Text.Encodingencoding=GetType(filePath);//Encoding.ASCII;//
DataTabledt=newDataTable();
System.IO.FileStreamfs=newSystem.IO.FileStream(filePath,System.IO.FileMode.Open,
System.IO.FileAccess.Read);
System.IO.StreamReadersr=newSystem.IO.StreamReader(fs,encoding);
//记录每次读取的一行记录
stringstrLine=;
//记录每行记录中的各字段内容
string[]aryLine=