19 June, 2011

Get data from CSV and Excel File in C#.NET

/*Get data from CSV File*/

public DataTable GetDataFromCSVFile(string sFolderName, string sFileName)

{

DataTable oTable = new DataTable("DFCSVFile");

try

{

String strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data

Source=" + sFolderName + ";Extended Properties='text;HDR=Yes'";

DataSet ds = new DataSet();

OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM " +

sFileName , strConn);

da.Fill(ds);

oTable= ds.Tables[0];

}

catch (Exception e)

{

throw new Exception(e.Message);

}

return oTable;

}

/*Get data from Excel File*/

public DataTable GetDataFromExcelFile(string sFilePath, string sSheetName)

{

DataTable oTable = new DataTable("EFile");

try

{

String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

sFilePath + ";Extended Properties=Excel 8.0;";

DataSet ds = new DataSet();

OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM " +

sSheetName + "", strConn);

da.Fill(ds);

oTable = ds.Tables[0];

}

catch (Exception e)

{

throw new Exception(e.Message);

}

return oTable;

}



No comments:

Post a Comment