C # Implementation reads data from Excel files to SQL Server database

Source: Internet
Author: User
Tags bulk insert first row

With third-party components: Npoi component implementation

Go to the official website: http://npoi.codeplex.com/The download requires the introduction of a DLL (you can select the. net2.0 or. net4.0 dll), and then add references to the Web site. With Npoi, you can read and write Word/excel documents on a machine that does not have Office installed or the appropriate environment.

Create an entity class first:

[Table ("Customer") ]     Public classCustomer {[Key] Public intId {Get;Set; }  Public stringFirstName {Get;Set; }  Public stringLastName {Get;Set; }  Public intAge {Get;Set; }  Public intGender {Get;Set; } }
Create a new entity class customer

Create a class to implement reading data from an Excel file to list<customer>.

  Public classImportexcel { PublicIlist<customer> Importexecltocustomer (stringFilePath) {            varCustomerList =NewList<customer>();            Customer customer; if(string. IsNullOrEmpty (FilePath)) {return NULL; } FileStream FileStream=NewFileStream (FilePath, FileMode.Open, FileAccess.Read); Xssfworkbook WorkBook=NewXssfworkbook (FileStream); intSheetcount =Workbook.count; if(Sheetcount >0)            {                varSheet = Workbook.getsheetat (0); //start the import from the second line, the first row is the column name                 for(intI=1; i<= sheet. Lastrownum; i++) {IRow row=sheet.                                        GetRow (i); //get the value of each column in the row                    stringTmpfirstname = Getcellvaluestringfromisheet (Row,0); stringTmplastname = Getcellvaluestringfromisheet (Row,1); stringTmpage = Getcellvaluestringfromisheet (Row,2); stringTmpgender = Getcellvaluestringfromisheet (Row,3); Customer=NewCustomer () {FirstName=Tmpfirstname, LastName=Tmplastname, age=Convert.ToInt32 (tmpage), Gender=Convert.ToInt32 (Tmpgender)};                customerList.Add (customer); }            }            returncustomerlist; }        Private stringGetcellvaluestringfromisheet (IRow Row,intColindex) {            if(Row! =NULL) {Icell cell=row.                Getcell (Colindex); if(Cell! =NULL)                {                    if(Cell. Celltype = =celltype.string) {returncell.                    Stringcellvalue.trim (); }                    if(Cell. Celltype = =celltype.numeric) {returncell. Numericcellvalue.tostring ().                    Trim (); }                    returncell.                Stringcellvalue.trim (); }            }            return string.        Empty; }    }
implements reading data from Excel into List

Methods in the main function to implement BULK INSERT data into SQL Server database tables

classProgram {Static voidMain (string[] args) {            stringFilePath =@"E:\Customer_Test.xlsx"; Importexcel Importexcel=NewImportexcel (); varCustomerList =Importexcel.importexecltocustomer (FilePath); #regionAdding data to a databaseusing(Codefirstdbcontext context =NewCodefirstdbcontext ()) {                //EF Big Data batch processingcontext.                Bulkinsert (customerlist); Context.            SaveChanges ();            }; #endregionConsole.readkey (); }    }
inserting data into the database is implemented in the main function

The code is applied to the EF create entity, BULK Insert data method, in subsequent articles will be listed in detail

C # Implementation reads data from Excel files to SQL Server database

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.