Create Workbook (Global) and Worksheet Scoped Named Ranges
Microsoft Excel allows users to define named ranges with two different scopes: workbook (also known as global scope) and worksheet.
- Named ranges with a workbook scope can be accessed from any worksheet within that workbook by simply using its name.
- Worksheet scoped named ranges are accessed with the reference of the particular worksheet in which it was created.
Aspose.Cells provides the same functionality as Microsoft Excel for adding workbook and worksheet scoped named ranges. When creating a worksheet scoped named range, the worksheet reference should be used in the named range to specify it as a worksheet scoped named range.
The following code samples show how to create workbook and worksheet scoped name ranges by using the Range class.
Adding a Named Range with Workbook Scope
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(AddNamedRangeWithWorkbookScope.class); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Get Worksheets collection | |
WorksheetCollection worksheets = workbook.getWorksheets(); | |
// Accessing the first worksheet in the Excel file | |
Worksheet sheet = worksheets.get(0); | |
// Get worksheet Cells collection | |
Cells cells = sheet.getCells(); | |
// Creating a workbook scope named range | |
Range namedRange = cells.createRange("A1", "C10"); | |
namedRange.setName("workbookScope"); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "output.xls"); |
Adding a Named Range with Worksheet Scope
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(AddNamedRangeWithWorkbookScope.class); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Get Worksheets collection | |
WorksheetCollection worksheets = workbook.getWorksheets(); | |
// Accessing the first worksheet in the Excel file | |
Worksheet sheet = worksheets.get(0); | |
// Get worksheet Cells collection | |
Cells cells = sheet.getCells(); | |
// Creating a workbook scope named range | |
Range namedRange = cells.createRange("A1", "C10"); | |
namedRange.setName("Sheet1!local"); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "output.xls"); |