2012-11-12 96 views
2

我想從我的數據庫中導出數據並將其保存爲.csv文件。理想情況下,用戶將能夠在視圖上選擇日期範圍,該日期範圍將顯示要導出的數據,然後用戶可以單擊「導出到CSV」鏈接。我做了很多搜索,但還沒有發現足夠的具體內容來幫助我逐步完成整個過程。任何幫助都會很棒。從日期範圍asp.net導出數據庫數據到csv mvc3

我想將數據從該數據庫模型導出...

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

     } 
    } 
+0

一個選項可以很好地執行但是這是一個直接的SQL事情,而不是通過一個應用程序,所以可能不是你所追求的:http://www.simple-talk.com/sql/database-administration/creating-csv-files-using -bcp-and-stored-procedures/ – JohnLBevan

+0

這很漂亮,但我真正希望的是類似於導出到csv actionresult的東西。 – WiseGuy

回答

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