2012-09-20 93 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中禁用加載項本身將解決您的問題。

相關問題