2

I am trying to find a way to export data from my database and save it as a .csv file. Ideally the user will be able to select a date range on a view, which will display the data to be exported, then the user can click an "export to CSV" link. I've done quite a bit of searching and but have not found much specific enough to help me step through the process. Any help would be great.

I would like to export data from this database model...

{
public class InspectionInfo
{
    [Key]
    public int InspectionId { get; set; }
    [DisplayName("Date Submitted")]
    [DataType(DataType.Date)]
    //  [Required]
    public DateTime Submitted { get; set; }
    [DataType(DataType.MultilineText)]
    [MaxLength(1000)]
    //  [Required]
    public string Comments { get; set; }




    // [Required]
    public Contact Contact { get; set; }
    [ForeignKey("Contact")]
    public Int32 ContactId { get; set; }

    [MaxLength(100)]
    public String OtherContact { get; set; }

I have a service for search also, just having difficulty implementing

public SearchResults SearchInspections(SearchRequest request)
    {
        using (var db = new InspectionEntities())
        {
            var results = db.InspectionInfos
                .Where( i=> 
                        (
                            (null == request.StartDate || i.Submitted >=   request.StartDate.Value) &&
                            (null == request.EndDate || i.Submitted <= request.EndDate.Value)
                        )

            )
            .OrderBy(i=>i.Submitted)
            .Skip(request.PageSize*request.PageIndex).Take(request.PageSize);

            return new SearchResults{
                TotalResults=results.Count(),
                PageIndex=request.PageIndex,
                Inspections=results.ToList(),
                SearchRequest=request
        };

        }
    }
Eric J.
  • 147,927
  • 63
  • 340
  • 553
WiseGuy
  • 409
  • 1
  • 8
  • 19
  • One option which would perform well is BCP - but that's a direct SQL thing rather than through an app, so may not be what you're after: http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/ – JohnLBevan Nov 12 '12 at 00:50
  • Thats pretty neat, but what I'm really hoping for is something like an Export to csv actionresult. – WiseGuy Nov 12 '12 at 00:53

1 Answers1

1

You can build the CSV output in a controller action and return it directly to the browser like this:

public ActionResult DownloadAsCsv(DateTime? start, DateTime? finish)
{
    // I guess you would use your SearchInspections instead of the following
    // but don't understand it well enough to be sure:

    IEnumerable<MyRowClass> rows = GetRelevantRows(start, finish);

    StringBuilder csv = new StringBuilder();
    foreach (MyRowClass row in rows)
    {
        // Take care to properly escape cells with embedded " or ,
        // The following is simplified by not doing that for brevity:
        csv.Append(row.PropertyA).Append(',').Append(row.PropertyB);
        csv.AppendLine();
    }

    var data = Encoding.UTF8.GetBytes(csv.ToString());
    string filename = "YourDesiredFileName.csv";
    return File(data, "text/csv", filename);
}
Eric J.
  • 147,927
  • 63
  • 340
  • 553