<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # 如何:通過使用 Visual C# 功能訪問 Office 互操作對象(C# 編程指南) Visual C# 2010 引入了可以簡化對 Office API 對象的訪問的新功能。這些新功能包括命名實參和可選實參、名為 **dynamic** 的新類型,以及在 COM 方法中將實參傳遞為引用形參(就像它們是值形參)的功能。 在本主題中,你將利用這些新功能來編寫創建并顯示 Microsoft Office Excel 工作表的代碼。然后,你將編寫添加包含鏈接到 Excel 工作表的圖標的 Office Word 文檔的代碼。 若要完成本演練,你的計算機上必須安裝 Microsoft Office Excel 2007 和 Microsoft Office Word 2007 或更高版本。 如果你使用的操作系統早于 Windows Vista,請確保安裝 .NET Framework 2.0。 | ![](https://box.kancloud.cn/2016-01-31_56adb62c1380a.jpg) 注意 | | :-- | | 以下說明中的某些 Visual Studio 用戶界面元素在計算機上出現的名稱或位置可能會不同。 這些元素取決于你所使用的 Visual Studio 版本和你所使用的設置。 有關詳細信息,請參閱[個性化 Visual Studio IDE](https://msdn.microsoft.com/zh-CN/library/mt269425.aspx)。 | ## 創建新的控制臺應用程序 1. 啟動 Visual Studio。 2. 在**“文件”**菜單上,指向**“新建”**,然后單擊**“項目”**。 出現 **新建項目** 對話框。 3. 在“已安裝的模板”窗格中,展開“Visual C#”,然后單擊“Windows”。 4. 查看“新建項目”對話框的頂部,確保“.NET Framework 4”(或更高版本)選為目標框架。 5. 在**“模板”**窗格中,單擊**“控制臺應用程序”**。 6. 在“名稱”字段中鍵入項目的名稱。 7. 單擊“確定”。 新項目將出現在“解決方案資源管理器”中。 ## 添加引用 1. 在“解決方案資源管理器”中,右鍵單擊你的項目名稱,然后單擊“添加引用”。將顯示**“添加引用”**對話框。 2. 在“程序集”頁上,在“組件名稱”列表中選擇“Microsoft.Office.Interop.Word”,然后按住 Ctrl 鍵并選擇“Microsoft.Office.Interop.Excel”。如果未看到程序集,你可能需要確保安裝并顯示它們(參閱[如何:安裝 Office 主互操作程序集](https://msdn.microsoft.com/zh-CN/library/kh3965hw.aspx)) 3. 單擊“確定”。 ## 添加必要的 using 指令 1. 在“解決方案資源管理器”中,右鍵單擊“Program.cs”文件,然后單擊“查看代碼”。 2. 將以下 **using** 指令添加到代碼文件的頂部。 ``` using Excel = Microsoft.Office.Interop.Excel; using Word = Microsoft.Office.Interop.Word; ``` ## 創建銀行帳戶列表 1. 將以下類定義粘貼到“Program.cs”中的 Program 類下。 ``` public class Account { public int ID { get; set; } public double Balance { get; set; } } ``` 2. 將以下代碼添加到 Main 方法,以創建包含兩個帳戶的 bankAccounts 列表。 ``` // Create a list of accounts. var bankAccounts = new List&lt;Account&gt; { new Account { ID = 345678, Balance = 541.27 }, new Account { ID = 1230221, Balance = -127.44 } }; ``` ## 聲明將帳戶信息導出到 Excel 的方法 1. 將以下方法添加到 Program 類以設置 Excel 工作表。 方法 [Add](http://go.microsoft.com/fwlink/?LinkId=210910) 有一個可選參數,用于指定特定的模板。如果希望使用形參的默認值,你可以借助可選形參(Visual C# 2010 中新增)忽略該形參的實參。由于以下代碼中未發送任何參數,**Add** 將使用默認模板并創建新的工作簿。C# 早期版本中的等效語句要求占位符參數:ExcelApp.Workbooks.Add(Type.Missing). ``` static void DisplayInExcel(IEnumerable&lt;Account&gt; accounts) { var excelApp = new Excel.Application(); // Make the object visible. excelApp.Visible = true; // Create a new, empty workbook and add it to the collection returned // by property Workbooks. The new workbook becomes the active workbook. // Add has an optional parameter for specifying a praticular template. // Because no argument is sent in this example, Add creates a new workbook. excelApp.Workbooks.Add(); // This example uses a single workSheet. The explicit type casting is // removed in a later procedure. Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet; } ``` 2. 在 DisplayInExcel 的末尾添加以下代碼。代碼將值插入工作表第一行的前兩列。 ``` // Establish column headings in cells A1 and B1. workSheet.Cells[1, "A"] = "ID Number"; workSheet.Cells[1, "B"] = "Current Balance"; ``` 3. 在 DisplayInExcel 的末尾添加以下代碼。 **foreach** 循環將帳戶列表中的信息放入工作表連續行的前兩列。 ``` var row = 1; foreach (var acct in accounts) { row++; workSheet.Cells[row, "A"] = acct.ID; workSheet.Cells[row, "B"] = acct.Balance; } ``` 4. 在 DisplayInExcel 的末尾添加以下代碼以將列寬調整為適合內容。 ``` workSheet.Columns[1].AutoFit(); workSheet.Columns[2].AutoFit(); ``` 早期版本的 C# 要求顯式強制轉換這些操作,因為 ExcelApp.Columns[1] 返回 **Object**,**AutoFit** 為 Excel [Range](http://go.microsoft.com/fwlink/?LinkId=210911) 方法。以下各行顯示強制轉換。 ``` ((Excel.Range)workSheet.Columns[1]).AutoFit(); ((Excel.Range)workSheet.Columns[2]).AutoFit(); ``` 如果程序集由 [/link](https://msdn.microsoft.com/zh-CN/library/dd264728.aspx) 編譯器選項引用或者如果 Excel 的“嵌入互操作類型”屬性設置為 true,則 Visual C# 2010 及更高版本會自動將返回的 **Object** 轉換為 **dynamic**。True 是此屬性的默認值。 ## 運行項目 1. 在 Main 的末尾添加以下行。 ``` // Display the list in an Excel spreadsheet. DisplayInExcel(bankAccounts); ``` 2. 按 Ctrl+F5。 出現包含兩個帳戶數據的 Excel 工作表。 ## 添加 Word 文檔 1. 若要說明 Visual C# 2010 以及更高版本在其他哪些方面增強了 Office 編程,可以使用以下代碼打開 Word 應用程序并創建鏈接到 Excel 工作表的圖標。 將方法 CreateIconInWordDoc(在此步驟后面提供)粘貼到 Program 類中。 CreateIconInWordDoc 利用命名參數和可選參數來降低對 [Add](http://go.microsoft.com/fwlink/?LinkId=210937) 和 [PasteSpecial](http://go.microsoft.com/fwlink/?LinkId=147099) 的方法調用的復雜度。這些調用合并了其他兩項新功能,這兩項新功能在簡化對具有引用參數的 COM 方法的調用的 Visual C# 2010 中引入。首先,你可以將實參發送到引用形參,就像它們是值形參一樣。即,你可以直接發送值,而無需為每個引用參數創建變量。編譯器會生成臨時變量以保存參數值,并將在你從調用返回時丟棄變量。其次,你可以忽略參數列表中的 **ref** 關鍵字。 **Add** 方法有四個引用參數,所有引用參數都是可選的。在 Visual C# 2010 或更高版本中,如果希望使用其默認值,可以忽略任何或所有形參的實參。在 Visual C# 2008 以及更早版本中,由于形參是引用形參,因此必須為每個形參提供實參且實參必須是變量。 **PasteSpecial** 方法可插入剪貼板的內容。該方法有七個引用參數,所有引用參數都是可選的。以下代碼為其中兩個形參指定實參:Link 用于創建指向剪貼板內容源的連接,DisplayAsIcon 用于將鏈接顯示為圖標。在 Visual C# 2010 中,你可以對其中兩個形參使用命名實參而忽略其他形參。盡管這些是引用形參,你也不必使用 **ref** 關鍵字,或者創建變量以實參形式發送。你可以直接發送值。在 Visual C# 2008 以及早期版本中,你必須為每個引用形參發送變量實參。 ``` static void CreateIconInWordDoc() { var wordApp = new Word.Application(); wordApp.Visible = true; // The Add method has four reference parameters, all of which are // optional. Visual C# 2010 allows you to omit arguments for them if // the default values are what you want. wordApp.Documents.Add(); // PasteSpecial has seven reference parameters, all of which are // optional. This example uses named arguments to specify values // for two of the parameters. Although these are reference // parameters, you do not need to use the ref keyword, or to create // variables to send in as arguments. You can send the values directly. wordApp.Selection.PasteSpecial( Link: true, DisplayAsIcon: true); } ``` 在 Visual C# 2008 或早期版本的語言中,需要以下更復雜的代碼。 ``` static void CreateIconInWordDoc2008() { var wordApp = new Word.Application(); wordApp.Visible = true; // The Add method has four parameters, all of which are optional. // In Visual C# 2008 and earlier versions, an argument has to be sent // for every parameter. Because the parameters are reference // parameters of type object, you have to create an object variable // for the arguments that represents 'no value'. object useDefaultValue = Type.Missing; wordApp.Documents.Add(ref useDefaultValue, ref useDefaultValue, ref useDefaultValue, ref useDefaultValue); // PasteSpecial has seven reference parameters, all of which are // optional. In this example, only two of the parameters require // specified values, but in Visual C# 2008 an argument must be sent // for each parameter. Because the parameters are reference parameters, // you have to contruct variables for the arguments. object link = true; object displayAsIcon = true; wordApp.Selection.PasteSpecial( ref useDefaultValue, ref link, ref useDefaultValue, ref displayAsIcon, ref useDefaultValue, ref useDefaultValue, ref useDefaultValue); } ``` 2. 在 Main 的末尾添加以下語句。 ``` // Create a Word document that contains an icon that links to // the spreadsheet. CreateIconInWordDoc(); ``` 3. 在 DisplayInExcel 的末尾添加以下語句。 **Copy** 方法可將工作表添加到剪貼板。 ``` // Put the spreadsheet contents on the clipboard. The Copy method has one // optional parameter for specifying a destination. Because no argument // is sent, the destination is the Clipboard. workSheet.Range["A1:B3"].Copy(); ``` 4. 按 Ctrl+F5。 將出現包含圖標的 Word 文檔。雙擊該圖標以將工作表置于前臺。 ## 設置嵌入互操作類型屬性 1. 當調用運行時不需要主互操作程序集 (PIA) 的 COM 類型時,可能實現其他增強。刪除 PIA 的依賴項可實現版本獨立性并且更易于部署。有關不使用 PIA 編程的優勢的詳細信息,請參閱[演練:嵌入托管程序集中的類型(C# 和 Visual Basic)](https://msdn.microsoft.com/zh-CN/library/dd409610.aspx)。 此外,由于可以通過使用類型 **dynamic**(而非 **Object**)表示 COM 方法必需并返回的類型,因此更易于編程。具有類型 **dynamic** 的變量在運行時以前均不會計算,從而消除了顯式強制轉換的需要。有關詳細信息,請參閱[使用類型 dynamic(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/dd264736.aspx)。 在 Visual C# 2010 中,默認行為是嵌入類型信息,而不是使用 PIA。由于該默認行為,因此不需要顯式強制轉換,之前的幾個示例也得到簡化。例如,DisplayInExcel 中 worksheet 的聲明會寫為 Excel._Worksheet workSheet = excelApp.ActiveSheet 而非 Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet。在相同方法中對 **AutoFit** 的調用還將要求在不進行默認行為的情況下顯式強制轉換,因為 ExcelApp.Columns[1] 返回 **Object**,并且 **AutoFit** 為 Excel 方法。以下代碼顯示強制轉換。 ``` ((Excel.Range)workSheet.Columns[1]).AutoFit(); ((Excel.Range)workSheet.Columns[2]).AutoFit(); ``` 2. 若要更改默認行為并使用 PIA 代替嵌入類型信息,請展開“解決方案資源管理器”中的“引用”節點,然后選擇“Microsoft.Office.Interop.Excel”或“Microsoft.Office.Interop.Word”。 3. 如果看不到“屬性”窗口,請按“F4”。 4. 在屬性列表中找到“嵌入互操作類型”,將其值更改為“False”。同樣地,你還可以通過在命令提示符下使用 [/reference](https://msdn.microsoft.com/zh-CN/library/yabyz3h4.aspx) 編譯器選項代替 [/link](https://msdn.microsoft.com/zh-CN/library/dd264728.aspx) 進行編譯。 ## 將其他格式添加到表格 1. 將在 DisplayInExcel 中對 **AutoFit** 的兩個調用替換為以下語句。 ``` // Call to AutoFormat in Visual C# 2010. workSheet.Range["A1", "B3"].AutoFormat( Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2); ``` [AutoFormat](http://go.microsoft.com/fwlink/?LinkId=210948) 方法有七個值參數,每個值參數都是可選的。使用命名參數和可選參數,你可以為這些參數中的所有或部分提供參數,也可以不為它們中的任何一個提供。在上一條語句中,僅為其中一個形參 Format 提供實參。由于 Format 是參數列表中的第一個參數,因此無需提供參數名稱。但是,如果包含參數名稱,語句則可能更易于理解,如以下代碼所示。 ``` // Call to AutoFormat in Visual C# 2010. workSheet.Range["A1", "B3"].AutoFormat(Format: Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2); ``` 2. 按 Ctrl+F5 查看結果。其他格式在 [XlRangeAutoFormat](http://go.microsoft.com/fwlink/?LinkId=210967) 枚舉中列出。 3. 將步驟 1 中的語句與以下代碼比較(以下代碼顯示 Visual C# 2008 或早期版本中要求的參數)。 ``` // The AutoFormat method has seven optional value parameters. The // following call specifies a value for the first parameter, and uses // the default values for the other six. // Call to AutoFormat in Visual C# 2008\. This code is not part of the // current solution. excelApp.get_Range("A1", "B4").AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatTable3, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); ``` 以下代碼顯示完整示例。 ``` using System; using System.Collections.Generic; using System.Linq; using Excel = Microsoft.Office.Interop.Excel; using Word = Microsoft.Office.Interop.Word; namespace OfficeProgramminWalkthruComplete { class Walkthrough { static void Main(string[] args) { // Create a list of accounts. var bankAccounts = new List<Account> { new Account { ID = 345678, Balance = 541.27 }, new Account { ID = 1230221, Balance = -127.44 } }; // Display the list in an Excel spreadsheet. DisplayInExcel(bankAccounts); // Create a Word document that contains an icon that links to // the spreadsheet. CreateIconInWordDoc(); } static void DisplayInExcel(IEnumerable<Account> accounts) { var excelApp = new Excel.Application(); // Make the object visible. excelApp.Visible = true; // Create a new, empty workbook and add it to the collection returned // by property Workbooks. The new workbook becomes the active workbook. // Add has an optional parameter for specifying a praticular template. // Because no argument is sent in this example, Add creates a new workbook. excelApp.Workbooks.Add(); // This example uses a single workSheet. Excel._Worksheet workSheet = excelApp.ActiveSheet; // Earlier versions of C# require explicit casting. //Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet; // Establish column headings in cells A1 and B1. workSheet.Cells[1, "A"] = "ID Number"; workSheet.Cells[1, "B"] = "Current Balance"; var row = 1; foreach (var acct in accounts) { row++; workSheet.Cells[row, "A"] = acct.ID; workSheet.Cells[row, "B"] = acct.Balance; } workSheet.Columns[1].AutoFit(); workSheet.Columns[2].AutoFit(); // Call to AutoFormat in Visual C# 2010\. This statement replaces the // two calls to AutoFit. workSheet.Range["A1", "B3"].AutoFormat( Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2); // Put the spreadsheet contents on the clipboard. The Copy method has one // optional parameter for specifying a destination. Because no argument // is sent, the destination is the Clipboard. workSheet.Range["A1:B3"].Copy(); } static void CreateIconInWordDoc() { var wordApp = new Word.Application(); wordApp.Visible = true; // The Add method has four reference parameters, all of which are // optional. Visual C# 2010 allows you to omit arguments for them if // the default values are what you want. wordApp.Documents.Add(); // PasteSpecial has seven reference parameters, all of which are // optional. This example uses named arguments to specify values // for two of the parameters. Although these are reference // parameters, you do not need to use the ref keyword, or to create // variables to send in as arguments. You can send the values directly. wordApp.Selection.PasteSpecial(Link: true, DisplayAsIcon: true); } } public class Account { public int ID { get; set; } public double Balance { get; set; } } } ``` ## 請參閱 [Type.Missing](https://msdn.microsoft.com/zh-CN/library/system.type.missing.aspx) [dynamic(C# 參考)](https://msdn.microsoft.com/zh-CN/library/dd264741.aspx) [使用類型 dynamic(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/dd264736.aspx) [命名實參和可選實參(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/dd264739.aspx) [如何:在 Office 編程中使用命名參數和可選參數(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/dd264738.aspx)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看