Back to Devexpress

Use the Excel Export API to Reorder Worksheets within a Document

officefileapi-120750-excel-export-library-worksheets-how-to-reorder-worksheets-within-a-document.md

latest2.1 KB
Original Source

Use the Excel Export API to Reorder Worksheets within a Document

  • Sep 19, 2023

The following example demonstrates how to use the IXlDocument.SetSheetPosition method to change a worksheet’s position within a workbook.

csharp
IXlExporter exporter = XlExport.CreateExporter(XlDocumentFormat.Xlsx);
using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite)) {
    using (IXlDocument document = exporter.CreateDocument(stream)) {
        // Create the first worksheet.
        using (IXlSheet sheet = document.CreateSheet()) {
            sheet.Name = "Sheet1"
            // ...
        }
        // Create the second worksheet.
        using (IXlSheet sheet = document.CreateSheet()) {
            sheet.Name = "Sheet2"
            // ...
        }
        // Create the third worksheet.
        using (IXlSheet sheet = document.CreateSheet()) {
            sheet.Name = "Sheet3"
            // ...
        }
        // Move the last worksheet to the first position within the document.
        document.SetSheetPosition("Sheet3", 0);
    }
}
vb
Dim exporter As IXlExporter = XlExport.CreateExporter(XlDocumentFormat.Xlsx)
Using stream As New FileStream(filePath, FileMode.Create, FileAccess.ReadWrite)
    Using document As IXlDocument = exporter.CreateDocument(stream)
        ' Create the first worksheet.
        Using sheet As IXlSheet = document.CreateSheet()
            sheet.Name = "Sheet1"
            ' ...
        End Using
        ' Create the second worksheet.
        Using sheet As IXlSheet = document.CreateSheet()
            sheet.Name = "Sheet2"
            ' ...
        End Using
        ' Create the third worksheet.
        Using sheet As IXlSheet = document.CreateSheet()
            sheet.Name = "Sheet3"
            ' ...
        End Using
        ' Move the last worksheet to the first position within the document.
        document.SetSheetPosition("Sheet3", 0)
    End Using
End Using