Hi Maheswar, try this;
The below code will return as a DataSet, then you can bind your Gridview using this Dataset Collection of Tables. pass your excel file path to this function
public static DataSet ImportExceltoDataset(string YourFilePath)
{
Microsoft.Office.Interop.Excel.Application oXL;
Workbook oWB;
Worksheet oSheet;
Range oRng;
oXL = new Microsoft.Office.Interop.Excel.Application();
try
{
oWB = oXL.Workbooks.Open(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
int M = oXL.Worksheets.Count;
for (int sheetnum = 1; sheetnum <= M; sheetnum++)
{
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets[sheetnum];
for (int j = oSheet.UsedRange.Cells.Columns.Count + 10; j > 0; j--)
{
if (j > oSheet.UsedRange.Cells.Columns.Count)
{
if (string.IsNullOrEmpty(((Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, j]).Text.ToString()))
{
((Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, j]).EntireColumn.Delete(null);
}
}
else
{
if (string.IsNullOrEmpty(((Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, j]).Text.ToString()))
{
int IsDeleteCunt = 1;
for (int i = 1; i < oSheet.UsedRange.Cells.Rows.Count; i++)
{
if (string.IsNullOrEmpty(((Microsoft.Office.Interop.Excel.Range)oSheet.Cells[i, j]).Text.ToString()))
{
IsDeleteCunt++;
}
else
{
break;
}
}
if (IsDeleteCunt == oSheet.UsedRange.Cells.Rows.Count)
{
((Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, j]).EntireColumn.Delete(null);
}
}
}
}
}
DataSet ds = new DataSet();
string WrkshtName = "";
for (int N = 1; N <= M; N++)
{
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets[N];
WrkshtName = oSheet.Name;
System.Data.DataTable dt = new System.Data.DataTable(WrkshtName);
ds.Tables.Add(dt);
DataRow dr;
StringBuilder sb = new StringBuilder();
int jValue = oSheet.UsedRange.Cells.Columns.Count;
int iValue = oSheet.UsedRange.Cells.Rows.Count;
int EmptyColumnCount = 1;
for (int j = 1; j <= jValue; j++)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, j];
string strValue = oRng.Text.ToString();
if (strValue.Trim() == "")
{
EmptyColumnCount++;
}
dt.Columns.Add(strValue, System.Type.GetType("System.String"));
}
if (EmptyColumnCount >= jValue)
{
ds.Tables.Remove(WrkshtName);
}
else
{
for (int i = 2; i <= iValue; i++)
{
dr = ds.Tables[WrkshtName].NewRow();
int k = 0;
EmptyColumnCount = 1;
for (int j = 1; j <= jValue; j++)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[i, j];
((Range)oSheet.Cells[1, j]).EntireColumn.AutoFit();
string strValue = oRng.Text.ToString();
if (strValue.Trim() == "")
{
EmptyColumnCount++;
}
dr[k] = strValue;
k++;
}
if (EmptyColumnCount < jValue)
{
ds.Tables[WrkshtName].Rows.Add(dr);
}
}
}
}
return ds;
}
catch (Exception ex)
{
return null;
}
}
I hope this will help you. If you found any errors/difficulty means let me know.
Thank's
Mohan G