{"id":15410557,"url":"https://github.com/damienbod/aspnetcorecsvimportexport","last_synced_at":"2025-10-19T10:33:31.409Z","repository":{"id":9637243,"uuid":"61354352","full_name":"damienbod/AspNetCoreCsvImportExport","owner":"damienbod","description":"ASP.NET Core CSV import export custom formatters","archived":false,"fork":false,"pushed_at":"2022-12-08T09:29:59.000Z","size":68,"stargazers_count":77,"open_issues_count":7,"forks_count":43,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-03-12T09:12:06.226Z","etag":null,"topics":["aspnet-core","csv","formatter"],"latest_commit_sha":null,"homepage":"https://damienbod.com/2016/06/17/import-export-csv-in-asp-net-core/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/damienbod.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-06-17T07:27:23.000Z","updated_at":"2025-02-12T06:37:23.000Z","dependencies_parsed_at":"2023-01-11T20:12:57.741Z","dependency_job_id":null,"html_url":"https://github.com/damienbod/AspNetCoreCsvImportExport","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2FAspNetCoreCsvImportExport","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2FAspNetCoreCsvImportExport/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2FAspNetCoreCsvImportExport/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2FAspNetCoreCsvImportExport/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/damienbod","download_url":"https://codeload.github.com/damienbod/AspNetCoreCsvImportExport/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246112640,"owners_count":20725300,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aspnet-core","csv","formatter"],"created_at":"2024-10-01T16:45:00.001Z","updated_at":"2025-10-19T10:33:26.358Z","avatar_url":"https://github.com/damienbod.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Import and Export CSV in ASP.NET Core\r\n## Where to get it\r\n\r\nYou can download [this package](https://www.nuget.org/packages/WebApiContrib.Core.Formatter.Csv/) on NuGet.\r\n\r\n## About\r\n\r\nThis article shows how to import and export csv data in an ASP.NET Core application. The InputFormatter and the OutputFormatter classes are used to convert the csv data to the C# model classes. \r\n\r\n\u003cstrong\u003e2020-01-10: \u003c/strong\u003e Updated to .NET Core 3.1\r\n\r\n\u003cstrong\u003e2019-09-14: \u003c/strong\u003e Updated to .NET Core 3.0\r\n\r\n\u003cstrong\u003e2018-11-23: \u003c/strong\u003e Encoding bug fix\r\n\r\n\u003cstrong\u003e2018-10-24: \u003c/strong\u003e Updated to .NET Core 2.2, sync with Web API Contrib Core\r\n\r\n\u003cstrong\u003e2018-10-08: \u003c/strong\u003e Updated to .NET Core 2.1.5, adding compression\r\n\r\n\u003cstrong\u003e2018-09-14: \u003c/strong\u003e Updated to .NET Core 2.1.4\r\n\r\n\u003cstrong\u003e2018-07-09: \u003c/strong\u003e Updated to .NET Core 2.1.1\r\n\r\n\u003cstrong\u003e2018-05-31: \u003c/strong\u003e Support for ignore, Updated to .NET Core 2.1\r\n\r\n\u003cstrong\u003e2018-05-13: \u003c/strong\u003e Updated to .NET Core 2.1 rc\r\n\r\n\u003cstrong\u003e2017-10-29: \u003c/strong\u003e Support for CSV encoding\r\n\r\n\u003cstrong\u003e2017-08-23: \u003c/strong\u003e Updated to ASP.NET Core 2.0\r\n\r\n\u003cstrong\u003e2017-02-12: \u003c/strong\u003e Updated to VS2017 msbuild\r\n\r\n\u003cstrong\u003e2016-11-25:\u003c/strong\u003e Updated ASP.NET Core 1.1\r\n\r\n\u003cstrong\u003e2016-06-29:\u003c/strong\u003e Updated to ASP.NET Core RTM\r\n\r\nThe LocalizationRecord class is used as the model class to import and export to and from csv data.\r\n\r\n```csharp\r\nusing System;\r\n\r\nnamespace AspNetCoreCsvImportExport.Model\r\n{\r\n    public class LocalizationRecord\r\n    {\r\n        public long Id { get; set; }\r\n        public string Key { get; set; }\r\n        public string Text { get; set; }\r\n        public string LocalizationCulture { get; set; }\r\n        public string ResourceKey { get; set; }\r\n    }\r\n}\r\n```\r\n\r\nThe MVC Controller CsvTestController  makes it possible to import and export the data. The Get method exports the data using the Accept header in the HTTP Request. Per default, Json will be returned. If the Accept Header is set to 'text/csv', the data will be returned as csv. The GetDataAsCsv method always returns csv data because the Produces attribute is used to force this. This makes it easy to download the csv data in a browser. \r\n\r\nThe Import method uses the Content-Type HTTP Request header to decide how to handle the request body. If the 'text/csv' is defined, the custom csv input formatter will be used.\r\n\r\n```csharp\r\nusing System.Collections.Generic;\r\nusing AspNetCoreCsvImportExport.Model;\r\nusing Microsoft.AspNetCore.Mvc;\r\n\r\nnamespace AspNetCoreCsvImportExport.Controllers\r\n{\r\n    [Route(\"api/[controller]\")]\r\n    public class CsvTestController : Controller\r\n    {\r\n        // GET api/csvtest\r\n        [HttpGet]\r\n        public IActionResult Get()\r\n        {\r\n            return Ok(DummyData());\r\n        }\r\n\r\n        [HttpGet]\r\n        [Route(\"data.csv\")]\r\n        [Produces(\"text/csv\")]\r\n        public IActionResult GetDataAsCsv()\r\n        {\r\n            return Ok( DummyData());\r\n        }\r\n\r\n        private static IEnumerable\u003cLocalizationRecord\u003e DummyData()\r\n        {\r\n            var model = new List\u003cLocalizationRecord\u003e\r\n            {\r\n                new LocalizationRecord\r\n                {\r\n                    Id = 1,\r\n                    Key = \"test\",\r\n                    Text = \"test text\",\r\n                    LocalizationCulture = \"en-US\",\r\n                    ResourceKey = \"test\"\r\n\r\n                },\r\n                new LocalizationRecord\r\n                {\r\n                    Id = 2,\r\n                    Key = \"test\",\r\n                    Text = \"test2 text de-CH\",\r\n                    LocalizationCulture = \"de-CH\",\r\n                    ResourceKey = \"test\"\r\n\r\n                }\r\n            };\r\n\r\n            return model;\r\n        }\r\n\r\n        // POST api/csvtest/import\r\n        [HttpPost]\r\n        [Route(\"import\")]\r\n        public IActionResult Import([FromBody]List\u003cLocalizationRecord\u003e value)\r\n        {\r\n            if (!ModelState.IsValid)\r\n            {\r\n                return BadRequest(ModelState);\r\n            }\r\n            else\r\n            {\r\n                List\u003cLocalizationRecord\u003e data = value;\r\n                return Ok();\r\n            }\r\n        }\r\n\r\n    }\r\n}\r\n\r\n```\r\n\r\nThe csv input formatter implements the InputFormatter class. This checks if the context ModelType property is a type of IList and if so, converts the csv data to a List of Objects of type T using reflection. This is implemented in the read stream method. The implementation is very basic and will not work if you have more complex structures in your model class.\r\n\r\n \r\n```csharp\r\nusing System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Reflection;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.AspNetCore.Mvc.Formatters;\r\nusing Microsoft.Net.Http.Headers;\r\nusing System.Text;\r\n\r\nnamespace AspNetCoreCsvImportExport.Formatters\r\n{\r\n    /// \u003csummary\u003e\r\n    /// ContentType: text/csv\r\n    /// \u003c/summary\u003e\r\n    public class CsvInputFormatter : InputFormatter\r\n    {\r\n        private readonly CsvFormatterOptions _options;\r\n\r\n        public CsvInputFormatter(CsvFormatterOptions csvFormatterOptions)\r\n        {\r\n            SupportedMediaTypes.Add(Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse(\"text/csv\"));\r\n\r\n            if (csvFormatterOptions == null)\r\n            {\r\n                throw new ArgumentNullException(nameof(csvFormatterOptions));\r\n            }\r\n\r\n            _options = csvFormatterOptions;\r\n        }\r\n\r\n        public override Task\u003cInputFormatterResult\u003e ReadRequestBodyAsync(InputFormatterContext context)\r\n        {\r\n            var type = context.ModelType;\r\n            var request = context.HttpContext.Request;\r\n            MediaTypeHeaderValue requestContentType = null;\r\n            MediaTypeHeaderValue.TryParse(request.ContentType, out requestContentType);\r\n\r\n\r\n            var result = ReadStream(type, request.Body);\r\n            return InputFormatterResult.SuccessAsync(result);\r\n        }\r\n\r\n        public override bool CanRead(InputFormatterContext context)\r\n        {\r\n            var type = context.ModelType;\r\n            if (type == null)\r\n                throw new ArgumentNullException(\"type\");\r\n\r\n            return IsTypeOfIEnumerable(type);\r\n        }\r\n\r\n        private bool IsTypeOfIEnumerable(Type type)\r\n        {\r\n\r\n            foreach (Type interfaceType in type.GetInterfaces())\r\n            {\r\n\r\n                if (interfaceType == typeof(IList))\r\n                    return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        private object ReadStream(Type type, Stream stream)\r\n        {\r\n            Type itemType;\r\n            var typeIsArray = false;\r\n            IList list;\r\n            if (type.GetGenericArguments().Length \u003e 0)\r\n            {\r\n                itemType = type.GetGenericArguments()[0];\r\n                list = (IList)Activator.CreateInstance(type);\r\n            }\r\n            else\r\n            {\r\n                typeIsArray = true;\r\n                itemType = type.GetElementType();\r\n\r\n                var listType = typeof(List\u003c\u003e);\r\n                var constructedListType = listType.MakeGenericType(itemType);\r\n\r\n                list = (IList)Activator.CreateInstance(constructedListType);\r\n            }\r\n\r\n            var reader = new StreamReader(stream, Encoding.GetEncoding(_options.Encoding));\r\n\r\n            bool skipFirstLine = _options.UseSingleLineHeaderInCsv;\r\n            while (!reader.EndOfStream)\r\n            {\r\n                var line = reader.ReadLine();\r\n                var values = line.Split(_options.CsvDelimiter.ToCharArray());\r\n                if(skipFirstLine)\r\n                {\r\n                    skipFirstLine = false;\r\n                }\r\n                else\r\n                {\r\n                    var itemTypeInGeneric = list.GetType().GetTypeInfo().GenericTypeArguments[0];\r\n                    var item = Activator.CreateInstance(itemTypeInGeneric);\r\n                    var properties = item.GetType().GetProperties();\r\n                    for (int i = 0;i\u003cvalues.Length; i++)\r\n                    {\r\n                        properties[i].SetValue(item, Convert.ChangeType(values[i], properties[i].PropertyType), null);\r\n                    }\r\n\r\n                    list.Add(item);\r\n                }\r\n\r\n            }\r\n\r\n            if(typeIsArray)\r\n            {\r\n                Array array = Array.CreateInstance(itemType, list.Count);\r\n\r\n                for(int t = 0; t \u003c list.Count; t++)\r\n                {\r\n                    array.SetValue(list[t], t);\r\n                }\r\n                return array;\r\n            }\r\n            \r\n            return list;\r\n        }\r\n    }\r\n}\r\n```\r\n\r\nThe csv output formatter is implemented using the code from \u003ca href=\"http://www.tugberkugurlu.com/archive/creating-custom-csvmediatypeformatter-in-asp-net-web-api-for-comma-separated-values-csv-format\"\u003eTugberk Ugurlu's blog\u003c/a\u003e with some small changes. Thanks for this. This formatter uses ';' to separate the properties and a new line for each object. The headers are added tot he first line.\r\n\r\n\r\n```csharp\r\nusing System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Reflection;\r\nusing Microsoft.AspNetCore.Mvc.Formatters;\r\nusing System.ComponentModel.DataAnnotations;\r\n\r\nnamespace AspNetCoreCsvImportExport.Formatters\r\n{\r\n    /// \u003csummary\u003e\r\n    /// Original code taken from\r\n    /// http://www.tugberkugurlu.com/archive/creating-custom-csvmediatypeformatter-in-asp-net-web-api-for-comma-separated-values-csv-format\r\n    /// Adapted for ASP.NET Core and uses ; instead of , for delimiters\r\n    /// \u003c/summary\u003e\r\n    public class CsvOutputFormatter : OutputFormatter\r\n    {\r\n        private readonly CsvFormatterOptions _options;\r\n\r\n        public string ContentType { get; private set; }\r\n\r\n        public CsvOutputFormatter(CsvFormatterOptions csvFormatterOptions)\r\n        {\r\n            ContentType = \"text/csv\";\r\n            SupportedMediaTypes.Add(Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse(\"text/csv\"));\r\n            _options = csvFormatterOptions ?? throw new ArgumentNullException(nameof(csvFormatterOptions));\r\n        }\r\n\r\n        protected override bool CanWriteType(Type type)\r\n        {\r\n\r\n            if (type == null)\r\n                throw new ArgumentNullException(\"type\");\r\n\r\n            return IsTypeOfIEnumerable(type);\r\n        }\r\n\r\n        private bool IsTypeOfIEnumerable(Type type)\r\n        {\r\n\r\n            foreach (Type interfaceType in type.GetInterfaces())\r\n            {\r\n\r\n                if (interfaceType == typeof(IList))\r\n                    return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)\r\n        {\r\n            var response = context.HttpContext.Response;\r\n\r\n            Type type = context.Object.GetType();\r\n            Type itemType;\r\n\r\n            if (type.GetGenericArguments().Length \u003e 0)\r\n            {\r\n                itemType = type.GetGenericArguments()[0];\r\n            }\r\n            else\r\n            {\r\n                itemType = type.GetElementType();\r\n            }\r\n\r\n            var streamWriter = new StreamWriter(response.Body, Encoding.GetEncoding(_options.Encoding));\r\n\r\n            if (_options.UseSingleLineHeaderInCsv)\r\n            {\r\n                await streamWriter.WriteLineAsync(\r\n                    string.Join(\r\n                        _options.CsvDelimiter, itemType.GetProperties().Select(x =\u003e x.GetCustomAttribute\u003cDisplayAttribute\u003e(false)?.Name ?? x.Name)\r\n                    )\r\n                );\r\n            }\r\n\r\n            foreach (var obj in (IEnumerable\u003cobject\u003e)context.Object)\r\n            {\r\n\r\n                var vals = obj.GetType().GetProperties().Select(\r\n                    pi =\u003e new\r\n                    {\r\n                        Value = pi.GetValue(obj, null)\r\n                    }\r\n                );\r\n\r\n                string valueLine = string.Empty;\r\n\r\n                foreach (var val in vals)\r\n                {\r\n                    if (val.Value != null)\r\n                    {\r\n\r\n                        var _val = val.Value.ToString();\r\n\r\n                        //Check if the value contans a comma and place it in quotes if so\r\n                        if (_val.Contains(\",\"))\r\n                            _val = string.Concat(\"\\\"\", _val, \"\\\"\");\r\n\r\n                        //Replace any \\r or \\n special characters from a new line with a space\r\n                        if (_val.Contains(\"\\r\"))\r\n                            _val = _val.Replace(\"\\r\", \" \");\r\n                        if (_val.Contains(\"\\n\"))\r\n                            _val = _val.Replace(\"\\n\", \" \");\r\n\r\n                        valueLine = string.Concat(valueLine, _val, _options.CsvDelimiter);\r\n\r\n                    }\r\n                    else\r\n                    {\r\n                        valueLine = string.Concat(valueLine, string.Empty, _options.CsvDelimiter);\r\n                    }\r\n                }\r\n\r\n                await streamWriter.WriteLineAsync(valueLine.TrimEnd(_options.CsvDelimiter.ToCharArray()));\r\n            }\r\n\r\n            await streamWriter.FlushAsync();\r\n        }\r\n    }\r\n}\r\n\r\n```\r\n\r\nThe custom formatters need to be added to the MVC middleware, so that it knows how to handle media types 'text/csv'. \r\n\r\n\r\n```csharp\r\npublic void ConfigureServices(IServiceCollection services)\r\n{\r\n    services.AddMvc(options =\u003e\r\n    {\r\n        options.InputFormatters.Add(new CsvInputFormatter());\r\n        options.OutputFormatters.Add(new CsvOutputFormatter());\r\n        options.FormatterMappings.SetMediaTypeMappingForFormat(\"csv\", MediaTypeHeaderValue.Parse(\"text/csv\"));\r\n    });\r\n}\r\n```\r\n\r\nWhen the data.csv link is requested, a csv type response is returned to the client, which can be saved. This data contains the header texts and the value of each property in each object. This can then be opened in excel.\r\n\r\nhttp://localhost:10336/api/csvtest/data.csv\r\n\r\n```csharp\r\nId;Key;Text;LocalizationCulture;ResourceKey\r\n1;test;test text;en-US;test\r\n2;test;test2 text de-CH;de-CH;test\r\n```\r\n\r\nThis data can then be used to upload the csv data to the server which is then converted back to a C# object. I use fiddler, postman or curl can also be used, or any HTTP Client where you can set the header Content-Type.\r\n\r\n```csharp\r\n\r\n http://localhost:10336/api/csvtest/import \r\n\r\n User-Agent: Fiddler \r\n Content-Type: text/csv \r\n Host: localhost:10336 \r\n Content-Length: 110 \r\n\r\n\r\n Id;Key;Text;LocalizationCulture;ResourceKey \r\n 1;test;test text;en-US;test \r\n 2;test;test2 text de-CH;de-CH;test \r\n\r\n```\r\n\r\nThe following image shows that the data is imported correctly.\r\n\r\n\r\n\u003cimg src=\"https://damienbod.files.wordpress.com/2016/06/importexportcsv.png\" alt=\"importExportCsv\" width=\"598\" height=\"558\" class=\"alignnone size-full wp-image-6742\" /\u003e\r\n\r\n\u003cstrong\u003eNotes\u003c/strong\u003e\r\n\r\nThe implementation of the InputFormatter and the OutputFormatter classes are specific for a list of simple classes with only properties. If you require or use more complex classes, these implementations need to be changed.\r\n\r\n\u003cstrong\u003eLinks\u003c/strong\u003e\r\n\r\nhttp://www.tugberkugurlu.com/archive/creating-custom-csvmediatypeformatter-in-asp-net-web-api-for-comma-separated-values-csv-format\r\n\r\nhttps://damienbod.com/2015/06/03/asp-net-5-mvc-6-custom-protobuf-formatters/\r\n\r\nhttp://www.strathweb.com/2014/11/formatters-asp-net-mvc-6/\r\n\r\nhttps://wildermuth.com/2016/03/16/Content_Negotiation_in_ASP_NET_Core\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdamienbod%2Faspnetcorecsvimportexport","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdamienbod%2Faspnetcorecsvimportexport","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdamienbod%2Faspnetcorecsvimportexport/lists"}