读取csv文件

public static DataTable OpenCSV(string filePath)
{
    DataTable dt = new DataTable();
    FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

    StreamReader sr = new StreamReader(fs);
    string strLine = "";
    string[] aryLine = null;
    string[] tableHead = null;
    int columnCount = 0;
    bool IsFirst = true;
    while ((strLine = sr.ReadLine()) != null)
    {
        if (IsFirst == true)
        {
            tableHead = strLine.Split(',');
            IsFirst = false;
            columnCount = tableHead.Length;
            for (int i = 0; i < columnCount; i++)
            {
                DataColumn dc = new DataColumn(tableHead[i]);
                dt.Columns.Add(dc);
            }
        }
        else
        {
            aryLine = strLine.Split(',');
            DataRow dr = dt.NewRow();
            for (int j = 0; j < columnCount; j++)
            {
                dr[j] = aryLine[j];
            }
            dt.Rows.Add(dr);
        }
    }
    if (aryLine != null && aryLine.Length > 0)
    {
        dt.DefaultView.Sort = tableHead[0] + " " + "asc";
    }
    sr.Close();
    fs.Close();
    return dt;
}

private void btOK_Click(object sender, EventArgs e)
{
    foreach (DataRow dr in OpenCSV(textBox1.Text).Rows)
    {
        // Get the first column
        checkedListBox1.Items.Add(dr["Tests"]);
    }
}
原文地址:https://www.cnblogs.com/jizhiqiliao/p/10572476.html