Friday, September 23, 2016

  Read and Import Excel data to DataTable using closedXml



protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] {
                new DataColumn("Number"typeof(int)),
                new DataColumn("String"typeof(string)),
                new DataColumn("DateTime"typeof(DateTime)),
                new DataColumn("Formula"typeof(string))
            });
    string file = Server.MapPath("~/TestData.xlsx");
    using (XLWorkbook workBook = new XLWorkbook(file))
    {
        IXLWorksheet workSheet = workBook.Worksheet(1);
        bool firstRow = false;
        foreach (IXLRow row in workSheet.Rows())
        {
            if (firstRow)
            {
                foreach (IXLCell cell in row.Cells())
                {
                    dt.Columns.Add(cell.Value.ToString());
                }
                firstRow = false;
            }
            else
            {
                dt.Rows.Add();
                int i = 0;
                foreach (IXLCell cell in row.Cells())
                {
                    if (cell.DataType == ClosedXML.Excel.XLCellValues.Number && !cell.HasFormula)
                    {
                        dt.Rows[dt.Rows.Count - 1][0] = cell.Value.ToString();
                    }
                    else if (cell.DataType == ClosedXML.Excel.XLCellValues.Text && !cell.HasFormula)
                    {
                        dt.Rows[dt.Rows.Count - 1][1] = cell.Value.ToString();
                    }
                    else if (cell.DataType == ClosedXML.Excel.XLCellValues.DateTime && !cell.HasFormula)
                    {
                        dt.Rows[dt.Rows.Count - 1][2] = cell.Value.ToString();
                    }
                    else if (cell.HasFormula && (cell.DataType == ClosedXML.Excel.XLCellValues.Number
                        || cell.DataType == ClosedXML.Excel.XLCellValues.Text || cell.DataType == ClosedXML.Excel.XLCellValues.DateTime))
                    {
                        dt.Rows[dt.Rows.Count - 1][3] = cell.Value.ToString();
                    }
                    i++;
                }
            }
        }
    }
    gvDetails.DataSource = dt;
    gvDetails.DataBind();
}

//Get the ClosedXML sdk from the following link
https://closedxml.codeplex.com/releases/view/197852

No comments:

Post a Comment