c#做窗口excel导入sqlserver教程
1、引入npoi,用vs打开项目,右键点击引用,选择NuGet管理程序包,搜索npoi,然后安装

2、导入Excel存放在DataTable中,方法如下。
private void OpenFile()
{
try
{
//获取Excel文件路径和名称
OpenFileDialog odXls = new OpenFileDialog();
//指定相应的打开文档的目录 AppDomain.CurrentDomain.BaseDirectory定位到Debug目录,再根据实际情况进行目录调整
string folderPath = AppDomain.CurrentDomain.BaseDirectory + @"databackup\";
odXls.InitialDirectory = folderPath;
// 设置文件格式
odXls.Filter = "Excel files office2003(*.xls)|*.xls|Excel office2010(*.xlsx)|*.xlsx|All files (*.*)|*.*";
//openFileDialog1.Filter = "图片文件(*.jpg)|*.jpg|(*.JPEG)|*.jpeg|(*.PNG)|*.png";
odXls.FilterIndex = 2;
odXls.RestoreDirectory = true;
if (odXls.ShowDialog() == DialogResult.OK)
{
// this.txtFilePath.Text = odXls.FileName;
//this.txtFilePath.ReadOnly = true;
string sConnString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';", odXls.FileName);
DataTable dt = ExcelHelper.ExcelToTable(odXls.FileName);
gv1.DataSource = dt;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
3、把DataTable中的数据拼接成sql语句插入到数据库中。方法如下
private void InsertData(DataTable dt)
{
try
{
string sql = "insert into table1 (列1,列2) values(";
foreach (DataRow row in dt.Rows)
{
sql = "insert into table1 (列1,列2) values('" + row["第一列"] + "','" + row["第一列"] + "')";
SqlHelper.ExecuteNonQuery(CommandType.Text, sql);//这块需要连自己的数据库,换成自己的数据库插入方法
}
MessageBox.Show("插入成功!");
}
catch(Exception ex)
{
throw ex;
}
}