C# CSV数据文件的导入和导出
一、将DataTable数据导出到CSV文件
/// <summary>
/// 写入CSV
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="dt">要写入的datatable</param>
public static void WriteCSV(string fileName, DataTable dt)
{
try
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
string data = "";
if (dt.Columns.Count > 0) //有数据列时,才执行写入
{
//写出列名称
for (int i = 0; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName