Description
Creating a Named Range
1) VSTO
[C#]
……. using Microsoft.VisualStudio.Tools.Applications.Runtime; using Excel = Microsoft.Office.Interop.Excel; using Office = Microsoft.Office.Core; using System.Reflection; ……. //Create Excel Object Excel.ApplicationClass xl = new Excel.ApplicationClass(); //Create a new Workbook Excel.Workbook wb = xl.Workbooks.Add(Missing.Value); //Get Worksheets Collection Excel.Sheets xlsheets = wb.Sheets; //Select the first sheet Excel.Worksheet excelWorksheet = (Excel.Worksheet)xlsheets[1]; //Select a range of cells Excel.Range range = (Excel.Range)excelWorksheet.get_Range("A1:B4", Type.Missing); //Add Name to Range range.Name = "Test_Range"; //Put data in range cells foreach (Excel.Range cell in range.Cells) { cell.set_Value(Missing.Value, "Test"); } //Save New Workbook wb.SaveCopyAs("C:\\Test_Range.xls") //Quit Excel Object xl.Quit();
[VB]
……. Imports Microsoft.VisualStudio.Tools.Applications.Runtime Imports Excel = Microsoft.Office.Interop.Excel Imports Office = Microsoft.Office.Core Imports System.Reflection ……. 'Create Excel Object Dim xl As New Excel.ApplicationClass() 'Create a new Workbook Dim wb As Excel.Workbook = xl.Workbooks.Add(Missing.Value) 'Get Worksheets Collection Dim xlsheets As Excel.Sheets = wb.Sheets 'Select the first sheet Dim excelWorksheet As Excel.Worksheet = CType(xlsheets(1), Excel.Worksheet) 'Select a range of cells Dim range As Excel.Range = excelWorksheet.Range("A1", "B4") 'Add Name to Range range.Name = "Test_Range" 'Put data in range cells For Each cell As Microsoft.Office.Interop.Excel.Range In range.Cells cell.Value = "Test" Next cell 'Save New Workbook wb.SaveCopyAs("C:\Test_Range.xls") 'Quit Excel Object xl.Quit()
2) Aspose.Cells for .NET
[C#]
……. using Aspose.Cells; ……. //Instantiating a Workbook object Workbook workbook = new Workbook(); //Accessing the first worksheet in the Excel file Worksheet worksheet = workbook.Worksheets[0]; //Creating a named range Range range = worksheet.Cells.CreateRange("A1", "B4"); //Setting the name of the named range range.Name = "Test_Range"; for (int row = 0; row < range.RowCount; row++) { for (int column = 0; column < range.ColumnCount; column++) { range[row, column].PutValue("Test"); } } //Saving the modified Excel file in default (that is Excel 2003) format workbook.Save("C:\\Test_Range.xls");
[VB]
……. Imports Aspose.Cells ……. 'Instantiating a Workbook object Dim workbook As New Workbook() 'Accessing the first worksheet in the Excel file Dim worksheet As Worksheet = workbook.Worksheets(0) 'Creating a named range Dim range As Range = worksheet.Cells.CreateRange("A1", "B4") 'Setting the name of the named range range.Name = "Test_Range" For row As Integer = 0 To range.RowCount - 1 For column As Integer = 0 To range.ColumnCount - 1 range(row, column).PutValue("Test") Next column Next row 'Saving the modified Excel file in default (that is Excel 2003) format workbook.Save("C:\Test_Range.xls")
