💼

Need Help With Your Project?

I provide expert-level support in .NET Core, SQL Server, and Web Application Development.
Hourly support & consultation also available.

Hire Me

How to Convert a List of Objects to CSV in C# | Step-by-Step Tutorial

watch_later 8/03/2025

In this tutorial, you will learn how to convert a list of objects to a CSV file in ASP.NET MVC, leveraging Entity Framework to fetch data from a SQL Server database.

We will cover step-by-step how to retrieve database records using Entity Framework, bind the data to an MVC view, and design the front-end using Bootstrap CSS framework for responsive layouts.

Finally, you’ll see how to convert the data into a list of C# objects and export that list to a downloadable CSV (comma-separated values) file directly from the MVC controller.

This approach is perfect for exporting data reports, logs, or user lists in a lightweight, easy-to-share CSV format.

By the end of this article, you’ll know how to export your data as a CSV (comma-separated values) file directly from your MVC controller. This is a common requirement for exporting reports, user lists, or any tabular data in a lightweight, portable format.

What You Will Learn

  • How to connect to a SQL Server database using Entity Framework in ASP.NET MVC
  • How to fetch and display data records in a view using Bootstrap CSS classes
  • How to convert data into a list of objects in C#
  • How to generate and download a CSV file from the list of objects in your MVC application

Why Export Data to CSV?

CSV files are widely used because they are simple text files that represent tabular data with values separated by commas. They can be opened easily in Excel or any text editor, making them perfect for sharing and reporting.

CSV (comma-separated values)

Requirement

  1. Create a SQL Server Database and Sample Students Table for ASP.NET MVC CSV Export
  2. First, create a SQL Server database with a sample table containing student records for demonstration purposes. The table should include basic student information such as Roll Number, Enrollment Number, Name, Branch, and University.
  3. Next, display a list of students in an ASP.NET MVC view, showing these key details clearly.
  4. Finally, implement functionality to export the list of students to a CSV file using C# and Entity Framework, enabling users to download student data as a comma-separated values (CSV) file easily.

Read: Read CSV File In ASP.NET With Example C# and VB.NET

Implementation

In this article, we will demonstrate how to display a list of students with essential details such as Roll Number, Enrollment Number, Name, Branch, and University in an ASP.NET MVC application. Additionally, we’ll implement functionality to export this student list to a CSV file for easy data sharing and reporting.

To begin, we'll set up a SQL Server database by creating a new database and a table to store student records. This foundational step prepares the data source that we’ll later fetch using Entity Framework and use to generate the CSV export.

Step 1: Create a new database table. You can follow this query.

CREATE TABLE [dbo].[Students](
	[Student_Id] [int] IDENTITY(1,1) NOT NULL,
	[RollNo] [int] NULL,
	[EnrollmentNo] [nvarchar](15) NULL,
	[Name] [nvarchar](50) NULL,
	[Branch] [nvarchar](50) NULL,
	[University] [nvarchar](50) NULL
) ON [PRIMARY]

Step 2: Insert a few sample records of students for demonstration.

INSERT INTO Students (RollNo, EnrollmentNo, Name, Branch, University) VALUES 
(101, '14SOECE13017', 'Nikunj Satasiya', 'Computer Science Engineering', 'RK University'),
(102, '14SOECE13018', 'Hiren Dobariya', 'Computer Science Engineering', 'RK University'),
(103, '14SOECE13019', 'Vivek Ghadiya', 'Computer Science Engineering', 'RK University'),
(104, '14SOECE13020', 'Shreya Patel', 'Information Technology', 'RK University'),
(105, '14SOECE13021', 'Kishan Dave', 'Information Technology', 'RK University'),
(106, '14SOECE13022', 'Meena Patel', 'Computer Science Engineering', 'RK University'),
(107, '14SOECE13023', 'Niraj Patel', 'Civil Engineering', 'RK University'),
(108, '14SOECE13024', 'Renu Savla', 'Computer Science Engineering', 'RK University'),
(109, '14SOECE13025', 'Priya Dobariya', 'Information Technology', 'RK University'),
(110, '14SOECE13026', 'Rinku Patel', 'Computer Science Engineering', 'RK University')

Step 3: Now, we have to create a new project in visual studio, So, open the visual studio 2019 » file » new » project » and Select Web Application.

When you click the Next button, a new window will appear prompting you to select a project template. Choose MVC (Model-View-Controller) as the template, then click the OK button.

Next, enter a meaningful project name for your ASP.NET MVC application, and click the Create button to generate the project structure.

Read: Export DataTable To CSV In C#

Step 4: Now, you have to go to solution explorer and right-click on the Model folder » Add » New Item » select Data from the left panel » Select ADO.NET Entity Data Model.

Now, click the Add button and choose Entity Framework Designer to create your data model. Proceed by clicking Next, then enter your SQL server credentials to connect to your database. Select the desired database from the list.

After that, click Add, select your students table, and finally click the Finish button to generate the Entity Framework model for your ASP.NET MVC project.

ADO.NET Entity Data Model

If you are a beginner or need any help to add an entity data model then you can read this article where I explained how to create an ADO.NET entity data model (EDM) in asp.net step by step.

Step 5: Now, you have to go to solution explorer » Controllers » HomeController.cs and write the following code in the home controller.

HomeController.cs

using Codingvila.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
 
namespace Codingvila.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            CodingvilaEntities entities = new CodingvilaEntities();
            var lstStudents = (from Student in entities.Students
                                        select Student);
            return View(lstStudents);
        }
 
        [HttpPost]
        public FileResult ExportToCSV()
        {
            #region Get list of Students from Database
 
            CodingvilaEntities entities = new CodingvilaEntities();
            List<objectlstStudents = (from Student in entities.Students.ToList()
                                        select new[] { Student.RollNo.ToString(),
                                                                Student.EnrollmentNo,
                                                                Student.Name,
                                                                Student.Branch,
                                                                Student.University
                                  }).ToList<object>();
 
            #endregion 
 
            #region Create Name of Columns
 
            var names = typeof(Student).GetProperties()
                        .Select(property => property.Name)
                        .ToArray();
 
            lstStudents.Insert(0, names.Where(x => x != names[0]).ToArray());
 
            #endregion
 
            #region Generate CSV
 
            StringBuilder sb = new StringBuilder();
            foreach (var item in lstStudents)
            {
                string[] arrStudents = (string[])item;
                foreach (var data in arrStudents)
                {
                    //Append data with comma(,) separator.
                    sb.Append(data + ',');
                }
                //Append new line character.
                sb.Append("\r\n");
            }
 
            #endregion
 
            #region Download CSV
 
            return File(Encoding.ASCII.GetBytes(sb.ToString()), "text/csv""Students.csv");
 
            #endregion
        }
    }
}

The HomeController.cs contains two important action methods: Index and ExportToCSV.

  • The Index action method returns an ActionResult, which represents the result of an action method. It retrieves a list of students from the database using Entity Framework and passes this student list as a model to the view for display.
  • The ExportToCSV action method is a POST method that returns a FileResult. This action method is responsible for generating and sending the CSV file to the user as a downloadable file.

Inside the ExportToCSV method, the process is as follows:

  1. Fetch the list of students from the database using Entity Framework and convert it into a list of objects.
  2. Define the CSV column headers by extracting the property names from the student model, and insert this header row at the beginning of the list.
  3. Use a StringBuilder to construct the CSV content by appending each student’s data, separating fields with commas (,) and adding newline characters to mark row ends.
  4. Finally, return the generated CSV content as a downloadable file named Students.csv.

This approach efficiently converts a list of objects into a CSV file in an ASP.NET MVC application using C# and Entity Framework.

Read: Export JSON Data to Excel/CSV File using AngularJs With Bootstrap

Step 6: Now, we have to design a view and for the same, you have to go to solution explorer » Views » Home » Index. CSS HTML and write the following code in the Index.CSS HTML file.

Index. CSS HTML

@{
    ViewBag.Title = "Students";
}
@model IEnumerable<Codingvila.Models.Student>
<div class="panel-body">
    <div class="form-group">
 
        <br />
        <div class="row">
            <table class="table table-bordered table-responsive">
                <tr>
                    <th>RollNo</th>
                    <th>EnrollmentNo</th>
                    <th>Name</th>
                    <th>Branch</th>
                    <th>University</th>
                </tr>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>
                                @item.RollNo
                            </td>
                            <td>
                                @item.EnrollmentNo
                            </td>
                            <td>
                                @item.Name
                            </td>
                            <td>
                                @item.Branch
                            </td>
                            <td>
                                @item.University
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
        </br>
        <div class="row">
            <div class="panel-primary">
                @using (Html.BeginForm("ExportToCSV""Home", FormMethod.Post))
                {
                <button type="submit" class="btn btn-success">
                    <i class="glyphicon glyphicon glyphicon-export"></i> Export To CSV
                </button>
                }
            </div>
        </div>
    </div>
</div>

As you can see in the code above, here, we have declared a student model with help of ASP.NET Razor Syntax. Finally, Create one button and put it into a form table that we have created using ASP.NET Razor Syntax.

Export to CSV


When a user clicks the Export To CSV button, the ExportToCSV action method in the HomeController is executed, which generates and downloads the CSV file containing the student data.

Read: Export Dataset/Datatable to CSV File Using C# and VB.NET

We use an HTML table to display the list of student records, which are retrieved from the database using Entity Framework in the ASP.NET MVC application.

Step 7: Now, you have to build and run the project in the browser.

After successfully running the project, when the user clicks the Export To CSV button, the application generates the CSV file and automatically downloads it to the user’s local Downloads folder.

Conclusion

In this article, we learned how to fetch records from a SQL Server database using Entity Framework in an ASP.NET MVC application, and how to export and download those records as a CSV file.

We also covered how to convert a model object into a list of objects and how to dynamically retrieve property names from the model for generating CSV column headers using C#.

This approach provides a simple and effective way to export data from your MVC apps in a widely supported, easy-to-use CSV format.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

If you have any questions, contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon