How to define discontinuous ranges?

8 Dec 20233 minutes to read

You can define a discontinuous range by adding different ranges to the Range collection. The following code example illustrates this.

using (ExcelEngine excelEngine = new ExcelEngine())
{
  IApplication application = excelEngine.Excel;
  application.DefaultVersion = ExcelVersion.Excel2013;
  IWorkbook workbook = application.Workbooks.Create(1);
  IWorksheet worksheet = workbook.Worksheets[0];

  //Create Range collection.
  IRanges rangeCollection = worksheet.CreateRangesCollection();

  //Add different ranges to the Range collection.
  rangeCollection.Add(worksheet.Range["D2:D3"]);
  rangeCollection.Add(worksheet.Range["D10:D11"]);
  rangeCollection.Text = "Welcome";

  FileStream stream = new FileStream("DiscontinuousRange.xlsx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
  workbook.SaveAs(stream);
  workbook.Close();
  excelEngine.Dispose();
}
using (ExcelEngine excelEngine = new ExcelEngine())
{
  IApplication application = excelEngine.Excel;
  application.DefaultVersion = ExcelVersion.Excel2013;
  IWorkbook workbook = application.Workbooks.Create(1);
  IWorksheet worksheet = workbook.Worksheets[0];

  //Create Range collection.
  IRanges rangeCollection = worksheet.CreateRangesCollection();

  //Add different ranges to the Range collection.
  rangeCollection.Add(worksheet.Range["D2:D3"]);
  rangeCollection.Add(worksheet.Range["D10:D11"]);
  rangeCollection.Text = "Welcome";

  workbook.SaveAs("DiscontinuousRange.xlsx");
}
Using excelEngine As ExcelEngine = New ExcelEngine()
  Dim application As IApplication = excelEngine.Excel
  application.DefaultVersion = ExcelVersion.Excel2013
  Dim workbook As IWorkbook = application.Workbooks.Create(1)
  Dim worksheet As IWorksheet = workbook.Worksheets(0)

  'Create Range collection.
  Dim range As IRanges = worksheet.CreateRangesCollection()

  'Add different ranges to the Range collection.
  range.Add(worksheet.Range("D2:D3"))
  range.Add(worksheet.Range("D10:D11"))
  range.Text = "Welcome"

  workbook.SaveAs("DiscontinuousRange.xlsx")
End Using

See Also