NPOI read Excel

Source: Internet
Author: User

Project Environment: Webform framework4.0

Dll version: NPOI2.0 dotnet2.0

I want to create an excel import function in the past two days. I thought I had used NPOI before. I wrote a DEMO today and it was quite smooth. After all, I used it before, I still want to record it and copy it later.

Read the excel Data and splice it into the able. In order to use SqlBulkCopy to copy the data to the database at a time

1 IWorkbook workbook = null; 2 string fileExt = Path. getExtension (path); 3 try 4 {5 using (var file = new FileStream (path, FileMode. open, FileAccess. read) 6 {7 if (fileExt = ". xls ") 8 workbook = new HSSFWorkbook (file); 9 else if (fileExt = ". xlsx ") 10 workbook = new XSSFWorkbook (file); 11 else12 {13 14} 15} 16} 17 catch (Exception ex) 18 {}View Code 1 // get sheet page 2 var sheet = workbook. getSheetAt (0); 3 // get the total number of items 4 int RowCount = sheet. lastRowNum; 5 // obtain the first data of the sheet page. 6 IRow firstRow = sheet. getRow (0); 7 // get the total number of Columns 8 int CellCount = firstRow. lastCellNum; 9 10 DataTable dt = new DataTable (); 11 for (int j = 0; j <CellCount; j ++) 12 {13 string value = firstRow. getCell (j ). stringCellValue; 14 DataColumn dc = new DataColumn (value, typeof (String); 15 Dt. columns. add (dc); 16} 17 18 for (int I = 1; I <= RowCount; I ++) 19 {20 IRow row = sheet. getRow (I); 21 DataRow dr = dt. newRow (); 22 for (int j = 0; j <CellCount; j ++) 23 {24 object obj = row. getCell (j); 25 if (obj! = Null) 26 dr [j] = obj. ToString (); 27 else28 dr [j] = ""; 29} 30 dt. Rows. Add (dr); 31}View Code

Use SqlBulkCopy

SqlBulkCopy sqlbulkcopy = new SqlBulkCopy (connectionString, response. UseInternalTransaction); sqlbulkcopy. DestinationTableName = "Table_1"; // sqlbulkcopy. WriteToServer (dataset. Tables [0]) in the database;

 

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.