Back to Devexpress

Use the Excel Export API to Specify the Cell Selection

officefileapi-400609-excel-export-library-cells-how-to-specify-a-cell-selection.md

latest2.3 KB
Original Source

Use the Excel Export API to Specify the Cell Selection

  • Sep 19, 2023
  • 2 minutes to read

You can use the following API properties to select cells in a generated worksheet:

PropertyDescription
IXlSheet.SelectionProvides access to the IXlSheetSelection object that allows you to specify the cell selection.
IXlSheetSelection.SelectedRangesSpecifies a list of cell ranges to select in a worksheet.
IXlSheetSelection.ActiveCellSpecifies an active cell.

You should specify the cell selection before you generate a worksheet’s content.

csharp
// Create a new document and write it to the stream.
using (IXlDocument document = exporter.CreateDocument(stream))
{
    // Add a new worksheet to the document.
    using (IXlSheet sheet = document.CreateSheet())
    {
        // Specify the cell ranges you want to select.
        IList<XlCellRange> selectedRanges = sheet.Selection.SelectedRanges;
        selectedRanges.Add(XlCellRange.FromLTRB(0, 1, 2, 3)); // A2:C4
        selectedRanges.Add(XlCellRange.FromLTRB(2, 5, 3, 8)); // C6:D9

        // Set the active cell.
        sheet.Selection.ActiveCell = new XlCellPosition(1, 2); // B3

        // Generate the document's content.
        // ...
    }
}
vb
' Create a new document and write it to the stream.
Using document As IXlDocument = exporter.CreateDocument(stream)
    ' Add a new worksheet to the document.
    Using sheet As IXlSheet = document.CreateSheet()
        ' Specify the cell ranges you want to select.
        Dim selectedRanges As IList(Of XlCellRange) = sheet.Selection.SelectedRanges
        selectedRanges.Add(XlCellRange.FromLTRB(0, 1, 2, 3)) ' A2:C4
        selectedRanges.Add(XlCellRange.FromLTRB(2, 5, 3, 8)) ' C6:D9

        ' Set the active cell.
        sheet.Selection.ActiveCell = New XlCellPosition(1, 2) ' B3

        ' Generate the document's content.
        ' ...
    End Using
End Using

The image below shows the result.