Export Content to CSV file sitefinity 9

Posted by Community Admin on 04-Aug-2018 07:16

Export Content to CSV file sitefinity 9

All Replies

Posted by Community Admin on 16-Aug-2016 00:00

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.

Posted by Community Admin on 16-Aug-2016 00:00

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);

This thread is closed