Excel bulk inserts SQL Server

First create a new WPF project, called ExcelToServerDemo

NPOI to Nuget to install the Nuget package, you can click on the installation, it will automatically referenced project.

Create a Student of the table, with the name, age, sex, address, and nationality, and date of birth

View Sudent table of data is empty

A new Excel spreadsheet data as follows, where the header I used English, does not affect.

WPF interface design come about, we will deal with just fine with a button and a button event, as shown below

Background code as follows

            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("写入完成!");

 

Then run it

Again look at the database

thanks for watching.

Guess you like

Origin www.cnblogs.com/R00R/p/11446911.html