WinForm中使用Excel控件



最近项目中要在WinForm中使用Excel控件,经过几天的研究,现在总结一下成果。

在WinForm中使用Excel控件主要有三种方法:WebBrowser、DSOFramer、OWC。下面分别描述一下如何使用。

一、WebBrowser

    /// -1、如何使用 WebBrowser 控件在 Visual C# 2005 或 Visual C# .NET 中打开 Office 文档
    ///     参见:http://support.microsoft.com/kb/304662/
    /// 0、尝试在 Windows Internet Explorer 7 或 Internet Explorer 8 中查看 2007 Microsoft Office 程序文档时会打开一个新的窗口
    ///     参见:http://support.microsoft.com/kb/927009/
    ///     即:运行BrowserFlags.reg注册表脚本。

    /// 1、添加控件:选择COM选项卡中的Microsoft Web Browser
    /// 2、使用控件:axWebBrowser1.Navigate(fileNme)
    /// 3、添加工具条:在axWebBrowser1_NavigateComplete2事件中添加,否则出错。
    ///     this.axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_HIDETOOLBARS, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER);
    /// 4、获取对象:在axWebBrowser1_NavigateComplete2事件中获取。
    ///     eDocument = e.pDisp.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, e.pDisp, null);
    ///     eApplication = (Excel.Application)eDocument.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, eDocument, null);
    ///     eWorkbook = eApplication.ActiveWorkbook;
    /// 5、保存文件:eWorkbook.Save();
    /// 6、释放文件:释放COM对象引用

    ///     Marshal.ReleaseComObject(eWorkbook);
    ///     Marshal.ReleaseComObject(eApplication);
    ///     Marshal.ReleaseComObject(eDocument);

后来发现,可以使用.NET的webBrowser控件,而不用添加COM选项卡中的Microsoft Web Browser。

只是获取eApplication 对象方式不同,有两种方法获取Application对象。

第一种其实和axWebBrowser一样

代码
private void LoadByActiveXInstance()
{
SHDocVw.WebBrowser wb
= (SHDocVw.WebBrowser)this.webBrowser1.ActiveXInstance;
eDocument
= wb.Document;
eApplication
= (Excel.Application)eDocument.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, eDocument, null);

//添加工具条
eWorkbook = eApplication.ActiveWorkbook; wb.ExecWB(SHDocVw.OLECMDID.OLECMDID_HIDETOOLBARS, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER);
}

第二种是使用COM方法获取,代码比较复杂

代码

private Office.CommandBar m_StandardCommandBar = null;
/// <summary>
/// 获取Application方式二
/// 添加工具条方式二
/// </summary>
private void LoadByAPI()
{
// Creation of the workbook object
if ((eWorkbook = RetrieveWorkbook(FileName)) == null) return;

// Create the Excel.Application
eApplication = eWorkbook.Application;
// Creation of the standard toolbar
m_StandardCommandBar = eApplication.CommandBars["Standard"];
m_StandardCommandBar.Position
= Office.MsoBarPosition.msoBarTop;
m_StandardCommandBar.Visible
= true;
//foreach (Office.CommandBar bar in eApplication.CommandBars)

// Enable the OpenFile and New buttons
foreach (Office.CommandBarControl control in m_StandardCommandBar.Controls)
{
string name = control.get_accName(Missing.Value);
if (name.Equals("Open")) ((Office.CommandBarButton)control).Enabled = false;
if (name.Equals("Save")) ((Office.CommandBarButton)control).Enabled = false;
}
}

///此方法为COM提供的方法。可google:COM原理及应用 命名和绑定技术
///另所有 OLE api 和接口的目的,参见:http://support.microsoft.com/kb/126157/zh-cn
[DllImport("ole32.dll")]
static extern int GetRunningObjectTable(uint reserved, out IRunningObjectTable pprot);
[DllImport(
"ole32.dll")]
static extern int CreateBindCtx(uint reserved, out IBindCtx pctx);

public Excel.Workbook RetrieveWorkbook(string xlfile)
{
IRunningObjectTable prot
= null;
IEnumMoniker pmonkenum
= null;
try
{
IntPtr pfetched
= IntPtr.Zero;
// Query the running object table (ROT)
if (GetRunningObjectTable(0, out prot) != 0 || prot == null) return null;
prot.EnumRunning(
out pmonkenum);
pmonkenum.Reset();
IMoniker[] monikers
= new IMoniker[1];
while (pmonkenum.Next(1, monikers, pfetched) == 0)
{
IBindCtx pctx;
string filepathname;
CreateBindCtx(
0, out pctx);
// Get the name of the file
monikers[0].GetDisplayName(pctx, null, out filepathname);
// Clean up
Marshal.ReleaseComObject(pctx);
// Search for the workbook
// filepathname = @"file:///D:/fly/Book1.xls"
// xlfile = @"D:\fly\Book1.xls"
if (filepathname.IndexOf(xlfile) != -1)
{
object roval;
// Get a handle on the workbook
prot.GetObject(monikers[0], out roval);
return roval as Excel.Workbook;
}
}
}
finally
{
// Clean up
if (prot != null) Marshal.ReleaseComObject(prot);
if (pmonkenum != null) Marshal.ReleaseComObject(pmonkenum);
}
return null;
}

另外,可以不引用COM对象,直接使用GetType().InvokeMember执行Excel操作。

二、DSOFramer

这种方法比较简单,感觉是对WebBrowser的封装。

    /// 需要下载DSOFramer.ocx控件。并regsvr32注册控件。
    /// 然后添加到工具箱ToolBox中使用。

三、OWC

需要下载并安装OWC11,添加Spreadsheet到工具箱中即可使用。

OWC方式只能打开xml、csv、htm格式的Excel文件!!无法打开xls文件。

附示例代码(VS2010的):https://files.cnblogs.com/xujiaoxiang/Fly_Excel_WinForm.zip

 

原文地址:https://www.cnblogs.com/xujiaoxiang/p/1797666.html