简版:
string filePath = @"E:\C#\CSV操作\person.csv"; //文件路径
System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
if (!fi.Directory.Exists)
{
fi.Directory.Create(); //文件不存在,创建文件
}
System.IO.FileStream fs = new System.IO.FileStream(filePath,System.IO.FileMode.Create,System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
//写入列名
string data = "姓名,年龄";
sw.WriteLine(data);
//写入行数据
data = "小李,12";
sw.WriteLine(data);
data = "小王,18";
sw.WriteLine(data);
data = "小刚,20";
sw.WriteLine(data);
sw.Close();
fs.Close();
通过Datatable操作
public static void SaveCSV(DataTable dt, string filePath)//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('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
{
str = string.Format("\"{0}\"", str);
}
data += str;
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
}
5080

被折叠的 条评论
为什么被折叠?



