我正在尝试从数据库中导出数据并将其另存为.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
};
}
}
答案 0 :(得分: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);
}