c# - WPF - 将 DataGrid 导出到 Excel,Microsoft.Office.Interop.Excel 替代 Office 2019

标签 c# excel wpf datagrid office-interop

关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。












我们不允许提出有关书籍、工具、软件库等建议的问题。您可以编辑问题,以便可以用事实和引用来回答它。


11 个月前关闭。







Improve this question




我正在尝试将我的 DataGrid 导出到 Excel (Office 2019/365)。
我的方法是使用 Microsoft.Office.Interop.Excel扩展,但它会引发异常,我了解到它仅适用于 Office 2013。
所以我的问题是 , 是否有任何适用于 Office 2019 的扩展可以与 Microsoft.Office.Interop.Excel 互换? ?尽可能少地进行重构会很棒。
我的方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Microsoft.Office.Interop.Excel;

namespace My.NameSpace {

    class ExcelExport {

        public static void ExportDataGrid(object sender) {

            DataGrid currentGrid = sender as DataGrid;
            if (currentGrid != null) {

                StringBuilder sbGridData = new StringBuilder();
                List<string> listColumns = new List<string>();

                List<DataGridColumn> listVisibleDataGridColumns = new List<DataGridColumn>();

                List<string> listHeaders = new List<string>();

                Microsoft.Office.Interop.Excel.Application application = null;
                Workbook workbook = null;
                Worksheet worksheet = null;

                int rowCount = 1;
                int colCount = 1;

                try {

                    application = new Microsoft.Office.Interop.Excel.Application();
                    workbook = application.Workbooks.Add(Type.Missing);
                    worksheet = (Worksheet)workbook.Worksheets[1];

                    if (currentGrid.HeadersVisibility == DataGridHeadersVisibility.Column || currentGrid.HeadersVisibility == DataGridHeadersVisibility.All) {

                        foreach (DataGridColumn dataGridColumn in currentGrid.Columns.Where(dataGridColumn => dataGridColumn.Visibility == Visibility.Visible)) {

                            listVisibleDataGridColumns.Add(dataGridColumn);
                            if (dataGridColumn.Header != null) {

                                listHeaders.Add(dataGridColumn.Header.ToString());
                            }

                            worksheet.Cells[rowCount, colCount] = dataGridColumn.Header;
                            colCount++;
                        }

                        // IEnumerable collection = currentGrid.ItemsSource

                        foreach (object data in currentGrid.ItemsSource) {

                            listColumns.Clear();
                            colCount = 1;
                            rowCount++;

                            foreach (DataGridColumn dataGridColumn in listVisibleDataGridColumns) {

                                string strValue = string.Empty;
                                Binding objBinding = null;
                                DataGridBoundColumn dataGridBoundColumn = dataGridColumn as DataGridBoundColumn;

                                if (dataGridBoundColumn != null) {

                                    objBinding = dataGridBoundColumn.Binding as Binding;
                                }

                                DataGridTemplateColumn dataGridTemplateColumn = dataGridColumn as DataGridTemplateColumn;

                                if (dataGridTemplateColumn != null) {

                                    // this is a template column, let's see the underlying dependency object
                                    DependencyObject dependencyObject = dataGridTemplateColumn.CellTemplate.LoadContent();

                                    FrameworkElement frameworkElement = dependencyObject as FrameworkElement;

                                    if (frameworkElement == null) {

                                        FieldInfo fieldInfo = frameworkElement.GetType().GetField("ContentProperty", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
                                        
                                        if (fieldInfo == null) {

                                            if (frameworkElement is System.Windows.Controls.TextBox || frameworkElement is TextBlock || frameworkElement is ComboBox) {

                                                fieldInfo = frameworkElement.GetType().GetField("TextProeprty");

                                            } else if (frameworkElement is DatePicker) {

                                                fieldInfo = frameworkElement.GetType().GetField("SelectedDateProperty");
                                            }
                                        }

                                        if (fieldInfo != null) {

                                            DependencyProperty dependencyProperty = fieldInfo.GetValue(null) as DependencyProperty;
                                            if (dependencyProperty != null) {

                                                BindingExpression bindingExpression = frameworkElement.GetBindingExpression(dependencyProperty);
                                                if (bindingExpression != null) {

                                                    objBinding = bindingExpression.ParentBinding;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (objBinding != null) {

                                    if (!String.IsNullOrEmpty(objBinding.Path.Path)) {

                                        PropertyInfo pi = data.GetType().GetProperty(objBinding.Path.Path);

                                        if (pi != null) {

                                            object propValue = pi.GetValue(data, null);

                                            if (propValue != null) {

                                                strValue = Convert.ToString(propValue);

                                            } else {

                                                strValue = string.Empty;
                                            }
                                        }
                                    }

                                    if (objBinding.Converter != null) {

                                        if(!String.IsNullOrEmpty(strValue)) {

                                            strValue = objBinding.Converter.Convert(strValue, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();

                                        } else {

                                            strValue = objBinding.Converter.Convert(data, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
                                        }
                                    }
                                }

                                listColumns.Add(strValue);

                                worksheet.Cells[rowCount, colCount] = strValue;

                                colCount++;
                            }
                        }
                    }

                } catch (System.Runtime.InteropServices.COMException) {

                } finally {

                    workbook.Close();
                    application.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
                }
            }
        }
    }
}

最佳答案

它可能没有相同的 api,但 EPPlus 是从 c# 创建 excel 文件的好选择。
它不使用互操作库,因此它不依赖于安装的 Office 版本(根本不需要 office)。
版本 4.5.3是使用 LGPL 许可证的最后一个版本,以后的版本有双重许可证,用于商业用途是收费的。

关于c# - WPF - 将 DataGrid 导出到 Excel,Microsoft.Office.Interop.Excel 替代 Office 2019,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68847809/

相关文章:

c# - 发布时的 TransformXml Web.config

c# - DataGrid 获取选中行的列值

c# - 调整 Window Forms 应用程序大小时如何保持纵横比?

c# - 将 mysql 数据库中的字符串日期与 Entity Framework c# 进行比较

c# - WPF DynamicDataDisplay - 在 Y 轴上放置字符串而不是数字

Excel VBA动态数据验证给出 "Application-defined object"错误

excel - 在多个 Excel 实例之一中查找工作簿

excel - 如何在 Excel 中表示日期时间

wpf - 解锁用于 VS2010 的 Ribbon WPF 程序集

c# - 为什么我不能本地化我的 WPF 程序?我在 PresentationFramework.dll 中得到 "Exception thrown: ' System.Windows.Markup.XamlParseException'