首页 > 数据库技术 > 详细

Excel批量插入的SQL Server

时间:2020-04-27 10:36:04      阅读:111      评论:0      收藏:0      [点我收藏+]

首先新建一个WPF的项目,名为ExcelToServerDemo

技术分享图片

 

 

到Nuget去安装NPOI的Nuget包,点击安装即可,会自动引用项目。

技术分享图片

 

 

新建一个Student的表格,有名字,年龄,性别,地址,以及民族,以及出生日期技术分享图片

 

 

技术分享图片

查看Sudent 表格的数据为空

 

技术分享图片

 

 新建个Excel表格数据如下,这里的表头我用了英文,不影响。

技术分享图片

 

 再来设计一下WPF的界面,我们就用一个按钮和一个按钮事件处理就好了,如下图

 

技术分享图片

 

 后台代码如下

技术分享图片

 

 

var datatble = new DataTable();
            var connectionsting = "Server=DESKTOP-GBT0AFP;Initial Catalog=Lexan;Integrated Security=SSPI;";
            var sqldataadapter = new SqlDataAdapter("select * from Student", connectionsting);
            var sqlbulkcopy = new SqlBulkCopy(connectionsting) { DestinationTableName = "Student" };
            sqldataadapter.FillSchema(datatble, SchemaType.Source);
            var xssfworkbook = new XSSFWorkbook(File.OpenRead(@"C:\Users\News\Desktop\Student.xlsx"));
            var sheetrow= xssfworkbook.GetSheetAt(0);
            for (int i = 1; i < sheetrow.LastRowNum; i++)
            {
                var tablenewrow = datatble.NewRow();
                var temprow = sheetrow.GetRow(i);
                tablenewrow[0] = temprow.Cells[0].StringCellValue;
                tablenewrow[1] = temprow.Cells[1].NumericCellValue;
                tablenewrow[2] = temprow.Cells[2].StringCellValue;
                tablenewrow[3] = temprow.Cells[3].StringCellValue;
                tablenewrow[4] = temprow.Cells[4].StringCellValue;
                tablenewrow[5] = temprow.Cells[5].DateCellValue;
                datatble.Rows.Add(tablenewrow);
            }
            sqlbulkcopy.WriteToServer(datatble);
            MessageBox.Show("写入完成!");

  然后运行一下

 

技术分享图片

 

 

再来查看一下数据库

技术分享图片

 

 感谢观看。

 原文作者:https://www.cnblogs.com/R00R/p/11446911.html

Excel批量插入的SQL Server

原文:https://www.cnblogs.com/Smina/p/12784687.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!