gpt4 book ai didi

c# - 从按日期范围查看的数据库数据导出到 csv asp.net mvc3

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:23 27 4
gpt4 key购买 nike

我正在尝试找到一种方法来从我的数据库中导出数据并将其保存为 .csv 文件。理想情况下,用户将能够在 View 上选择一个日期范围,该 View 将显示要导出的数据,然后用户可以单击“导出到 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
};

}
}

最佳答案

您可以在 Controller 操作中构建 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);
}

关于c# - 从按日期范围查看的数据库数据导出到 csv asp.net mvc3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337076/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com