简体   繁体   English

如何使用mvc c#导出到网格中显示的csv文件

[英]how to export to csv file as it is shown in grid using mvc c#

I have a grid with the following consist of file columns and header as its shown in the following : 我有一个网格,其中包括文件列和标头,如下所示:

   List<string> eventResult = (from c in DB.Events
                                    where (c.m_turbine_id == turbineid.turbineID) && (c.m_time_stamp >= frmDate && c.m_time_stamp <= toDate)

                                    select new EventLogPartialViewModel
                                    {
                                        Timestamp = c.m_time_stamp,
                                        Description = c.m_event_log_description,
                                        WindSpeed = c.m_wind_speed,
                                        RPM = c.m_rpm,
                                        Power = c.m_power
                                    }).ToList().Select(x =>
                  x.Timestamp.ToString("dd/MM/yyyy H:mm:ss") + "," +
                  x.Description + "," +
                  x.WindSpeed + "," +
                  x.RPM + "," +
                  x.Power)

             .ToList();

Im using the following conversion to get CSV file: 我使用以下转换来获取CSV文件:

 string sss=string.Join(",",eventResult.ToArray());         
 byte[] csvBytes = ASCIIEncoding.ASCII.GetBytes(sss);

here I export: 我在这里出口:

 return this.File(csvBytes, "text/csv",".csv");

when I open the file, headers are missing and all my data is in a single line,not like a grid 当我打开文件时,标题丢失并且我的所有数据都在一行中,而不是像网格一样

You've already joined fields by comma in your last select statement, so final Join should be by new line. 您在上一个select语句中已经用逗号加入了字段,因此最终的Join应该用换行。

string sss = string.Join(Environment.NewLine, eventResult.ToArray());

Typically I use CsvHelper for generating csv files, since I don't want to validate or escape double quotation marks and commas in my input string. 通常,我使用CsvHelper生成csv文件,因为我不想在输入字符串中验证或转义双引号和逗号。 These are quite common characters that can disrupt the file. 这些是非常常见的字符,可能会破坏文件。

For including a header full code is: 包含标头的完整代码是:

string header = "Timestamp,Description,WindSpeed,RPM,Power";
string rows = string.Join(Environment.NewLine, eventResult.ToArray());
byte[] csvBytes = ASCIIEncoding.ASCII.GetBytes(header + Environment.NewLine + rows);
return File(csvBytes, "text/csv", ".csv");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM