Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've to read the only headers (not data)of the first sheet form an excel document with multiple sheets . I don't want to load the complete document in the memory hence no DOM approach. The code I'm using reads the second sheet of the file and not the first ?


C#
internal DataTable GetSchema(string fileName)

{

 int i = 0;

 DataTable dataTable = new DataTable();

 using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false))

{

 WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;               
 
 foreach (WorksheetPart worksheetPart in workbookPart.WorksheetParts)

{

 OpenXmlReader reader = OpenXmlReader.Create(worksheetPart);// (

 while (reader.Read())

{

 if (reader.ElementType == typeof(Row))///loops through row 

{

reader.ReadFirstChild();

 if (i > 1)

{

return dataTable;
 
 // we have recieved all column names till here 

}

 i++; //increments for the first time which means we are reading columns 

 do

{

 if (reader.ElementType == typeof(Cell))

{

 Cell c = (Cell)reader.LoadCurrentElement();

 string cellValue = string.Empty;

 if (c.CellValue != null)

{

 if (c.DataType != null && c.DataType == CellValues.SharedString)

{

 SharedStringItem ssi = workbookPart.SharedStringTablePart.SharedStringTable.Elements<sharedstringitem>().ElementAt(int.Parse(c.CellValue.InnerText));                                           

 cellValue = Convert.ToString(ssi.InnerText);

}

else

{

 cellValue = Convert.ToString(c.CellValue.InnerText);

}

}

 else

{

                                       

cellValue = c.InnerText;

}

                                    

 if (i <= 1)

{

dataTable.Columns.Add(cellValue);

}

 else

{

 break;

}

}

 } while (reader.ReadNextSibling());

}

}

}

 return dataTable;

}

}






the excel file has three sheets :

1. records

2.sa

3.da (no columns)

and my code reads headers for the 2 (sa).

Can some one please help me to read the header from 1 (records) file ?
Posted
Updated 11-Feb-15 1:55am
v3

1 solution

I removed the for each, tried below line and it worked.
Apparently it looks that the order of the sheets is reversed when we read it directly.

WorksheetPart worksheetPart = workbookPart.WorksheetParts.Last();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900