Hi smile,
Check this example. Now please take its reference and correct your code.
For reading excel i have used ClosedXML. You can refer below link for more details.
I have added two Button controls, one DataGridView control and one OpenFileDialog control in the Form.
Namespaces
C#
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using ClosedXML.Excel;
VB.Net
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Imports System.Linq
Imports ClosedXML.Excel
Code
C#
public partial class Form1 : Form
{
private static DataTable dt;
public Form1()
{
InitializeComponent();
}
private void btnImport_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string filePath = openFileDialog1.FileName;
using (XLWorkbook workBook = new XLWorkbook(filePath))
{
IXLWorksheet workSheet = workBook.Worksheet(1);
dt = new DataTable();
bool firstRow = true;
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())
{
dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
i++;
}
}
dataGridView1.DataSource = dt;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
DataTable dtStudent = dt.Copy();
DataTable dtClass = new DataTable();
dtClass.Columns.Add("ClassID", typeof(int));
dtClass.Columns.Add("ClassName", typeof(string));
object[] classNames = dt.AsEnumerable().Select(x => x["ClassName"]).Distinct().ToArray();
for (int i = 0; i < classNames.Length; i++)
{
DataRow dr = dtClass.NewRow();
dr["ClassID"] = i + 1;
dr["ClassName"] = classNames[i];
dtClass.Rows.Add(dr);
// Insert into tblClass.
SqlCommand cmdClass = new SqlCommand();
cmdClass.CommandText = "INSERT INTO tblClass (ClassID,ClassName) VALUES (@ClassID,@ClassName)";
cmdClass.Parameters.AddWithValue("@ClassID", i + 1);
cmdClass.Parameters.AddWithValue("@ClassName", classNames[i]);
Insert(cmdClass);
}
DataTable dtSection = new DataTable();
dtSection.Columns.Add("SectionID", typeof(int));
dtSection.Columns.Add("ClassID", typeof(int));
dtSection.Columns.Add("SectionName", typeof(string));
var sections = dt.AsEnumerable()
.Select(x => new
{
SectionName = x["SectionName"],
ClassName = x["ClassName"]
}).Distinct().ToList();
for (int i = 0; i < sections.Count; i++)
{
DataRow dr = dtSection.NewRow();
dr["SectionID"] = i + 1;
dr["ClassID"] = dtClass.Select("ClassName='" + sections[i].ClassName + "'").FirstOrDefault().Field<int>("ClassID");
dr["SectionName"] = sections[i].SectionName;
dtSection.Rows.Add(dr);
// Insert into tblSection.
SqlCommand cmdSection = new SqlCommand();
cmdSection.CommandText = "INSERT INTO tblSection (SectionID,ClassID,SectionName) VALUES (@SectionID,@ClassID,@SectionName)";
cmdSection.Parameters.AddWithValue("@SectionID", i + 1);
cmdSection.Parameters.AddWithValue("@ClassID", dtClass.Select("ClassName='" + sections[i].ClassName + "'").FirstOrDefault().Field<int>("ClassID"));
cmdSection.Parameters.AddWithValue("@SectionName", sections[i].SectionName);
Insert(cmdSection);
}
foreach (DataRow dr in dtStudent.Rows)
{
dr["ClassName"] = dtClass.AsEnumerable().Where(x => x["ClassName"] == dr["ClassName"]).Select(x => x["ClassID"]).FirstOrDefault();
dr["SectionName"] = dtSection.AsEnumerable().Where(x => x["SectionName"] == dr["SectionName"]).Select(x => x["SectionID"]).FirstOrDefault();
//Insert into tblStudent.
SqlCommand cmdStudent = new SqlCommand();
cmdStudent.CommandText = "INSERT INTO tblStudent (StuID,StuName,FName,ClassID,SectionID) VALUES (@StuID,@StuName,@FName,@ClassID,@SectionID)";
cmdStudent.Parameters.AddWithValue("@StuID", dr["StuID"]);
cmdStudent.Parameters.AddWithValue("@StuName", dr["StuName"]);
cmdStudent.Parameters.AddWithValue("@FName", dr["FName"]);
cmdStudent.Parameters.AddWithValue("@ClassID", dr["ClassName"]);
cmdStudent.Parameters.AddWithValue("@SectionID", dr["SectionName"]);
Insert(cmdStudent);
}
}
private void Insert(SqlCommand cmd)
{
string conString = @"Server=.;DataBase=Test;UID=sa;PWD=pass@123";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}
}
VB.Net
Public Class Form1
Private Shared dt As DataTable
Public Sub New()
InitializeComponent()
End Sub
Private Sub btnImport_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnImport.Click
openFileDialog1.ShowDialog()
End Sub
Private Sub openFileDialog1_FileOk(sender As Object, e As CancelEventArgs) Handles openFileDialog1.FileOk
Dim filePath As String = openFileDialog1.FileName
Using workBook As XLWorkbook = New XLWorkbook(filePath)
Dim workSheet As IXLWorksheet = workBook.Worksheet(1)
dt = New DataTable()
Dim firstRow As Boolean = True
For Each row As IXLRow In workSheet.Rows()
If firstRow Then
For Each cell As IXLCell In row.Cells()
dt.Columns.Add(cell.Value.ToString())
Next
firstRow = False
Else
dt.Rows.Add()
Dim i As Integer = 0
For Each cell As IXLCell In row.Cells()
dt.Rows(dt.Rows.Count - 1)(i) = cell.Value.ToString()
i += 1
Next
End If
dataGridView1.DataSource = dt
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
Next
End Using
End Sub
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Dim dtStudent As DataTable = dt.Copy()
Dim dtClass As DataTable = New DataTable()
dtClass.Columns.Add("ClassID", GetType(Integer))
dtClass.Columns.Add("ClassName", GetType(String))
Dim classNames As Object() = dt.AsEnumerable().[Select](Function(x) x("ClassName")).Distinct().ToArray()
For i As Integer = 0 To classNames.Length - 1
Dim dr As DataRow = dtClass.NewRow()
dr("ClassID") = i + 1
dr("ClassName") = classNames(i)
dtClass.Rows.Add(dr)
Dim cmdClass As SqlCommand = New SqlCommand()
cmdClass.CommandText = "INSERT INTO tblClass (ClassID,ClassName) VALUES (@ClassID,@ClassName)"
cmdClass.Parameters.AddWithValue("@ClassID", i + 1)
cmdClass.Parameters.AddWithValue("@ClassName", classNames(i))
Insert(cmdClass)
Next
Dim dtSection As DataTable = New DataTable()
dtSection.Columns.Add("SectionID", GetType(Integer))
dtSection.Columns.Add("ClassID", GetType(Integer))
dtSection.Columns.Add("SectionName", GetType(String))
Dim sections = dt.AsEnumerable().Select(Function(x) New With {Key _
.SectionName = x("SectionName"), Key _
.ClassName = x("ClassName")
}).Distinct().ToList()
For i As Integer = 0 To sections.Count - 1
Dim dr As DataRow = dtSection.NewRow()
dr("SectionID") = i + 1
dr("ClassID") = dtClass.[Select]("ClassName='" & sections(i).ClassName & "'").FirstOrDefault().Field(Of Integer)("ClassID")
dr("SectionName") = sections(i).SectionName
dtSection.Rows.Add(dr)
Dim cmdSection As SqlCommand = New SqlCommand()
cmdSection.CommandText = "INSERT INTO tblSection (SectionID,ClassID,SectionName) VALUES (@SectionID,@ClassID,@SectionName)"
cmdSection.Parameters.AddWithValue("@SectionID", i + 1)
cmdSection.Parameters.AddWithValue("@ClassID", dtClass.[Select]("ClassName='" & sections(i).ClassName & "'").FirstOrDefault().Field(Of Integer)("ClassID"))
cmdSection.Parameters.AddWithValue("@SectionName", sections(i).SectionName)
Insert(cmdSection)
Next
For Each dr As DataRow In dtStudent.Rows
dr("ClassName") = dtClass.AsEnumerable().Where(Function(x) x("ClassName") = dr("ClassName")).[Select](Function(x) x("ClassID")).FirstOrDefault()
dr("SectionName") = dtSection.AsEnumerable().Where(Function(x) x("SectionName") = dr("SectionName")).[Select](Function(x) x("SectionID")).FirstOrDefault()
Dim cmdStudent As SqlCommand = New SqlCommand()
cmdStudent.CommandText = "INSERT INTO tblStudent (StuID,StuName,FName,ClassID,SectionID) VALUES (@StuID,@StuName,@FName,@ClassID,@SectionID)"
cmdStudent.Parameters.AddWithValue("@StuID", dr("StuID"))
cmdStudent.Parameters.AddWithValue("@StuName", dr("StuName"))
cmdStudent.Parameters.AddWithValue("@FName", dr("FName"))
cmdStudent.Parameters.AddWithValue("@ClassID", dr("ClassName"))
cmdStudent.Parameters.AddWithValue("@SectionID", dr("SectionName"))
Insert(cmdStudent)
Next
End Sub
Private Sub Insert(ByVal cmd As SqlCommand)
Dim conString As String = "Server=.;DataBase=Test;UID=sa;PWD=pass@123"
Using con As SqlConnection = New SqlConnection(conString)
con.Open()
cmd.Connection = con
cmd.ExecuteNonQuery()
con.Close()
End Using
End Sub
End Class
Screenshot
The form
Database record on save Button click