Friday, February 26, 2010

Reading data from Excel and create a datatable

//read data from Excel
object[,] colDataValues = (object[,])objRange.Value2;


//create columns
for (int index = 1; index <= colDataValues.GetLength(1); index++ )
{
DataColumn col = new DataColumn();
col.ColumnName = (string)colDataValues[1,index];
excelData.Columns.Add(col);
}

//reading rows values
for (int i = 2; i <= colDataValues.GetLength(0); i++)
{
DataRow row = excelData.NewRow();
for (int j = 1; j <= colDataValues.GetLength(1); j++)
{
row[j-1] = Convert.ToString(colDataValues[i, j]);
}
excelData.Rows.Add(row);
}

No comments:

Post a Comment