Excel 二次开发系列(6): 引用Excel模板

Excel 二次开发系列 C#

这一节,主要有两个方面:

第一个是直接对Excel模板进行二次开发,第二个是对已经存在模板进行开发和引用。

·         可以直接对Excel 模板进行二次开发,开发工程的引用和 创建Excel二次开发环境 一样。但是去掉了一些step 在每个sheet中都有两个事件,一个是在sheet运行开始之前就执行,还一个是在运行之后就执行。在一个Excel Template Workbook 中还可以添加sheet

    private void Sheet1_Startup(object sender, System.EventArgs e)

{

 

    }

    private void Sheet1_Shutdown(object sender, System.EventArgs e)

{

          

}

    #region VSTO Designer generated code

 

        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

              private void InternalStartup()

        {

            this.Startup += new System.EventHandler(Sheet1_Startup);

            this.Shutdown += new System.EventHandler(Sheet1_Shutdown);

        }

       

     #endregion

要调用此sheet中的任何信息。此时要用到Globals.Sheet1.xxxx

在插件开发中经常会用到Globals 这个对象。所以对很多的操作,要查找其方法,首先从全局对象Globals入手。

例如在这里写个方法: 向模板sheet1 随即添加数据

        public void LoadData()

        {

            Random ran = new Random();

            for (int i = 1; i <= 12; i++)

            {

                Globals.Sheet1.Cells[i, 1] = i.ToString() + "";

                Globals.Sheet1.Cells[i, 2] = ran.Next(2000).ToString();

              

            }

      }

 把这个方法在 Sheet1_Startup(object sender, System.EventArgs e) 方法中进行调用,运行之后就可以得到你数据了。

 

·         直接引用现有的模板:

Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();

            Microsoft.Office.Interop.Excel.Workbook book = app.Workbooks.Add(object Template);

这时候就把现有的模板添加到了workbook中。这时候我们可以向里面填充一些数据。

public void SetValueForPrice(Microsoft.Office.Interop.Excel.Application app)

        {

            if (app == null)

            {

                return;

            }

            Worksheet sheet = app.ActiveSheet as Worksheet; //默认的为sheet1

            sheet.Cells.set_Item(6, 2, CurrentTime.ToString("d"));

            sheet.Cells.set_Item(7, 2, "PO#" + ProInf.PoNumber);

            sheet.Cells.set_Item(16, 2, ProInf.ProjectName);

            sheet.Cells.set_Item(21,3,CurrentTime.Year.ToString()+""+CurrentTime.Month.ToString()+"");

            sheet.Cells.set_Item(18,2, Startmonth.ToString()+@"/19/"+CurrentTime.Year.ToString());

            sheet.Cells.set_Item(18, 4, CurrentTime.Month.ToString() + @"/20/" + CurrentTime.Year.ToString());

            sheet.Cells.set_Item(21, 4, ProInf.ActualInvoiceAmount);

            sheet.Cells.set_Item(22, 4, ProInf.ActualInvoiceAmount);         

        }

设置完了以后,我们可以保存:

book.Close(true, file, Missing.Value);

app.Quit();

对于二次开发系列,要多去实践。实践出来才能得到你想要的东西。甚至有意外的收获。

原文地址:https://www.cnblogs.com/tomin/p/Excel_second_develepment_serise6.html