最近項目中要在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一樣


{
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的):http://files.cnblogs.com/xujiaoxiang/Fly_Excel_WinForm.zip
?
?