2012-09-20 161 views
2

我最近想查看是否可以使用c#为我的工作中的任务创建Excel电子表格。我写了一个快速程序(见下面的代码)来学习基础知识,现在每次打开Excel时,都会显示由我的代码生成的电子表格。我如何阻止这种情况发生?通过代码创建的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 
    } 
} 
+0

野生猜测在这里(从来没有创建一个AddIn),但它可能是因为你使用启动事件。我的猜测是在Excel中禁用加载项。但我可能会吠叫错误的课程树。 – Koen

+0

感谢Koen已经完成的技巧 – Teague

+0

欢迎您。有时候猜测足够好;-) – Koen

回答

0

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

相关问题