VSTO Excel 和 Word 加载项 C#






4.96/5 (18投票s)
引言
本文的主要目的是解释如何使用 Visual Studio Tools for Office (VSTO) 创建简单的 Excel 和 MS Word 插件。VSTO 作为 Microsoft Visual Studio 的一个插件工具提供。使用 Visual Studio,我们可以为 Excel、Word 等 Office 工具开发自己的自定义控件。
在我的演示程序中,我使用了 Visual Studio 2010 和 Office 2007。
在本文中,我将解释创建我们自己的自定义 Excel 和 Word 插件的几个基本知识,如下所示。
- Excel 插件。
- 向任何 Excel 选定的活动 Excel 单元格添加文本。
- 从我们的自定义控件向 Excel 添加图像。
- 从数据库加载数据并在 Excel 中显示搜索结果数据。
- Word 插件
- 将 Word 导出为 PDF。
- 向 Word 文档添加图像。
- 向 Word 文档添加表格。
使用代码
1) 创建 Excel 插件
在我的示例中,我使用了 Visual Studio 2010 和 Office 2007。
要为 Excel 创建我们自己的自定义控件插件
步骤 1: 创建新项目并选择 Office 2007 Excel AddIn,如下图所示。选择您的项目文件夹并输入您的项目名称。
步骤 2: 现在我们可以在项目文件夹中看到创建的 Excel ThisAddIn.Cs 文件,并在该类中找到两个默认方法,如下图所示。“ThisAddIn_Startup” 在此事件中,我们可以将我们自己的自定义控件插件显示到 Excel 中,详细信息请参见代码部分。
步骤 3:向项目添加新的 UserControl 以创建我们自己的自定义 Excel 控件插件。
右键单击您的项目 -> 点击添加新项 -> 添加 UserControl 并按您喜欢的名称命名控件。根据您的需求添加所有控件并设计您的 UserControl。
在我的示例中,我在 User Controls 中执行 3 种操作。
1) 添加文本:在此按钮单击事件中,我将从文本框中的文本插入到活动的选定 Excel 单元格中。使用“Globals.ThisAddIn.Application.ActiveCell”我们可以获取当前活动的 Excel 单元格。我们将结果存储在 Excel 范围中,现在使用范围、值、颜色,我们可以为活动的 Excel 单元格设置我们自己的文本和颜色。
private void btnAddText_Click(object sender, EventArgs e)
{
Excel.Range objRange = Globals.ThisAddIn.Application.ActiveCell;
objRange.Interior.Color = Color.Pink; //Active Cell back Color
objRange.Borders.Color = Color.Red;// Active Cell border Color
objRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
objRange.Value = txtActiveCellText.Text; //Active Cell Text Add
objRange.Columns.AutoFit();
}
2) 添加图像:通过打开文件对话框,我们可以选择需要添加到 Excel 文件中的图像。使用 Excel.Shape,我们可以将选定的图像添加到 Excel 文件。
private void btnAddImage_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.FileName = "*";
dlg.DefaultExt = "bmp";
dlg.ValidateNames = true;
dlg.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Bitmap dImg = new Bitmap(dlg.FileName);
Excel.Shape IamgeAdd = Globals.ThisAddIn.Application.ActiveSheet.Shapes.AddPicture(dlg.FileName,
Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoCTrue,
20, 30, dImg.Width, dImg.Height);
}
System.Windows.Forms.Clipboard.Clear();
}
3) 搜索并绑定数据库数据到 Excel:现在我们可以创建自己的自定义搜索控件,用于在 Excel 中从数据库搜索我们的数据,并将结果绑定到 Excel 文件。
创建表格。
-- Create Table ItemMaster in your SQL Server - This table will be used for search and bind result to excel.
CREATE TABLE [dbo].[ItemMasters](
[Item_Code] [varchar](20) NOT NULL,
[Item_Name] [varchar](100) NOT NULL)
-- insert sample data to Item Master table
INSERT INTO [ItemMasters] ([Item_Code],[Item_Name])
VALUES ('Item001','Coke')
INSERT INTO [ItemMasters] ([Item_Code],[Item_Name])
VALUES ('Item002','Coffee')
INSERT INTO [ItemMasters] ([Item_Code],[Item_Name])
VALUES ('Item003','Chiken Burger')
INSERT INTO [ItemMasters] ([Item_Code],[Item_Name])
VALUES ('Item004','Potato Fry')
在按钮搜索单击事件中,我们从数据库搜索数据,并使用 “Globals.ThisAddIn.Application.ActiveSheet.Cells”
将结果绑定到 Excel 单元格,这将把结果添加到活动的 Excel 工作表中。
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
System.Data.DataTable dt = new System.Data.DataTable();
String ConnectionString = "Data Source=YOURDATASOURCE;Initial Catalog=YOURDATABASENAME;User id = UID;password=password";
SqlConnection con = new SqlConnection(ConnectionString);
String Query = " Select Item_Code,Item_Name FROM ItemMasters Where Item_Name LIKE '" + txtItemName.Text.Trim() + "%'";
SqlCommand cmd = new SqlCommand(Query, con);
cmd.CommandType = System.Data.CommandType.Text;
System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.Rows.Count <= 0)
{
return;
}
Globals.ThisAddIn.Application.ActiveSheet.Cells.ClearContents();
Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 1].Value2 = "Item Code";
Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 2].Value2 = "Item Name";
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 1].Value2 = dt.Rows[i][0].ToString();
Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 2].Value2 = dt.Rows[i][1].ToString();
}
}
catch (Exception ex)
{
}
}
步骤 4:现在我们已经创建了自己的 UserControl 以添加到我们的 Excel 插件中。要将此 UserControl 添加到我们的 Excel 插件中,正如我们已经看到的,Excel Addin 类“ThisAddIn.Cs
” 具有启动和停止事件。使用 Office“CustomTaskpane
”,我们可以将我们的 UserControl 作为插件添加到 Excel 中,如下所示。
private Microsoft.Office.Tools.CustomTaskPane customPane;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
ShowShanuControl();
}
public void ShowShanuControl()
{
var txtObject = new ShanuExcelADDIn();
customPane = this.CustomTaskPanes.Add(txtObject, "Enter Text");
customPane.Width = txtObject.Width;
customPane.Visible = true;
}
步骤 5:运行您的程序,现在我们可以看到我们自己的 UserControl 已作为插件添加到 Excel 文件中。
接下来,我们将看到如何使用 Ribbon Control 为 Word 文档创建插件。
2) 创建 Word 插件
在我的示例中,我使用了 Visual Studio 2010 和 Office 2007。
要为 Word 创建我们自己的自定义控件插件
步骤 1:创建新项目并选择 Office 2007 Word AddIn,如下图所示。选择您的项目文件夹并输入您的项目名称。
步骤 2:向项目添加新的 Ribbon Control 以创建您自己的 Word 控件插件。
右键单击您的 项目 -> 点击添加新项 -> 添加 Ribbon Control
并按您喜欢的名称命名控件。
根据您的需求添加所有控件并设计您的 UserControl。默认情况下,我们的 Ribbon Control 中有一个“RibbonGroup
”。我们可以将所有控件添加到 Ribbon Group 中。在我的示例中,我已经将 Group Label Text 更改为“SHANU Add-In”。我已将三个 Ribbon Button Controls 添加到 Group 中。我们可以向 Ribbon Button Controls 添加图像,并设置 Button Control 的大小属性为“RibbobControlSizeLarge
”。
在这里,我添加了三个按钮控件,用于导出 Word 为 PDF、向 Word 添加图像以及向 Word 文件添加表格。
步骤 3:导出为 PDF 文件按钮单击。
使用“Globals.ThisAddIn.Application.ActiveDocument.ExportAsFixedFormat
”,我们可以将 Word 文档保存为 PDF 文件。我使用了 Save file dialog 将 PDF 文件保存在我们选择的路径中。
private void btnPDF_Click(object sender, RibbonControlEventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "*";
dlg.DefaultExt = "pdf";
dlg.ValidateNames = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Globals.ThisAddIn.Application.ActiveDocument.ExportAsFixedFormat(dlg.FileName, word.WdExportFormat.wdExportFormatPDF, OpenAfterExport: true);
}
}
步骤 4:向 Word 添加图像
通过打开文件对话框,我们可以选择需要添加到 Word 文件中的图像。使用“Globals.ThisAddIn.Application.ActiveDocument.Shapes.AddPicture
”方法,我们可以将选定的图像添加到 Word 文件。
private void btnImage_Click(object sender, RibbonControlEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.FileName = "*";
dlg.DefaultExt = "bmp";
dlg.ValidateNames = true;
dlg.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Globals.ThisAddIn.Application.ActiveDocument.Shapes.AddPicture(dlg.FileName);
}
}
步骤 5:向 Word 添加表格
使用“Globals.ThisAddIn.Application.ActiveDocument.Tables
”方法,我们可以向 Word 文件添加表格。在我的示例中,我创建了一个 4 列 3 行的表格。
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(Globals.ThisAddIn.Application.ActiveDocument.Range(0, 0), 3, 4);
Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorSeaGreen;
Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Range.Font.Size = 12;
Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Rows.Borders.Enable = 1;
}
步骤 6:运行您的程序,现在我们可以看到我们自己的 Ribbon Control 已作为插件添加到 Word 文件中。
历史
ShanuWordAddInsV1.0.zip - 2015-06-26