Babu Goel
Babu Goel

Reputation: 57

C# EPPlus: How to reorder sheets position in a excel file

I am generating excel file with EPPlus. My Excel file has 4 sheets. those are Vertical, Summary, Delta & DashBoard. now those sheets order are Vertical, Summary, Delta & DashBoard but i want to open that excel file and change the order again using code.

new order will be Summary , Vertical, DashBoard & Delta. i searched google to know how to change order but not very luck now. i found this url How to Move a sheet using EPPlus?

the way it says like

excelPackage.Workbook.Worksheets.MoveAfter()
excelPackage.Workbook.Worksheets.MoveBefore()
excelPackage.Workbook.Worksheets.MoveToStart()
excelPackage.Workbook.Worksheets.MoveToEnd()

but using above code how can i instruct a system that i want this order Summary , Vertical, DashBoard & Delta.

if anyone has any idea how to open excel file and reorder sheets position then please share the idea or sample code.

Thanks

Upvotes: 0

Views: 1002

Answers (1)

Babu Goel
Babu Goel

Reputation: 57

I have done the job this way. i am sharing the working code which may help others. Thanks

FileInfo newFile = new FileInfo("d:\\TestOrder.xlsx");
ExcelPackage pck = new ExcelPackage(newFile);

List<string> _sheet = new List<string>();
_sheet.Add("Summary");
_sheet.Add("Vertical");
_sheet.Add("DashBoard");
_sheet.Add("Delta");

int counter = 1;
foreach (var wsname in pck.Workbook.Worksheets)
{
    string worksheetname = wsname.Name;

    int index = _sheet.FindIndex(str => str.Contains(worksheetname));
    pck.Workbook.Worksheets.MoveAfter(counter, index + 1);
    counter++;
}

pck.Save();

Upvotes: 1

Related Questions