把Excel嵌入winform中,其实在
思路的博客与MSDN都有相关的介绍,但所有的文章对于怎么获得载入的excel对象都没有说得太清楚,下面是我写的一个简单控件,用.net framework 1.1+office 2003测试通过。
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Win32;
using Microsoft.Office.Interop.Excel;
using ExcelApplication=Microsoft.Office.Interop.Excel.ApplicationClass;
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
namespace ExcelTest
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// ExcelControl 的摘要说明。
/// </summary>
public class ExcelControl : System.Windows.Forms.UserControl
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
私有变量、方法和构造函数#region 私有变量、方法和构造函数
![](/Images/OutliningIndicators/InBlock.gif)
private AxSHDocVw.AxWebBrowser axWebBrowser1;
![](/Images/OutliningIndicators/InBlock.gif)
//奇怪,必须初始化一个ExcelApplication方能正常工作
private ExcelApplication excel=new ExcelApplication();
private object missing=Missing.Value;
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
![](/Images/OutliningIndicators/InBlock.gif)
public ExcelControl()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// 该调用是 Windows.Forms 窗体设计器所必需的。
InitializeComponent();
![](/Images/OutliningIndicators/InBlock.gif)
// TODO: 在 InitializeComponent 调用后添加任何初始化
![](/Images/OutliningIndicators/InBlock.gif)
}
![](/Images/OutliningIndicators/InBlock.gif)
private void axWebBrowser1_NavigateComplete2(object sender, AxSHDocVw.DWebBrowserEvents2_NavigateComplete2Event e)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
object o=e.pDisp;
object oDocument = o.GetType().InvokeMember("Document",BindingFlags.GetProperty,null,o,null);
excel=(ExcelApplication)o.GetType().InvokeMember("Application",BindingFlags.GetProperty,null,oDocument,null);
//MessageBox.Show(excel.ActiveSheet.ToString());
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 释放EXCEL进程
/// </summary>
private void releaseExcel()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
excel.Quit();
excel=null;
axWebBrowser1.Dispose();
GC.Collect();
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 判断一个工作表中是否有内容
/// </summary>
/// <param name="worksheet"></param>
/// <returns></returns>
private bool hasContent(Worksheet worksheet)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Range range=worksheet.get_Range("A1","G15");
object[,] vals=(object[,])range.get_Value(missing);
string content=string.Empty;
foreach(object val in vals)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(val!=null)
content+=val.ToString();
}
if(content.Length>0)
return true;
else
return false;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 加入新工作簿
/// </summary>
/// <param name="fileName"></param>
private void addWorksheet(string fileName)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
ExcelApplication myExcel=new ExcelApplication();
myExcel.Workbooks.Open(fileName,missing,missing,missing,missing,missing,missing,missing,missing,
missing,missing,missing,missing,missing,missing);
int count=myExcel.Worksheets.Count+1;
for(int i=1;i<count;i++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Worksheet sheet=(Worksheet)myExcel.Worksheets.get_Item(i);
if(hasContent(sheet))
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Range range=sheet.get_Range("A1","Z200");
object[,] vals=(object[,])range.get_Value(missing);
string sheetName=(string)sheet.Name;
int sheetNo=sheetCount();
excel.Sheets.Add(missing,excel.Worksheets.get_Item(sheetNo),missing,missing);
Worksheet newSheet=(Worksheet)excel.Worksheets.get_Item(sheetNo+1);
if(hasDupliacteName(sheetName))
sheetName=sheetName+"-1";
newSheet.Name=sheetName;
range=newSheet.get_Range("A1","Z200");
range.Value2=vals;
}
}
myExcel.Quit();
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 检查现有工作簿中是否有重名工作表存在
/// </summary>
/// <param name="sheetName"></param>
/// <returns></returns>
private bool hasDupliacteName(string sheetName)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
int count=excel.Worksheets.Count+1;
for(int i=1;i<count;i++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Worksheet sheet=(Worksheet)excel.Worksheets.get_Item(i);
if(sheet.Name==sheetName)
return true;
}
return false;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 返回现有工作簿中有内容的工作表数量
/// </summary>
/// <returns></returns>
private int sheetCount()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
int count=excel.Worksheets.Count+1;
int retval=0;
for(int i=1;i<count;i++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(hasContent((Worksheet)excel.Worksheets.get_Item(i)))
retval++;
}
return retval;
}
![](/Images/OutliningIndicators/InBlock.gif)
#endregion
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if( disposing )
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(components != null)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
releaseExcel();
components.Dispose();
}
}
base.Dispose( disposing );
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
组件设计器生成的代码#region 组件设计器生成的代码
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器
/// 修改此方法的内容。
/// </summary>
private void InitializeComponent()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ExcelControl));
this.axWebBrowser1 = new AxSHDocVw.AxWebBrowser();
((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).BeginInit();
this.SuspendLayout();
//
// axWebBrowser1
//
this.axWebBrowser1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.axWebBrowser1.Enabled = true;
this.axWebBrowser1.Location = new System.Drawing.Point(0, 0);
this.axWebBrowser1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWebBrowser1.OcxState")));
this.axWebBrowser1.Size = new System.Drawing.Size(400, 300);
this.axWebBrowser1.TabIndex = 0;
this.axWebBrowser1.NavigateComplete2 += new AxSHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(this.axWebBrowser1_NavigateComplete2);
//
// ExcelControl
//
this.Controls.Add(this.axWebBrowser1);
this.Name = "ExcelControl";
this.Size = new System.Drawing.Size(400, 300);
((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).EndInit();
this.ResumeLayout(false);
![](/Images/OutliningIndicators/InBlock.gif)
}
#endregion
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
公有方法#region 公有方法
![](/Images/OutliningIndicators/InBlock.gif)
public void Open(string fileName)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
try
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
axWebBrowser1.Navigate(fileName,ref missing,ref missing,ref missing,ref missing);
//axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_HIDETOOLBARS,SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER,ref missing,ref missing);
}
catch
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
throw new ApplicationException("文件不存在");
}
![](/Images/OutliningIndicators/InBlock.gif)
}
public void Save(string fileName)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Worksheet worksheet=(Worksheet)excel.ActiveSheet;
worksheet.SaveAs(fileName,missing,missing,missing,missing,missing,missing,missing,missing,missing);
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 把已有文件的内容插入到工作表中
/// </summary>
/// <param name="fileName"></param>
public void Insert(string fileName)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
try
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
addWorksheet(fileName);
// Range range=((Worksheet)excel.ActiveSheet).get_Range("A1",missing);
// range.Select();
}
catch(Exception ex)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
MessageBox.Show(ex.ToString());
}
}
#endregion
}
}
![](/Images/OutliningIndicators/None.gif)