c# 对对CSV文件操作(写入、读取、修改)文件操作(写入、读取、修改)
主要介绍了c# 如何对CSV文件操作,帮助大家更好的理解和学习C#,感兴趣的朋友可以了解下
一、一、DataTable数据写入数据写入CSV文件文件
public static void SaveCSV(DataTable dt, string fullPath)//table数据写入csv
{
System.IO.FileInfo fi = new System.IO.FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Create,
System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
string data = "";
for (int i = 0; i < dt.Columns.Count; i++)//写入列名
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
for (int i = 0; i < dt.Rows.Count; i++) //写入各行数据
{
data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
if (str.Contains(',') || str.Contains('"')
|| str.Contains('') || str.Contains('')) //含逗号 冒号 换行符的需要放到引号中
{
str = string.Format("\"{0}\"", str);
}
data += str;
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
}
二、读取二、读取CSV文件到文件到DataTable
public static DataTable OpenCSV(string filePath)//从csv读取数据返回table
{
System.Text.Encoding encoding = GetType(filePath); //Encoding.ASCII;//
DataTable dt = new DataTable();
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open,
System.IO.FileAccess.Read);
System.IO.StreamReader sr = new System.IO.StreamReader(fs, encoding);
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine = null;
string[] tableHead = null;
//标示列数
int columnCount = 0;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
if (IsFirst == true)
{
tableHead = strLine.Split(',');
评论1