// This paragraph puts the value 5 to the cell G1 Range range1 = worksheet.get_Range("A1", Missing.Value); if (range1 == null) { statusBar1.Text = "ERROR: range == null"; return; } const int nCells = 2345; range1.Value2 = nCells;
二、示例程序
在Visual Studio .Net中建立一個C# WinForm工程. 添加Microsoft Excel Object Library引用: 右鍵單擊Project , 選“添加引用” 在COM 標簽項,選中 locate Microsoft Excel Object Library 點確定按鈕完成添加引用。 On the VIEw menu, select Toolbox to display the Toolbox. Add two buttons and a check box to Form1. 在Form1上添加一個button1,雙擊 Button1,添加click事件的代碼.把數組裡的數據填到Excel表格。 首先添加引用:
using System.Reflection; using Excel = Microsoft.Office.Interop.Excel;
try { // Instantiate Excel and start a new workbook. objApp = new Excel.Application(); objBooks = objApp.Workbooks; objBook = objBooks.Add( Missing.Value ); obJSheets = objBook.Worksheets; objSheet = (Excel._Worksheet)obJSheets.get_Item(1);
//Get the range where the starting cell has the address //m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols. range = obJSheet.get_Range("A1", Missing.Value); range = range.get_Resize(5, 5);
if (this.FillWithStrings.Checked == false) { //Create an array. double[,] saRet = new double[5, 5];
//Fill the array. for (long iRow = 0; iRow < 5; iRow++) { for (long iCol = 0; iCol < 5; iCol++) { //Put a counter in the cell. saRet[iRow, iCol] = iRow * iCol; } }
//Set the range value to the array. range.set_Value(Missing.Value, saRet ); }
else { //Create an array. string[,] saRet = new string[5, 5];
//Fill the array. for (long iRow = 0; iRow < 5; iRow++) { for (long iCol = 0; iCol < 5; iCol++) { //Put the row and column address in the cell. saRet[iRow, iCol] = iRow.ToString() + "|" + iCol.ToString(); } }
//Set the range value to the array. range.set_Value(Missing.Value, saRet ); }
try { try { //Get a reference to the first sheet of the workbook. obJSheets = objBook.Worksheets; objSheet = (Excel._Worksheet)obJSheets.get_Item(1); }
catch( Exception theException ) { String errorMessage; errorMessage = "Can't find the Excel workbook. Try clicking Button1 " + "to create an Excel workbook with data before running Button2.";