public class ExcelToDataTable
{
public static DataTable ExtractExcelSheetValuesToDataTable(string xlsxFilePath, string sheetName, out bool blnResult)
{
blnResult = false;
DataTable dt = new DataTable();
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(xlsxFilePath, true))
{
WorkbookPart workbookPart = spreadSheet.WorkbookPart;
WorksheetPart worksheetPart = null;
if (!string.IsNullOrEmpty(sheetName))
{
Sheet ss = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).SingleOrDefault<Sheet>();
if (ss != null)
{
worksheetPart = (WorksheetPart)workbookPart.GetPartById(ss.Id);
if (worksheetPart != null)
{
blnResult = true;
}
}
else
{
blnResult = false;
}
}
else
{
blnResult = false;
}
if (!blnResult)
{
return null;
}
SharedStringTablePart stringTablePart = workbookPart.SharedStringTablePart;
if (worksheetPart != null)
{
Row firstRow = worksheetPart.Worksheet.Descendants<Row>().FirstOrDefault();
if (firstRow != null)
{
foreach (Cell c in firstRow.ChildElements)
{
string value = GetValue(c, stringTablePart);
dt.Columns.Add(value);
}
}
IEnumerable<Row> dataRows = from row in worksheetPart.Worksheet.Descendants<Row>() where row.RowIndex > 1 select row;
foreach (Row row in dataRows)
{
DataRow dr = dt.NewRow();
int j = 0;
int n;
if (row != null)
{
Boolean blnIsEmpty = true;
var catalogueValues =
from cell in row.Descendants<Cell>()
select new ExcelCol
{
cellVal = (cell.CellValue != null ? (Int32.TryParse(cell.CellValue.InnerText, out n) ? (cell.DataType != null && cell.DataType == CellValues.SharedString ? stringTablePart.SharedStringTable.ChildElements[int.Parse(cell.CellValue.InnerText)].InnerText : cell.CellValue.InnerText) : cell.CellValue.Text) : ""),
celRef = GetColumnNumber(Regex.Replace(cell.CellReference.Value, @"\d", ""))
};
foreach (var item in catalogueValues)
{
if (!string.IsNullOrEmpty(item.cellVal))
{
dr[item.celRef - 1] = item.cellVal;
blnIsEmpty = false;
}
j++;
if (j == dt.Columns.Count)
break;
}
if (!blnIsEmpty)
{
dt.Rows.Add(dr);
}
}
}
}
}
return dt;
}
private static int GetColumnNumber(string name)
{
int number = 0;
int pow = 1;
for (int i = name.Length - 1; i >= 0; i--)
{
number += (name[i] - 'A' + 1) * pow; pow *= 26;
}
return number;
}
private static string GetValue(Cell cell, SharedStringTablePart stringTablePart)
{
if (cell.ChildElements.Count == 0)
{
return null;
}
string value = cell.ElementAt(0).InnerText;
Int32 val;
if (Int32.TryParse(value, out val))
{
if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
{
value = stringTablePart.SharedStringTable.ChildElements[val].InnerText;
}
}
else
{
value = cell.CellValue.Text;
}
return value;
}
}