Monday 28 March 2016

Read excel to datatable using openXML DLL

Need to add openxml DLL reference from codeplex and use below code to read excel to datatable

static void Main(string[] args)
        {
DataTable dtRecords;
            dtRecords = new DataTable();
            dtRecords.Columns.Add("URL");        
            DataTable dt = new DataTable();

            SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open("C:\\Sites.xlsx.", false);
            {
                IEnumerable<Sheet> sheets =
                    spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
                string relationshipId = sheets.First().Id.Value;
                WorksheetPart worksheetPart =
                    (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
                Worksheet workSheet = worksheetPart.Worksheet;
                SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                IEnumerable<Row> rows = sheetData.Descendants<Row>();
                foreach (Cell cell in rows.ElementAt(0))
                {
                    dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
                }
                foreach (Row row in rows)
                {
                    DataRow tempRow = dt.NewRow();
                    for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                    {
                        tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
                    }
                    dt.Rows.Add(tempRow);
                }
                dt.Rows.RemoveAt(0);
                //CreateDocumentSetInMeetings(dt);
            }
            foreach (DataRow row in dt.Rows)
            {
           //do your stuff
            }
}
public static string GetCellValue(SpreadsheetDocument document, Cell cell)
        {
            SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
            if (cell.CellValue == null)
            {
                return "";
            }
            string value = cell.CellValue.InnerXml;
            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
            {
                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            }
            else
            {
                return value;
            }
        }

No comments:

Post a Comment