Export CSV file using C# MVC

Posted on April 6, 2018 by Suresh Kamrushi in C#

Sharing here how you can export CSV file on runtime using C# MVC 4.5.
In below code I am executing query to get data and then exporting it as CSV files.

public ActionResult exportData(FormCollection exportForm)
{
    var exportReport = exportForm["exportList"];
    if (exportReport != "")
    {
        var BL = new businesslogic();
        string sqlQuery = "SELECT * FROM " + exportReport;
        DataSet tableDataSet = BL.GetResultsDS(cs, sqlQuery);

        string data = ""; //will store file data
        bool flag = true;
        string headings = ""; //to store column headings
        foreach (DataTable table in tableDataSet.Tables)
        {
            foreach (DataRow row in table.Rows)
            {
                data += "\n"; // New line for each column
                foreach (DataColumn column in table.Columns)
                {
                    if(flag)
                        headings += column + ",";
                    data +=row[column]+",";
                }
                flag = false; //once we get heading setting to false;
            }
        }
        data = headings+data;
        Response.Clear();
        Response.ContentType = "application/CSV";
        Response.AddHeader("content-disposition", "attachment; filename=\"" + exportReport + ".csv\"");
        Response.Write(data);
        Response.End();
        return new EmptyResult();
    }
    else
    {  
         //redirecting to different page if no form data found.
        return RedirectToAction("index", "ExportImport");
    }
}

Hope this will help someone!!!

Generating and Formatting excelsheet in c# using EPPlus

  Comments or questions are welcome  
Tagged as