+1-888-365-2779
Try Now
More in this section

Forums / Developing with Sitefinity / Export Content to CSV file sitefinity 9

Export Content to CSV file sitefinity 9

2 posts, 0 answered
  1. Chaitanya
    Chaitanya avatar
    22 posts
    Registered:
    14 Oct 2013
    16 Aug
    Link to this post

    Hi,

    I want to create a backend widget in Sitefinity to export my dynamic module content to a csv file. I have referred to this post, but instead of usercontrol I have used MVC Widget. It triggers the download but instead of returning a csv file with name mentioned in content-disposition header, it returns a file automatically named, and contains complete html along with file content. Is it due to the fact that a lot of changes are there regarding MVC in Sitefinity 9, because I have done this before in maybe 6 or 7 version. What should be done to accomplish this?

    Regards,

    Chaitanya.

  2. Chaitanya
    Chaitanya avatar
    22 posts
    Registered:
    14 Oct 2013
    16 Aug in reply to Chaitanya
    Link to this post

    Instead of writing directly to response, I changed my approach and used StreamWriter instead, now HTML is not written into the file but still file name and extension mentioned in content-disposition header are not applied, below is my code.

    public ActionResult export()
    {
    //Content Fetch logic
    var sw = new StreamWriter(new MemoryStream());
    HttpContext.Response.Clear();
    HttpContext.Response.ClearHeaders();
    HttpContext.Response.ClearContent();
    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=myFile.csv");
    Response.ContentType = "text/csv";
    Response.AddHeader("Pragma", "public");
    string columnNames = "C1, C2, C3, C4";
    sw.WriteLine(columnNames);
     
    foreach (var parentContent in parentContents)
    {
        var children = parentContent.GetChildItems(childType);
     
        foreach (var child in children)
        {
            //Some operations
     
            WriteInfo(model, sw);
        }
    }
    sw.Flush();
    sw.BaseStream.Seek(0, SeekOrigin.Begin);
     
    return new FileStreamResult(sw.BaseStream, "text/csv");
    }
     
    private void WriteInfo(ViewModel model, StreamWriter sw)
    {
        StringBuilder stringBuilder = new StringBuilder();
        //Create string of comma separated output values from model
        sw.WriteLine(stringBuilder);
    }

2 posts, 0 answered