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 に答える