[C#] C#读取csv文件内容

csv文件内容由多行构成,
每行是逗号分隔的字符串。

csv可以用excel来显示,但是不能使用excel来编辑保存。
用以下函数可以将csv读取到DataTable中。

public static DataTable ConverntToTable(string folderPath, string fileName)
{
    OleDbConnection connection = null;
    OleDbCommand command = null;
    OleDbDataAdapter adapter = null;

    try
    {
        connection = new OleDbConnection
        {
            ConnectionString = string.Format(@"
                Provider=Microsoft.Jet.OLEDB.4.0;
                Data Source={0};
                Extended Properties='Text;FMT=Delimited;HDR=YES;CharacterSet=65001;'",
            folderPath
            )
        };

        connection.Open();

        command = new OleDbCommand
        {
            Connection = connection,
            CommandText = string.Format("SELECT * FROM {0}", fileName)
        };

        adapter = new OleDbDataAdapter
        {
            SelectCommand = command
        };

        DataSet csvData = new DataSet();

        adapter.Fill(csvData, "Csv");

        return csvData.Tables[0]; ;
    }
    finally
    {
        if (connection != null)
        {
            connection.Close();
            connection.Dispose();
        }

        if (command != null)
        {
            command.Dispose();
        }

        if (adapter != null)
        {
            adapter.Dispose();
        }
    }
}

你可能感兴趣的:([C#] C#读取csv文件内容)