使用mvc3以csv格式下载不同的表列

时间:2011-07-04 09:18:43

标签: asp.net-mvc asp.net-mvc-2 asp.net-mvc-3 csv

我想使用mvc3从sql server下载不同的列数据。例如,我想从表帐户中下载5列,其中id = 1,以及2列来自产品,其中id = 1。任何人都可以为我提供一些教程或任何链接来实现这一目标。感谢

1 个答案:

答案 0 :(得分:0)

你可以做点什么

public ActionResult ExportCsv(int page, string orderBy, string filter)
        {
            IEnumerable orders = GetOrders().AsQueryable().ToGridModel(page, 10, orderBy, string.Empty, filter).Data;
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
            writer.Write("OrderID,");
            writer.Write("ContactName,");
            writer.Write("ShipAddress,");
            writer.Write("OrderDate");
            writer.WriteLine();
            foreach (Order order in orders)
            {
                writer.Write(order.OrderID);
                writer.Write(",");
                writer.Write("\"");
                writer.Write(order.Customer.ContactName);
                writer.Write("\"");
                writer.Write(",");
                writer.Write("\"");
                writer.Write(order.ShipAddress);
                writer.Write("\"");
                writer.Write(",");
                writer.Write(order.OrderDate.Value.ToShortDateString());
                writer.WriteLine();
            }
            writer.Flush();
            output.Position = 0;

            return File(output, "text/comma-separated-values", "Orders.csv");
        }

有关详细信息,请访问Telerik Demos。您不需要使用telerik来实现此功能。只需编写actionresult,获取数据将其转换为csv,从浏览器调用它就完成了。