来自DataGrid的DataExport:用更通用的东西替换switch / case

时间:2014-10-15 07:51:14

标签: c# .net wpf generics radgridview

我有一个显示项目的数据网格。 datagrid绑定到ObservableCollection类型的属性DataGridItems。在代码中,我动态地实例化DataGridItems属性,如下所示:

this.DataGridItems = Db.Instance.RetrieveFoldingBoxes();

this.DataGridItems = Db.Instance.RetrieveLabels();

现在我想导出数据网格中显示(和过滤/排序)的数据。 我可以这样做:

    private void ExportData(ControlDataGrid dataGrid)
    {
        if (dataGrid == null) return;

        //items is type of Telerik.Windows.Data.DataItemCollection
        var items = dataGrid.GetFilteredCollection();

        switch (this.GetSelectedViewComboBoxItemName)
        {
            case "Folding Box":
                var exportItems1 = items.Cast<View_DataExport_FoldingBox>();
                this.GenericExport(exportItems1);
                break;

            //30 cases more...

            case "Label":
                var exportItems2 = items.Cast<View_DataExport_Label>();
                this.GenericExport(exportItems2);
                break;
        }
    }

    private void GenericExport<T>(IEnumerable<T> list) { ... }

但由于这种高冗余度,我真的不喜欢这样。如果我可以做这样的事情,那将会更加优雅:

    private void ExportData(ControlDataGrid dataGrid)
    {
        if (dataGrid == null) return;

        //items == Telerik.Windows.Data.DataItemCollection
        var items = dataGrid.GetFilteredCollection();

        //Getting the generic type in pseudo code
        //Also far from a good solution because I think CurrentItem could be null
        if(items.CurrentItem == null) return;
        var type = Type.GetType(items.CurrentItem);

        var exportItems = items.Cast<type>();

        this.GenericExport<type>(exportItems);
    }

我确定它有可能以某种方式但目前我不知道如何。


修改 这是GenericExport方法的代码:

    private void GenericExport<T>(IEnumerable<T> list)
    {
        using (var excelPackage = new ExcelPackage())
        {
            var name = this.GetSelectedViewComboBoxItemName;

            excelPackage.Workbook.Properties.Company = "COMPANYNAME";
            excelPackage.Workbook.Properties.Author = Configuration.UserName;
            excelPackage.Workbook.Properties.Title = string.Concat("Export for ", name);
            excelPackage.Workbook.Properties.Category = "CATEGORY";

            var worksheet = excelPackage.Workbook.Worksheets.Add(name);

            worksheet.Cells["A1"].LoadFromCollection(list, true, TableStyles.Medium2);
            ExcelSheetFormatter.FormatWorksheet(worksheet, list);

            var fileName = this.GetSelectedViewComboBoxItemName;

            var fileDestination = DataExportHelper.ShowSaveFileDialog(fileName, false);

            if (fileDestination == null) return;

            try
            {
                excelPackage.SaveAs(fileDestination);
            }
            catch (InvalidOperationException)
            {
                throw new PulseException(ExceptionMessage.FileInUse, false);
            }

            DataExportHelper.OpenExportedFileDialog(fileDestination.FullName);
        }
    }

我使用EPPlus 4.0 Beta 2(epplus.codeplex.com/releases/view/118053)将数据导出到Excel。

因此,我必须使用EPPlus的API:

    public ExcelRangeBase LoadFromCollection<T>(IEnumerable<T> Collection, ...);

1 个答案:

答案 0 :(得分:1)

如果您无法更改GenericExport签名,那么,我很害怕,反思是您唯一的朋友。假设items implement IList包含相同类型的项目,并且它不是空的:

// make IEnumerable<YourType>
var itemType = items[0].GetType();
var castDef = typeof(Enumerable).GetMethod("Cast");
var cast = castDef.MakeGenericMethod(itemType);
var enumerable = cast.Invoke(null, new[] { items });

// call GenericExport<YourType>
var methodDef = typeof(Program).GetMethod("GenericExport", BindingFlags.Instance | BindingFlags.NonPublic);
var method = methodDef.MakeGenericMethod(itemType);

method.Invoke(this, new[] { enumerable });