全栈工程师开发手册 (作者:栾鹏)

​​ c#教程全解​​

c#读取csv文件成DataTable,将DataTable数据存储为csv格式文件,

测试代码

static void Main()
{
//自定义数据
DataTable alldata = new DataTable();
alldata.Columns.Add("第1列", Type.GetType("System.String"));
alldata.Columns.Add("第2列", Type.GetType("System.Int32"));
alldata.Columns.Add("第3列", Type.GetType("System.Double"));
for (int i = 0; i < 10;i++ )
{
DataRow onerow = alldata.NewRow();
onerow[0] = i + "0";
onerow[1] = i;
onerow[2] = i*1.1;
alldata.Rows.Add(onerow);
}

DataTable2CSV(alldata, "test.csv"); //保存csv
DataTable alldata1 = CSV2DataTable("test.csv"); //读取csv
//遍历数据
for (int i = 0; i < alldata1.Rows.Count; i++)
{
DataRow onerow = alldata1.Rows[i];
foreach (DataColumn col in alldata1.Columns)
{
System.Console.WriteLine(onerow[col].ToString());
}
}
}

读取csv文件成DataTable数据

如果是Unicode存储,列之间使用tab间隔,如果是utf-8存储,使用逗号间隔

//导入CSV文件
public static System.Data.DataTable CSV2DataTable(string fileName)
{
System.Data.DataTable dt = new System.Data.DataTable();
FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs, new System.Text.UnicodeEncoding());
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine;
//标示列数
int columnCount = 0;
//标示是否是读取的第一行
bool IsFirst = true;

//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
aryLine = strLine.Split(',');
if (IsFirst == true)
{
IsFirst = false;
columnCount = aryLine.Length;
//创建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(aryLine[i]);
dt.Columns.Add(dc);
}
}
else
{
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
}

sr.Close();
fs.Close();
return dt;
}

将DataTable数据写入csv文件

如果是Unicode存储,列之间使用tab间隔,如果是utf-8存储,使用逗号间隔

public static void DataTable2CSV(System.Data.DataTable dt, string AbosultedFilePath)
{
//MessageBox.Show(AbosultedFilePath);
System.IO.FileStream fs = new FileStream(AbosultedFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());
//Tabel header
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ColumnName);
sw.Write("\t");
}
sw.WriteLine("");
//Table body
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
sw.Write(DelQuota(dt.Rows[i][j].ToString()));
sw.Write("\t");
}
sw.WriteLine("");
}
sw.Flush();
sw.Close();
}
public static string DelQuota(string str)
{
string result = str;
string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
for (int i = 0; i < strQuota.Length; i++)
{
if (result.IndexOf(strQuota[i]) > -1)
result = result.Replace(strQuota[i], "");
}
return result;
}