How to create CSV Excel file C#?

I'm looking for a class for creating CSV Excel files.

Expected features:

  • Extremely simple to use
  • Escapes commas and quotes so excel handles them fine
  • Exports date and datetimes in timezone-proof format
  • Do you know any class capable of this?


    Slightly different version I wrote using reflection for my needs. I had to export a list of objects to csv. In case someone wants to use it for future.

    public class CsvExport<T> where T: class
        {
            public List<T> Objects;
    
            public CsvExport(List<T> objects)
            {
                Objects = objects;
            }
    
            public string Export()
            {
                return Export(true);
            }
    
            public string Export(bool includeHeaderLine)
            {
    
                StringBuilder sb = new StringBuilder();
                //Get properties using reflection.
                IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();
    
                if (includeHeaderLine)
                {
                    //add header line.
                    foreach (PropertyInfo propertyInfo in propertyInfos)
                    {
                        sb.Append(propertyInfo.Name).Append(",");
                    }
                    sb.Remove(sb.Length - 1, 1).AppendLine();
                }
    
                //add value for each property.
                foreach (T obj in Objects)
                {               
                    foreach (PropertyInfo propertyInfo in propertyInfos)
                    {
                        sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj, null))).Append(",");
                    }
                    sb.Remove(sb.Length - 1, 1).AppendLine();
                }
    
                return sb.ToString();
            }
    
            //export to a file.
            public void ExportToFile(string path)
            {
                File.WriteAllText(path, Export());
            }
    
            //export as binary data.
            public byte[] ExportToBytes()
            {
                return Encoding.UTF8.GetBytes(Export());
            }
    
            //get the csv value for field.
            private string MakeValueCsvFriendly(object value)
            {
                if (value == null) return "";
                if (value is Nullable && ((INullable)value).IsNull) return "";
    
                if (value is DateTime)
                {
                    if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                        return ((DateTime)value).ToString("yyyy-MM-dd");
                    return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
                }
                string output = value.ToString();
    
                if (output.Contains(",") || output.Contains("""))
                    output = '"' + output.Replace(""", """") + '"';
    
                return output;
    
            }
        }
    

    Usage sample : (updated per comment)

    CsvExport<BusinessObject> csv= new CsvExport<BusinessObject>(GetBusinessObjectList());
    Response.Write(csv.Export());
    

    Please forgive me

    But I think a public open-source repository is a better way to share code and make contributions, and corrections, and additions like "I fixed this, I fixed that"

    So I made a simple git-repository out of the topic-starter's code and all the additions:

    https://github.com/jitbit/CsvExport

    I also added a couple of useful fixes myself. Everyone could add suggestions, fork it to contribute etc. etc. etc. Send me your forks so I merge them back into the repo.

    PS. I posted all copyright notices for Chris. @Chris if you're against this idea - let me know, I'll kill it.


    读取和写入CSV文件的另一个好方法是filehelpers(开源)。

    链接地址: http://www.djcxy.com/p/35690.html

    上一篇: 在C#中重命名文件

    下一篇: 如何创建CSV Excel文件C#?