Search code examples
asp.net-mvcasp.net-mvc-2export-to-excel

Export to text or excel from MVC controller


What I have already : I have controller code churning up some values / calculations and sending them to the View. Right now, I am displaying all results on the view page.

What I am trying to do : Export those results that are displayed on the view to a text or excel file on press of a button "Export"

Using : MVC

Sample code I have

Controller:

    public ActionResult Calculations()
    {       
            dynamic CalcModel = new ExpandoObject();
            int var1 = //Value calculated here
            int var2 = //Calculation

            CalcModel.Var1= var1;
            CalcModel.Var2= var2;

            return View(CalcModel);

    }

View:

<table>
   <tr><td>First Value:</td><td><%=Model.Var1%></td></tr>
   <tr><td>Second Value:</td><td><%=Model.Var2%></td></tr>
</table>

I want to be able to write these values from the controller to a text file or excel file and let the user save the file. Thanks for the help.

EDIT:

I found a solution (kind of) but need further help:

Latest Controller code:

    public ActionResult Calculations()
    {       
            dynamic CalcModel = new ExpandoObject();
            int var1 = //Value calculated here
            int var2 = //Calculation

            CalcModel.Var1= var1;
            CalcModel.Var2= var2;   

            //Export code.

            string csv = "Value1 = " + var1 + "|| Value2 = " + var2; 
            return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", 
            "Report.txt"); 

            //Export code end.

            return View(CalcModel);                  

    }

This generates a text file with the values printed in it. But How do I get each value printed in a separate line.. right now all values are printed in one flat line.


Solution

  • Envrionment.NewLine should do it:

    var builder = new StringBuilder();
    //this is probably a loop...
    builder.AppendFormat("1,2{0}", Envrionment.NewLine);
    builder.AppendFormat("3,4{0}", Envrionment.NewLine);
    
    File(new System.Text.UTF8Encoding().GetBytes(builder.ToString()), "text/csv", 
            "Report.txt"); 
    

    Edit: You can try \n as well.

    string csvText = string.Format("First Value,{0}\nSecond Value,{1}",var1, var2);
    File(new System.Text.UTF8Encoding().GetBytes(csvText), "text/csv", 
            "Report.txt");