使用Winforms控件将Excel嵌入到WPF中

时间:2019-03-04 08:33:14

标签: excel wpf office-interop excel-interop windowsformshost

我正在尝试将Excel嵌入到WPF应用程序中。原因是,我的用户必须打开一个大型(5000+行,100 +列)只读excel,对其进行过滤,然后我必须如图所示提取这些行并进行大量的后处理。我正在尝试为此使用互操作。在这里进入教程https://www.cnblogs.com/redalert2c/articles/2760352.html,我得到以下结果-Excel在窗口中显示为嵌入式,我可以通过单击GUI中的按钮来打开文件,也可以与excel中的菜单进行交互(切换功能区)栏内容,选择下拉菜单,打开对话框...)。但是,我不能与工作表本身进行交互!在第一个选项卡中选定的单元格只是A1,我既不能选择其他选项卡,也不能滚动或过滤。可能是个问题吗?

我的代码:

public partial class ExcelView : UserControl
{

    /**
     * Solution based upon https://www.cnblogs.com/redalert2c/articles/2760352.html
     * */
    public ExcelView()
    {
        InitializeComponent();
        Init();
        // setup the Handler to ExcelView_Resize
        this.Resize += new EventHandler(ExcelViewer_Resize);
    }

    #region Fields

    private Application application;
    private Process process;
    public IntPtr excelHandle;
    private bool initialized = false;
    private Workbooks workbooks;
    private Workbook workbook;
    private CultureInfo threadCulture;

    #endregion Fields
    #region Hosting Excel Properties
    public bool Saved { get { return workbook.Saved; } }
    public Microsoft.Office.Interop.Excel.Application Application { get { return application; } }
    public Workbook Workbook { get { return workbook; } }

    #endregion Hosting Excel Properties



    #region Proxy Method
    public void Init()
    {
        threadCulture = Thread.CurrentThread.CurrentCulture;
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

        application = new Application();
        application.WindowState = XlWindowState.xlNormal;

        application.Visible = true;
        application.DisplayFormulaBar = true;

        excelHandle = new IntPtr(application.Hwnd); // get the excelHandle, it is created in a separate process, through the use of 
                                                    // Hwnd, we can get to the handle to the main Wnd 
        SetParent(excelHandle, this.Handle);       // set the current Host as the Parent of the Excel Hwnd
        int lngStyle = GetWindowLong(excelHandle, GWL_STYLE);
        lngStyle = lngStyle ^ WS_CAPTION;
        lngStyle = lngStyle ^ WS_SIZEBOX;

        SetWindowLong(excelHandle, GWL_STYLE, lngStyle); // apply the new style
        SetWindowPos(excelHandle, new IntPtr(0), 0, 0, this.Width, this.Height, SWP_FRAMECHANGED);

        int pid = 0;
        GetWindowThreadProcessId(excelHandle, out pid);
        process = Process.GetProcessById(pid);

        initialized = true; // do not initalize a second tieme
    }

    public void OpenFile(string fileName, bool isExclusive = true, bool isReadonly = true)
    {
        if (!initialized)
            Init();
        if (isExclusive && application.ActiveWorkbook != null) // close existing apps
            application.ActiveWorkbook.Close(false);            // close without saving
        workbooks = application.Workbooks;
        workbook = workbooks.Open(fileName, isReadonly);       // Open mode - readonly

    }

    public void CloseExcel()
    {
        InternalCloseExcel();
    }
    private void InternalCloseExcel()
    {
        try
        {
            if (workbook != null)
            {
                workbook.Close(false);
                Marshal.ReleaseComObject(workbooks);   // take care of the ref counting? 
                Marshal.ReleaseComObject(workbook);
                if (application != null)
                {
                    application.Quit();
                    Marshal.ReleaseComObject(application);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            workbooks = null;
            workbook = null;
            application = null;
            if (process != null && !process.HasExited)
            {
                process.Kill();
            }
            Thread.CurrentThread.CurrentCulture = threadCulture;
            initialized = false;
        }
    }

    public void KillExcel()
    {
        if (process != null && !process.HasExited)
        {
            process.Kill();
        }
    }

    public void SaveActiveWorkbook()
    {
        workbook.Save();
    }

    public void SaveActiveBookAs(string filename)
    {
        Debug.Assert(!string.IsNullOrEmpty(filename));
        workbook.SaveAs(filename);
    }

    public void SaveCopyOfActiveBookAs(string filename)
    {
        Debug.Assert(!string.IsNullOrEmpty(filename));
        workbook.SaveCopyAs(filename);
    }


    #region Internal Handlers
    // once the host is resized, the content should shall resize according to the new host
    private void ExcelViewer_Resize(object sender, EventArgs args)
    {
        if (excelHandle != IntPtr.Zero)
        {
            SetWindowPos(excelHandle, new IntPtr(0), 0, 0, this.Width, this.Height, SWP_NOACTIVATE);
        }
    }


    #endregion Internal Handlers


    #endregion Proxy Method

    #region Override
    protected override void OnHandleDestroyed(EventArgs e)
    {
        CloseExcel();
        base.OnHandleDestroyed(e);
    }
    #endregion Override

    #region P/Invoke

    private const int SWP_FRAMECHANGED = 0x0020;
    private const int SWP_DRAWFRAME = 0x20;
    private const int SWP_NOMOVE = 0x2;
    private const int SWP_NOSIZE = 0x1;
    private const int SWP_NOZORDER = 0x4;
    private const int GWL_STYLE = (-16);
    private const int WS_CAPTION = 0xC00000;
    private const int WS_THICKFRAME = 0x40000;
    private const int WS_SIZEBOX = WS_THICKFRAME;
    private const int SWP_NOACTIVATE = 0x0010;

    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    [DllImport("user32.dll")]
    public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

    [DllImport("User32", SetLastError = true)]
    public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

    #endregion P/Invoke

}

它是这样嵌入的:

    <WindowsFormsHost Grid.Row="0" IsManipulationEnabled="True">
        <excel:ExcelView x:Name="excel"/>
    </WindowsFormsHost>

编辑:我试图删除集成到我的WPF中,只是在每个互操作的单独窗口中启动excel(注释了this.Resize行和excelHandle =行之后的Init方法),然后加载了文档-在单独的窗口中轻松地交互并在工作表中执行我想要的操作。...还不够漂亮!看起来excel工作表没有收到任何鼠标或键盘事件,或者只是

0 个答案:

没有答案