Export CSV file using C# MVC

Posted on April 6, 2018 by Suresh Kamrushi in asp.net

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)
                        headings += column + ",";
                    data +=row[column]+",";
                flag = false; //once we get heading setting to false;
        data = headings+data;
        Response.ContentType = "application/CSV";
        Response.AddHeader("content-disposition", "attachment; filename=\"" + exportReport + ".csv\"");
        return new EmptyResult();
         //redirecting to different page if no form data found.
        return RedirectToAction("index", "ExportImport");

Hope this will help someone!!!

  Comments or questions are welcome  

Tagged as