officefileapi-120750-excel-export-library-worksheets-how-to-reorder-worksheets-within-a-document.md
The following example demonstrates how to use the IXlDocument.SetSheetPosition method to change a worksheet’s position within a workbook.
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);
}
}
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