How to import data from CSV to Database
Use the function below to import the data from excel to the database connected
public void importdatafromexcel(string excelfilepath)
{
try
{
DataTable tblReadCSV= new DataTable();
tblReadCSV.Columns.Add("ID");
tblReadCSV.Columns.Add("Name");
Microsoft.VisualBasic.FileIO.TextFieldParser csvParser = new Microsoft.VisualBasic.FileIO.TextFieldParser(excelfilepath);
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true))
{
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());
SqlCommand cmd = new SqlCommand();
cnn.Open();
for (int i = 0; i < tblReadCSV.Rows.Count; i++)
{
cmd = new SqlCommand("Insert into Tests (ID,Name) Values ('" + tblReadCSV.Rows[i]["ID"] + "','" + tblReadCSV.Rows[i]["Name"] + "')", cnn);
cmd.ExecuteNonQuery();
}
cnn.Close();
}
catch (Exception ex)
{
}
}
0 Comment(s)