2

我正在尝试找到一种从我的数据库中导出数据并将其保存为 .csv 文件的方法。理想情况下,用户将能够在视图上选择一个日期范围,该日期范围将显示要导出的数据,然后用户可以单击“导出为 CSV”链接。我已经进行了很多搜索,但没有找到足够具体的内容来帮助我逐步完成整个过程。任何帮助都会很棒。

我想从此数据库模型中导出数据...

{
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; }

我也有搜索服务,只是难以实施

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

        }
    }
4

1 回答 1

1

您可以在控制器操作中构建 CSV 输出并将其直接返回到浏览器,如下所示:

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);
}
于 2012-11-12T00:56:12.123 回答