我希望导出datagrid在wpf C#中表现优异,而GetClipboardContent()的代码是错误的?

时间:2017-07-26 06:39:11

标签: c# wpf

我使用的捆绑代码在Winform到WPF中运行良好。 代码在GetClipboardContent()时出错; 我用:

using Excel = Microsoft.Office.Interop.Excel; 
using System.IO;

public class MyCommon
{
    private static MainWindow mainWindow;

    public static void copyAlltoClipboard()
    {
        mainWindow.grdKQ_TASK.SelectAll();
        DataObject dataObj = mainWindow.grdKQ_TASK.GetClipboardContent(); 
        if (dataObj != null)
            Clipboard.SetDataObject(dataObj);
    }

    public static void releaseObject(object obj) 
    {
        //same at other post
    }

    public static void export2excel() 
    {
        copyAlltoClipboard();
        //same at other post
    }
}

错误:

  

'数据网格'不包含' GetClipboardContent'的定义和   没有扩展方法' GetClipboardContent'接受第一个论点   类型' DataGrid'可以找到(你是否错过了使用指令   或汇编参考?)

函数导出datagrid到excel,我在这里得到,2秒回答:How to export dataGridView data Instantly to Excel on button click?  怎么解决?

1 个答案:

答案 0 :(得分:0)

我最终找到了解决上述问题的另一种方法,用数据表替换剪贴板来存储数据网格视图。

  using Excel = Microsoft.Office.Interop.Excel;
  private void btnEX_Click(object sender, RoutedEventArgs e)
    {

        Excel.Application excel = null;
        Excel.Workbook wb = null;

        object missing = Type.Missing;
        Excel.Worksheet ws = null;
        Excel.Range rng = null;

        try
        {
            excel = new Microsoft.Office.Interop.Excel.Application();
            wb = excel.Workbooks.Add();
            ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;

            DataView view = (DataView)grdKQ_TASK.ItemsSource;
            DataTable dt = DataViewAsDataTable(view);

            for (int Idx = 0; Idx < dt.Columns.Count; Idx++)
            {
                ws.Range["A1"].Offset[0, Idx].Value = dt.Columns[Idx].ColumnName;
            }

            for (int Idx = 0; Idx < dt.Rows.Count; Idx++)
            {  

                ws.Range["A2"].Offset[Idx].Resize[1, dt.Columns.Count].Value = dt.Rows[Idx].ItemArray;
            }


            excel.Visible = true;
            wb.Activate();
        }
        catch (COMException ex)
        {
            MessageBox.Show("Error accessing Excel: " + ex.ToString());
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.ToString());
        }
    }
    public static DataTable DataViewAsDataTable(DataView dv)
    {
        DataTable dt = dv.Table.Clone();
        foreach (DataRowView drv in dv)
            dt.ImportRow(drv.Row);
        return dt;
    }

我希望能帮助别人。