简体   繁体   English

访问IQueryable / System.Collections.Generic.List的内容?

[英]Access the contents of an IQueryable/System.Collections.Generic.List?

I have an MVC5/Code-First application I'm developing using Entity Framework. 我有一个使用实体框架开发的MVC5 /代码优先应用程序。 Currently I'm trying to add Export to Excel functionality to output user selected properties of my INV_Assets model dynamically. 目前,我正在尝试添加“导出到Excel”功能以动态输出用户选择的INV_Assets模型的属性。 Using the EPPlus Libary and Linq.Dynamic I have managed to export my data to excel, but not quite correctly. 通过使用EPPlus Libary和Linq.Dynamic我设法将数据导出到excel,但是不太正确。

I've gotten the Headers to export into Row 1, but I'm still having difficulty getting the data to export. 我已经将标头导出到第1行,但是我仍然很难导出数据。 Currently the data for my selected fields all comes across, but each value is exported as a long string into it's own row in Column A. For example, if I select the following fields (Status, ip_address, mac_address, note, owner, cost, po_number, and description) I get the following: 目前,我所选择的字段的数据都可以使用,但是每个值都作为长字符串导出到A列中自己的行中。例如,如果我选择以下字段(状态,ip_address,mac_address,注释,所有者,成本, po_number和说明),我得到以下信息:

Row1: [Status][ip_address][mac_address][note][owner][cost][po_number][description] 第1行: [Status][ip_address][mac_address][note][owner][cost][po_number][description]

Row2: [{Status=SIGNEDOUT, ip_address=10.10.121.25, mac_address=10.10.134.11, note=, owner=John Smith, cost=35.00, po_number=G348, description=This is a description of the item.}][][][][][][][] 第2列: [{Status=SIGNEDOUT, ip_address=10.10.121.25, mac_address=10.10.134.11, note=, owner=John Smith, cost=35.00, po_number=G348, description=This is a description of the item.}][][][][][][][]

Here is a visual of the output I'm currently getting in Excel: 这是我目前在Excel中获得的输出的视觉效果:

ExcelOutput

When I set my IQueryable variable ( selectStatement ) as a Watch variable in VS2013 I am able to drill down into the contents, but I can't figure out how to access these contents individually in code: 当我在VS2013中将IQueryable变量( selectStatement )设置为Watch变量时,我可以深入研究内容,但无法弄清楚如何在代码中单独访问这些内容:

IQueryable的

Currently I use my IQueryable and load it into Excel via the EPPlus LoadFromCollection() method, but if I can figure out how to access individual contents of my IQueryable I can then set up some counters and loops to appropriately set the cells I want instead of everything dumping into ColumnA. 当前,我使用IQueryable并通过EPPlus LoadFromCollection()方法将其加载到Excel中,但是如果我能弄清楚如何访问IQueryable各个内容,则可以设置一些计数器和循环来适当地设置所需的单元格,而不是一切都转储到ColumnA中。

Can anyone assist with this? 有人可以协助吗? Full code for my ExportController below: 我的ExportController完整代码如下:

    public ActionResult ExportUsingEPPlus(ExportAssetsViewModel model)
    {
        ExcelPackage package = new ExcelPackage();
        var ws = package.Workbook.Worksheets.Add("TestExport");

        var exportFields = new List<string>();
        foreach (var selectedField in model.SelectedFields)
        {
            // Adds selected fields to [exportFields] List<string>
            exportFields.Add(model.ListOfExportFields.First(s => s.Key == selectedField).Value);
        }

        IQueryable selectStatement = DynamicSelectionColumns(exportFields);

        // Loops to insert column headings into Row 1 of Excel
        for (int i = 0; i < exportFields.Count(); i++)
        {
            ws.Cells[1, i + 1].Value = exportFields[i].ToString();
        }

        // Place contents of IQueryable into Excel -- currently dumps selected value for each record into rows with all values for the row as a long string in ColumnA
        if (selectStatement.Count() > 0)
        {
            ws.Cells["A2"].LoadFromCollection(selectStatement.Cast<object>(), true);
        }

        int cnt = 20;
        foreach (var item in selectStatement)
        {
            ws.Cells["A" + cnt].LoadFromCollection(selectStatement.Cast<object>(), false);
            cnt++;

        }


        var memoryStream = new MemoryStream();
        package.SaveAs(memoryStream);

        string fileName = "Exported-InventoryAssets-" + DateTime.Now + ".xlsx";
        string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        memoryStream.Position = 0;
        return File(memoryStream, contentType, fileName);
    }

    public IQueryable DynamicSelectionColumns(List<string> fieldsForExport)
    {
        using (var db = new InventoryTrackerContext())
        {
            string fieldIds = "," + "4,5,3,2,6,17,11,12" + ",";

            var taskColum = Enum.GetValues(typeof(EnumTasks)).Cast<EnumTasks>().Where(e => fieldIds.Contains("," + ((int)e).ToString() + ",")).Select(e => e.ToString().Replace("_", ""));

            //string select = "new (  TaskId, " + (taskColum.Count() > 0 ? string.Join(", ", taskColum) + ", " : "") + "Id )";
            string select = "new (  " + string.Join(", ", fieldsForExport) + ")";

            //return db.INV_Assets.ToList().Select(t => new DynamicColumns() { Id = t.Id, TaskId = Project != null ? Project.Alias + "-" + t.Id : t.Id.ToString(), 
            return db.INV_Assets.ToList().Select(t => new DynamicColumns()
            {
                Id = t.Id,
                Manufacturer = Convert.ToString(t.Manufacturer.manufacturer_description),
                Type = t.Type.type_description,
                Location = t.Location.location_room,
                Vendor = t.Vendor.vendor_name,
                Status = t.Status.status_description,
                ip_address = t.ip_address,
                mac_address = t.mac_address,
                note = t.note,
                owner = t.owner,
                //Module = t.Module != null ? t.Module.Name : "", 
                cost = t.cost,
                po_number = t.po_number,
                description = t.description,
                invoice_number = t.invoice_number,
                serial_number = t.serial_number,
                asset_tag_number = t.asset_tag_number,
                acquired_date = t.acquired_date,
                disposed_date = t.disposed_date,
                verified_date = t.verified_date,
                created_date = t.created_date,
                created_by = t.created_by,
                modified_date = t.modified_date,
                modified_by = t.modified_by
            }).ToList().AsQueryable().Select(select);
        }
    }
}

public class DynamicColumns : INV_Assets
{
    public string Model { get; set; }
    public string Manufacturer { get; set; }
    public string Type { get; set; }
    public string Location { get; set; }
    public string Vendor { get; set; }
    public string Status { get; set; }
    public string ip_address { get; set; }
    public string mac_address { get; set; }
    public string note { get; set; }
    public string owner { get; set; }
    public decimal cost { get; set; }
    public string po_number { get; set; }
    public string description { get; set; }
    public int invoice_number { get; set; }
    public string serial_number { get; set; }
    public string asset_tag_number { get; set; }
    public DateTime? acquired_date { get; set; }
    public DateTime? disposed_date { get; set; }
    public DateTime? verified_date { get; set; }
    public DateTime created_date { get; set; }
    public string created_by { get; set; }
    public DateTime? modified_date { get; set; }
    public string modified_by { get; set; }
}

public enum EnumTasks
{
    Model = 1,
    Manufacturer = 2,
    Type = 3,
    Location = 4,
    Vendor = 5,
    Status = 6,
    ip_address = 7,
    mac_address = 8,
    note = 9,
    owner = 10,
    cost = 11,
    po_number = 12,
    description = 13,
    invoice_number = 14,
    serial_number = 15,
    asset_tag_number = 16,
    acquired_date = 17,
    disposed_date = 18,
    verified_date = 19,
    created_date = 20,
    created_by = 21,
    modified_date = 22,
    modified_by = 23
}

The output you are getting in your non-header cells: 您在非标题单元格中获得的输出:

Status=SIGNEDOUT, ip_address=10.10.121.25, mac_address=10.10.134.11, note=, owner=John Smith, cost=35.00, po_number=G348, description=This is a description of the item. 状态= SIGNEDOUT,ip_address = 10.10.121.25,mac_address = 10.10.134.11,note =,所有者= John Smith,成本= 35.00,po​​_number = G348,description =这是该项目的描述。

looks like the object represented as property=value , separated by commas. 看起来像用property=value表示的对象,用逗号分隔。 I would guess that the object's ToString() method is overridden and creating that output. 我猜想该对象的ToString()方法将被覆盖并创建该输出。

Since you are casting your strongly typed objects to System.Object 由于将强类型对象投射到System.Object

selectStatement.Cast<object>()

that is probably the best that EPPlus can do. 那可能是EPPlus可以做的最好的事情。

Try not casting it to System.Object, eg 尽量不要将其强制转换为System.Object,例如

ws.Cells["A2"].LoadFromCollection(selectStatement, true);

Here's an article that shows proper use of LoadFromCollection 这是一篇文章,显示LoadFromCollection的正确使用

http://www.sitecorecleveland.com/resources/blogs-posts/easy_excel_interaction_pt5 http://www.sitecorecleveland.com/resources/blogs-posts/easy_excel_interaction_pt5

UPDATE UPDATE

The error 错误

The type arguments for method 'OfficeOpenXml.ExcelRangeBase.LoadFromCollection(System.Collection.Generic.IE‌​numerable, bool)' cannot be inferred from the usage. 无法从用法中推断出方法'OfficeOpenXml.ExcelRangeBase.LoadFromCollection(System.Collection.Generic.IE‌numerable,bool)'的类型参数。 Try specifying the type arguments explicitly. 尝试显式指定类型参数。

is telling you that you need to specify the actual type returned by the query (rather than specifying object ). 告诉您您需要指定查询返回的实际类型(而不是指定object )。

ws.Cells["A2"].LoadFromCollection(selectStatement.Cast<DynamicColumns>(), true);

暂无
暂无

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

相关问题 无法将类型为“ System.Collections.Generic.List`1 []”的对象强制转换为类型为“ System.Linq.IQueryable`1 []”的对象 - Unable to cast object of type 'System.Collections.Generic.List`1[]' to type 'System.Linq.IQueryable`1[]' 无法从&#39;System.Collections.Generic.List转换<System.Linq.IQueryable<> - cannot convert from 'System.Collections.Generic.List<System.Linq.IQueryable<> 无法隐式转换类型&#39;System.Collections.Generic.List <T> &#39;to&#39;System.Linq.IQueryable <T> “ - Cannot implicitly convert type 'System.Collections.Generic.List<T>' to 'System.Linq.IQueryable<T>' 无法将类型&#39;System.Linq.IQueryable&#39;隐式转换为&#39;System.Collections.Generic.List - Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.List 无法将类型“System.Linq.IQueryable”隐式转换为“System.Collections.Generic.List” - Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.List' C# List.AsQueryable() 返回 System.Collections.Generic.List 而不是 IQueryable - C# List.AsQueryable() returns System.Collections.Generic.List instead of IQueryable system.collections.generic.list 到 system.collections.generic.ienumerable - system.collections.generic.list to system.collections.generic.ienumerable “ System.Collections.Generic.List`1” SerializationBinder BindToType - “System.Collections.Generic.List`1” SerializationBinder BindToType Route属性中的“ System.Collections.Generic.List &lt;&gt;” - 'System.Collections.Generic.List<>' in Route attribute 在System.Collections.Generic.List中的Find() <T> - Find() In a System.Collections.Generic.List<T>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM