Quantcast
Channel: Effect Labs Blog
Viewing all articles
Browse latest Browse all 37

Export Data to CSV file in MVC4

$
0
0

In this post we will learn to export data into csv file.

Step 1 :- Take a new MVC 4 Project and download the CsvHelper.dll , you can download this dll by the following way

Click on Tools --> Library Package Manager --> Package Manager Console

Now write  Install-Package CsvHelper on Package Manager Console

like PM > Install-Package CsvHelper and enter

by this you will get the latest version of CsvHelper.

 

Step 2:-

Now Make a model class and do some setting for Csv

 

[DebuggerDisplay("Index = {Index}, Name = {Name}, Ignore = {Ignore}, ReferenceKey = {ReferenceKey}")]
        [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
        public class CsvFieldAttribute : Attribute
        {
            public virtual object Default { get; set; }
            public virtual string Format { get; set; }
            public virtual bool Ignore { get; set; }
            public virtual int Index { get; set; }
            public virtual string Name { get; set; }
            public virtual string[] Names { get; set; }
            public virtual string ReferenceKey { get; set; }
        }

        public class UserInfo
        {
            [CsvField(Index = 0)]
            public string FirstName { get; set; }
            [CsvField(Index = 1)]
            public string LastName { get; set; }
            [CsvField(Index=2)]
            public string DOJ { get; set; }
        }

 

   Step :3- Make a class and write some method which will help in exporting and formatting of Csv

public class Common
    {
        public static string GetCsv<T>(List<T> csvDataObjects)
        {
            PropertyInfo[] propertyInfos = typeof(T).GetProperties();
            var sb = new StringBuilder();
            sb.AppendLine(GetCsvHeaderSorted(propertyInfos));
            csvDataObjects.ForEach(d => sb.AppendLine(GetCsvDataRowSorted(d, propertyInfos)));
            return sb.ToString();
        }

        private static string GetCsvDataRowSorted<T>(T csvDataObject, PropertyInfo[] propertyInfos)
        {
            IEnumerable<string> valuesSorted = propertyInfos
                .Select(x => new
                {
                    Value = x.GetValue(csvDataObject, null),
                    Attribute = (CsvFieldAttribute)Attribute.GetCustomAttribute(x, typeof(CsvFieldAttribute), false)
                })
                .Where(x => x.Attribute != null)
                .OrderBy(x => x.Attribute.Index)
                .Select(x => GetPropertyValueAsString(x.Value));
            return String.Join(",", valuesSorted);
        }

        private static string GetCsvHeaderSorted(PropertyInfo[] propertyInfos)
        {
            IEnumerable<string> headersSorted = propertyInfos
                .Select(x => (CsvFieldAttribute)Attribute.GetCustomAttribute(x, typeof(CsvFieldAttribute), false))
                .Where(x => x != null)
                .OrderBy(x => x.Index)
                .Select(x => x.Name);
            return String.Join(",", headersSorted);
        }

        private static string GetPropertyValueAsString(object propertyValue)
        {
            string propertyValueString;

            if (propertyValue == null)
                propertyValueString = "";
            else if (propertyValue is DateTime)
                propertyValueString = ((DateTime)propertyValue).ToString("dd MMM yyyy");
            else if (propertyValue is int)
                propertyValueString = propertyValue.ToString();
            else if (propertyValue is float)
                propertyValueString = ((float)propertyValue).ToString("#.####"); // format as you need it
            else if (propertyValue is double)
                propertyValueString = ((double)propertyValue).ToString("#.####"); // format as you need it
            else // treat as a string
                propertyValueString = @"""" + propertyValue.ToString().Replace(@"""", @"""""") + @""""; // quotes with 2 quotes

            return propertyValueString;
        }
    }

 

 

Step: 4 -

Write a method in Controller which return the FileContentResult and a method for Csv Header

Here, i am taking the static data.

public FileContentResult ExportToCsv()
        {
            var userList = new List<UserInfo>();
            userList.Add(GetHeader());
            int k = -5;
            for (int i = 0; i < 5; i++)
            {
                //static data 
                var userInfo = new UserInfo();
                userInfo.FirstName = "abc" + i;
                userInfo.LastName = "xyz" + i;
                userInfo.DOJ = DateTime.Now.AddDays(k + i).ToString();
                userList.Add(userInfo);
            }
            string result =Utility.Common.GetCsv(userList);
            return File(new System.Text.UTF8Encoding().GetBytes(result), "text/csv", "userinfo.csv");
        }

        public UserInfo GetHeader()
        {
            var userInfo = new UserInfo();
            userInfo.FirstName = "First Name";
            userInfo.LastName = "Last Name";
            userInfo.DOJ = "Date of Joining";
            return userInfo;
        }

 

So, this is the basic example of  export data to Csv file in MVC.

 

You can download the complete solution from the following link

 CsvGenerator.zip (13.86 mb)


Viewing all articles
Browse latest Browse all 37

Trending Articles