/// <summary>
/// 读取CSV文件
/// </summary>
/// <param name="filePath">文件路径 eg:D:\A.csv</param>
/// <param name="dt">数据(无标题)</param>
/// <param name="csvTitles">标题</param>
public static bool ReadCSV(string filePath, out DataTable dt, out ArrayList csvTitles)
{
dt = new DataTable();
csvTitles = new ArrayList();
try
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"));
//记录每次读取的一行记录
string strLine = null;
//记录每行记录中的各字段内容
string[] arrayLine = null;
//分隔符
string[] separators = { "," };
//表头标志位(若是第一次,建立表头)
bool isFirst = true;
//逐行读取CSV文件
while ((strLine = sr.ReadLine()) != null)
{
//去除头尾空格
strLine = strLine.Trim();
//分隔字符串,返回数组
arrayLine = strLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);
//建立表头
if (isFirst)
{
for (int i = 0; i < arrayLine.Length; i++)
{
dt.Columns.Add(arrayLine[i]);//每一列名称
csvTitles.Add(arrayLine[i]);
}
isFirst = false;
}
else //表内容
{
DataRow dataRow = dt.NewRow();//新建一行
for (int j = 0; j < arrayLine.Length; j++)
{
dataRow[j] = arrayLine[j];
}
dt.Rows.Add(dataRow);//添加一行
}
}
sr.Close();
fs.Close();
return true;
}
catch
{
return false;
}
}
C# 读取CSV数据
最新推荐文章于 2024-05-28 19:18:54 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)