Get Max Range In A Worksheet
When reading data from the worksheet, we need to know the maximum area.
When copying all data from a worksheet, we need to know the maximum area.
When exporting a specified area to html and pdf, we need to know the maximum area.
Aspose.Cells for .Net contains different ways to find max range in a worksheet.
Getting max range
In Aspose.Cells ,if the row and column objects are initialized, these rows and columns will be counted to the maximum area, even if there is no data in empty rows or columns.
Workbook workbook = new Workbook("Book1.xlsx"); | |
// Get all the worksheets in the book. | |
WorksheetCollection worksheets = workbook.Worksheets; | |
Worksheet sheet = worksheets[0]; | |
//Gets the max data range. | |
int maxRow = sheet.Cells.MaxRow; | |
int maxColumn = sheet.Cells.MaxColumn; | |
//The range is A1:B3. | |
Range range = sheet.Cells.CreateRange(0, 0, maxRow + 1, maxColumn + 1); | |
sheet.Cells["A10"].PutValue(null); | |
maxRow = sheet.Cells.MaxRow; | |
maxColumn = sheet.Cells.MaxColumn; | |
//The range is udpated to A1:B10. | |
range = sheet.Cells.CreateRange(0, 0, maxRow + 1, maxColumn + 1); |
Getting max data range
In most cases, we only need to obtain all the ranges containing all the data, even if the empty cells outside the range are formatted. And the settings about shapes, tables and pivottables will be ignored.
// Instantiate a new Workbook. | |
Workbook workbook = new Workbook("Book1.xlsx"); | |
// Get all the worksheets in the book. | |
WorksheetCollection worksheets = workbook.Worksheets; | |
Worksheet sheet = worksheets[0]; | |
//Gets the max data range. | |
int maxRow = sheet.Cells.MaxDataRow; | |
int maxColumn = sheet.Cells.MaxDataColumn; | |
//The range is A1:B3. | |
Range range = sheet.Cells.CreateRange(0, 0, maxRow + 1, maxColumn + 1); | |
sheet.Cells["A10"].PutValue(null); | |
maxRow = sheet.Cells.MaxDataRow; | |
maxColumn = sheet.Cells.MaxDataColumn; | |
//The range is still A1:B3. | |
range = sheet.Cells.CreateRange(0, 0, maxRow + 1, maxColumn + 1); |
Getting max display range
When we export all data from the worksheet to HTML, PDF, or images, we need to obtain an area containing all visible objects, including data, styles, graphics, tables, and pivot tables. The following codes show how to render the max diplay range to html:
// Instantiate a new Workbook. | |
Workbook workbook = new Workbook("Book1.xlsx"); | |
// Get all the worksheets in the book. | |
WorksheetCollection worksheets = workbook.Worksheets; | |
//Gets the max display range. | |
Range range = worksheets[0].Cells.MaxDisplayRange; | |
//Save the range to html | |
HtmlSaveOptions saveOptions = new HtmlSaveOptions(); | |
saveOptions.ExportActiveWorksheetOnly = true; | |
saveOptions.ExportArea = CellArea.CreateCellArea(range.FirstRow, range.FirstColumn, range.FirstRow + range.RowCount - 1, range.FirstColumn + range.ColumnCount - 1); | |
//Save the range. | |
workbook.Save("html.html", saveOptions); |
Here is source excel file.