【问题标题】:How to extract a model objects into an .csv file如何将模型对象提取到 .csv 文件中
【发布时间】:2012-12-23 10:11:17
【问题描述】:

我有以下看法:-

@model IEnumerable<MvcApplication4.Models.customers> 

@{ 
    ViewBag.Title = "customer"; 
} 

<h3>Avialble cusotmer</h3> 
<table id ="avilalbe"> 
    <tr> 
        <th> 
           @Html.CheckBox("ORG_NAME ", true) NAME 
        </th> 
<th> 
           @Html.CheckBox("description ", true) Description 
        </th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 


        <td> 
            @Html.DisplayFor(modelItem => item.customer_NAME) 
        </td> 
<td> 
            @Html.DisplayFor(modelItem => item.description) 
        </td> 

    </tr> 
} 

   <a href=""> Extract To Excel </a>

如何根据用户从复选框中的选择将模型数据提取到 .csv 中(包括名称和描述列或仅包括其中之一)。

【问题讨论】:

  • 那么问题出在哪里?您不知道如何在服务器端获取复选框值或者您不知道如何创建 .csv 文件?
  • 不需要在服务器上设置复选框,但我不知道如何根据复选框状态创建 .csv 文件?谢谢

标签: javascript jquery asp.net asp.net-mvc asp.net-mvc-3


【解决方案1】:

如果我理解这个问题 - 只需使用对象转储器来解析值和名称,但老实说,我无法 100% 从上述问题中准确说出您想要什么。

Objectdumper 在这里可用: http://blogs.msdn.com/b/ericwhite/archive/2008/08/14/object-dumper-an-invaluable-tool-for-writing-code-in-the-functional-programming-style.aspx

【讨论】:

  • 我有一个包含两个列的表,根据用户选择,我需要将表数据提取到 .csv 文件中,例如,如果用户选中这两个复选框以提取整个表列,而如果他保持选中描述复选框以将所有描述记录仅提取到 .csv 文件中。
  • 如果您的意图只是动态创建 CSV 并进行流式传输,请参阅:stackoverflow.com/questions/6775248/…
【解决方案2】:

创建一个方法(类似的)

private static string GetCsvString(IEnumerable<Customer> customers, string separator, params string[] fields)
{
    var csvString = new StringBuilder();
    var propertyInfos = typeof (Customer).GetProperties().Where(p => fields.Contains(p.Name)).ToList();
    foreach (var customer in customers)
    {
        var currentCustomer = customer;
        csvString.AppendLine(string.Join(separator, propertyInfos.Select(p => p.GetValue(currentCustomer, null).ToString())));
    }

    return csvString.ToString();
}

然后使用它:

var csvString = GetCsvString(yourSetOfCustomers, ";", "name", "description");
File.WriteAllText("yourPath.csv", csvString);

如果你只需要描述,你会打电话:

GetCsvString(yourSetOfCustomers, ";", "description");

我假设您知道如何确定您需要哪些字段(根据您对我的评论的回答)。希望你明白了。

【讨论】:

  • 感谢您的回复,但您能否解释一下 yourPath.csv 应该指什么,因为我要即时创建 .csv 文件?并且没有一个已经存在的文件。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-01-30
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多