导入导出数据到csv文件

CSV文件基于文本格式,具有非依赖的特性,用来存放一些简单的数据再好不过了。csv文件的读取基本和文本文件一致。

读取CSV文件

public static DataTable ImportFromCSVAsText(string strFileName)
        {
            DataTable table = new DataTable();

            using (StreamReader reader = new StreamReader(strFileName, Encoding.UTF8))
            {
                string line = null;
                // 添加表头
                if ((line = reader.ReadLine()) != null)
                {
                    string[] heads = line.Split(',');
                    for (int i = 0; i < heads.Length; i++)
                    {
                        DataColumn column = new DataColumn(heads[i], typeof(string));
                        table.Columns.Add(column);
                    }
                }
                // 读取数据
                while ((line = reader.ReadLine()) != null)
                {
                    string[] fields = line.Split(',');
                    DataRow row = table.NewRow();
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        row[i] = fields[i];
                    }

                    table.Rows.Add(row);
                }
            }

            return table;
        }

写入csv文件

static string WriteFile(List<Entity> errorList)
{
    string path = string.Empty;
    if (errorList != null && errorList.Count > 0)
    {
        string title = "ID,Country,CountryName,城市,CityCode,Address_intl,LAT,LON";
        path = AppDomain.CurrentDomain.BaseDirectory + @"Hotel_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
        using (var stream = new FileStream(path, FileMode.Create))
        {
            using (var writer = new StreamWriter(new BufferedStream(stream), Encoding.UTF8))
            {
                writer.WriteLine(title);
                foreach (ExpandHotelInterfaceRequestDateErrorLog entity in errorList)
                {

       StringBuilder line = new StringBuilder();
                    line.Append(FormatCsvContent(entity.ID.ToString()) + ",");
                    line.Append(FormatCsvContent(entity.Country) + ",");
                    line.Append(FormatCsvContent(entity.CountryName) + ",");
                    line.Append(FormatCsvContent(entity.City.ToString() + ",");
                    line.Append(FormatCsvContent(entity.CityCode) + ",");
                    line.Append(FormatCsvContent(entity.AddressInfo) + ",");
                    line.Append(FormatCsvContent(entity.LAT) + ",");
                    line.Append(FormatCsvContent(entity.LON) + ",");
                    writer.WriteLine(line.ToString());
                }
                writer.Flush();
            }
        }
    }

    return path;
}

/// <summary>
/// CSV字段中含双引号 逗号时处理
/// </summary>
/// <param name="content">处理内容</param>
/// <returns></returns>
private static string FormatCsvContent(string content)
{
    if (string.IsNullOrEmpty(content)) return content;

    if (content.Contains("""))//字段中存在双引号
    {
        content = content.Replace(""", """");
    }

    content = """ + content + """;

    content = content.Replace(",]", "]");
    return content;
}

原文地址:https://www.cnblogs.com/ahua1188/p/5360798.html