打开excel时,将打开通过代码创建的Excel电子表格

时间:2012-09-20 07:41:08

标签: c# excel-2007

我最近想知道是否可以使用c#为我的工作中的任务创建一个excel电子表格。我写了一个快速程序(参见下面的代码)来学习基础知识,现在每次打开Excel时,都会显示由我的代码生成的电子表格。我该如何阻止这种情况发生?

namespace ExcelAddIn1
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            var bankAccounts = new List<Account>
            {
             new Account
             {
                ID = 1, 
                Balance = 50.00, 
                Payee = "Debit", 
                PayDate = DateTime.Today
             }
            };

            DisplayInExcel(bankAccounts, (account, cell) =>
                //This multiline lamda expression sets 
                //custom processing rules for bankAccounts.
                {
                    cell.Value = account.ID;
                    cell.Offset[0, 1].Value = account.Balance;
                    cell.Offset[0, 2].Value = account.Payee;
                    cell.Offset[0, 3].Value = account.PayDate;
                    if (account.Balance < 0)
                    {
                        cell.Interior.Color = 255;
                        cell.Offset[0, 1].Interior.Color = 255;
                    }
                });
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        void DisplayInExcel(
            IEnumerable<Account> accounts, 
            Action<Account, 
            Excel.Range> DisplayFunc)
        {
            var excelApp = this.Application;
            // Add a new Excel workbook.
            excelApp.Visible = true;
            excelApp.Workbooks.Add();

            #region cellValues
            excelApp.Range["A1"].Value = "ID";
            excelApp.Range["B1"].Value = "Balance";
            excelApp.Range["C1"].Value = "Payee";
            excelApp.Range["D1"].Value = "Date";
            excelApp.Range["A2"].Select();

            foreach (var ac in accounts)
            {
                DisplayFunc(ac, excelApp.ActiveCell);
                excelApp.ActiveCell.Offset[1, 0].Select();

            }
            #endregion

            // Copy the results to Clipboard.
            excelApp.Range["A1:D2"].Copy();

            excelApp.Columns[1].AutoFit();
            excelApp.Columns[2].AutoFit();
            excelApp.Columns[3].AutoFit();
            excelApp.Columns[4].AutoFit();
        }

        #region VSTO 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(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}

1 个答案:

答案 0 :(得分:0)

由于您正在使用Startup-event,因此每次启动Excel时都会启动此代码。 禁用Excel中的加载项将解决您的问题。