2

我最近想看看是否可以使用 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
    }
}
4

1 回答 1

0

由于您使用的是启动事件,因此每次启动 Excel 时都会启动此代码。在 Excel 本身中禁用加载项将解决您的问题。

于 2012-09-20T08:14:24.830 回答