Tuesday, 2 September 2014

Open XML - How to read excel sheets in the same order of uploaded excel in C#

By default, when we use open xml to read multiple sheets from an excel file, it will take sheets in ascending order. So for doing it, i have added a small piece of code. We can be able to get the worksheeets by its tab index. That is we can select a sheet from the work book by its index.

Declaration
-------------
SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(xmlFile.InputStream, false);
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
WorksheetPart workPart;

Step 1. For that first create a data table to store tab names.

DataTable tabNames = new DataTable();
tabNames.Columns.Add("TabName");
tabNames.TableName = "TabName";

Step 2. Then declare a tabcounter.

int tabNumber = 0;

Step 3. Just iterate the work sheet tabs like below.

            foreach (WorksheetPart worksheetpart in spreadSheetDocument.WorkbookPart.WorksheetParts)
            {
                tabNames.Rows.Add();
                tabNames.Rows[tabNumber][0] = workbookPart.Workbook.Descendants<Sheet>().ElementAt(tabNumber).Name;
                tabNumber = tabNumber + 1;
            }

Now the data table contains sheet names in the order from the excel we uploads.

Step 4. Now iterate the datatable for doing your stuff with that sheet


for (int i = 0; i < tabNames.Rows.Count; i++)
            {
                workPart = this.GetWorksheetPart(workbookPart, tabNames.Rows[i][0].ToString());
//your stuuf
   }

below is the function GetWorksheetPart()

public WorksheetPart GetWorksheetPart(WorkbookPart workbookPart, string sheetName)
        {
            string relId = workbookPart.Workbook.Descendants<Sheet>().First(s => sheetName.Equals(s.Name)).Id;
            return (WorksheetPart)workbookPart.GetPartById(relId);
        }

===================   ***   ===================
Thanks.


No comments:

Post a Comment