调用:dataGridView1.DataSource =readCSV(System.Environment.CurrentDirectory + @"\路径规划.csv");
#region 将CSV文件的数据读取到DataTable中
/// <summary>
/// 将CSV文件的数据读取到DataTable中
/// </summary>
/// <param name="fileName">CSV文件路径</param>
/// <returns>返回读取了CSV数据的DataTable</returns>
public static System.Data.DataTable readCSV(string fileName)
{
DataTable dt = new DataTable();
try
{
FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
//记录每次读取的一行记录
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
{
int nullCount = 0;
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
if (aryLine[j] != "")
{
dr[j] = aryLine[j];
}
else
{
nullCount += 1;
}
}
if (nullCount >= 6)
{
}
else
{
dt.Rows.Add(dr);
}
}
}
sr.Close();
fs.Close();
return dt;
}
catch
{
return dt = null;
}
}
#endregion