Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export HTML Table in asp.net MVC

Tags:

c#

asp.net-mvc

I trying to export an HTML table named Table that is dynamically binded to ViewData.Model in C#. I have a method called export that is called based on another method's actions. so everything before that is set up.. I just don't know how to export the data to a CSV or Excel file.. So when the I step inside the Export method I don't know what next to do to export the table. Can someone help me

    public void Export(List<data> List)
    {
     //the list is the rows that are checked and need to be exported
       StringWriter sw = new StringWriter();

     //I don't believe any of this syntax is right, but if they have Excel export to excel and if not export to csv  "|" delimeted

   for(int i=0; i<List.Count;i++)
    {
              sw.WriteLine(List[i].ID+ "|" + List[i].Date + "|" + List[i].Description);

    }
    Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
    Response.ContentType = "application/ms-excel";
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
    Response.Write(sw);
    Response.End(); 

    }
like image 344
TStamper Avatar asked Jan 09 '09 20:01

TStamper


People also ask

How can I download Excel file in ASP NET MVC?

Step 1: Create a new ASP.NET web application project. Step 2: Complete the New ASP.NET Web Application – CreateXlsIOSample dialog: Select MVC. Click OK.


1 Answers

I don't quite understand the whole "export an HTML table named Table that is dynamically binded to ViewData.Model" so I'll just ignore that and focus on your Export(List<data> list) method. Btw, you never really mentioned what was going wrong and where.

I see you had written "if they have Excel export to excel and if not export to csv" - I would personally just export it as a CSV file in both cases because excel can handle csv files no problem.

So with that in mind, here would be my export method based on your code.

public void Export(List<DataType> list)
{
    StringWriter sw = new StringWriter();

    //First line for column names
    sw.WriteLine("\"ID\",\"Date\",\"Description\"");

    foreach(DataType item in list)
    {
        sw.WriteLine(string.format("\"{0}\",\"{1}\",\"{2}\"",
                                   item.ID,
                                   item.Date,
                                   item.Description));
    }

    Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
    Response.ContentType = "text/csv";
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
    Response.Write(sw);
    Response.End(); 
}
like image 131
Charlino Avatar answered Oct 05 '22 23:10

Charlino