Use NPOI to upload excel and npoi to upload excel

Source: Internet
Author: User

Use NPOI to upload excel and npoi to upload excel

The purpose of this article is to record problems encountered in the work, so that problems can be solved quickly in the future.

The NPOI version I use is 2.2.1.0.

Namespace to be used

using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;

First, you must read the content in the excel file and convert it into a table.

String path is the local address of the excel file.

Stream fs is the Stream for uploading Files, which can be obtained according to Request. Files [0]. InputStream

Public DataTable GetexcelDataSet (string path, Stream fs) {IWorkbook workbook = null; if (path. indexOf (". xlsx ")> 0) {workbook = new XSSFWorkbook (fs); // excel 2007} else if (path. indexOf (". xls ")> 0) {workbook = new HSSFWorkbook (fs); // excel version 2003} ISheet sheet = workbook. getSheetAt (0); // get the first DataTable table = new DataTable (); IRow headerRow = sheet. getRow (0); // The first row title line int cellCount = header Row. lastCellNum; // LastCellNum = PhysicalNumberOfCells int rowCount = sheet. lastRowNum; // LastRowNum = PhysicalNumberOfRows-1 for (int I = headerRow. firstCellNum; I <cellCount; I ++) {DataColumn column = new DataColumn (headerRow. getCell (I ). stringCellValue); table. columns. add (column); // Add row title} for (int I = (sheet. firstRowNum + 1); I <= rowCount; I ++) {IRow row = sheet. getRow (I); DataRow dataRow = Table. NewRow (); if (row! = Null) {for (int j = row. FirstCellNum; j <cellCount; j ++) {if (row. GetCell (j )! = Null) dataRow [j] = row. GetCell (j) ;}} table. Rows. Add (dataRow);} return table ;}

After dateTable is obtained, it is inserted into the database using a transaction loop. This is not explained.

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.