MVC Import Export Excel

Source: Internet
Author: User

Add a reference to Npoi in your project

The view section is as follows:

@{    viewbag.title = "Index";    Layout = "~/views/shared/_layout.cshtml";} 

Controller section:

public class Excelcontroller:controller {////GET:/excel/public actionresult Index ()        {return View ();        }///<summary>///Bulk Export Excel//</summary>//<returns></returns> Public Fileresult Exportexcel () {///Create an object Npoi for an Excel file. HSSF. Usermodel.hssfworkbook book = new Npoi. HSSF.            Usermodel.hssfworkbook (); Add a sheet Npoi. Ss. Usermodel.isheet Sheet1 = Book.            Createsheet ("Sheet1"); Gets the list data windataentities db = new windataentities ();//ef context object list<userinfo> List = db. userinfo.where<userinfo> (U = True).            ToList (); Add the header title Npoi of the first line to Sheet1. Ss. Usermodel.irow Row1 = Sheet1.            CreateRow (0); Row1. Createcell (0).            Setcellvalue ("name"); Row1. Createcell (1).            Setcellvalue ("login name"); Progressively writes data to Sheet1 individual lines for (int i = 0; i < list. Count;    i++)        {Npoi. Ss. Usermodel.irow rowtemp = Sheet1.                CreateRow (i + 1); Rowtemp. Createcell (0). Setcellvalue (List[i].                Truename); Rowtemp. Createcell (1). Setcellvalue (List[i].            UserName);            }//write to client System.IO.MemoryStream ms = new System.IO.MemoryStream (); Book.            Write (MS); Ms.            Seek (0, Seekorigin.begin);        Return File (MS, "Application/vnd.ms-excel", "user. xls");        }///<summary>//Bulk import of Excel//</summary>//<returns></returns> Public ActionResult Importexcel () {try {httppostedfilebase file = Request.                files["File"];//receives the data that the client passes over.                if (file==null) {return Content ("Please select an Excel file to upload"); } else {//to the format of the file, omit windataentities db = new Wind Ataentities ();//ef Context Object                   Stream InputStream = file.                    InputStream;                    Hssfworkbook Hssfworkbook = new Hssfworkbook (InputStream); Npoi. Ss. Usermodel.isheet sheet = Hssfworkbook.                    Getsheetat (0); IRow HeaderRow = sheet.                    GetRow (0);//First Action header line//int cellcount = Headerrow.lastcellnum;//lastcellnum = Physicalnumberofcells int rowCount = sheet. Lastrownum;//lastrownum = PhysicalNumberOfRows-1 for (int i = (sheet. Firstrownum + 1); I <= RowCount; i++) {IRow row = sheet.                        GetRow (i);                        NewUser model = new NewUser (); if (row! = null) {if (row. Getcell (0) = null) {model. Truename = Getcellvalue (row.                            Getcell (0)); } if (row.              Getcell (1)! = NULL)              {model. LoginName = Getcellvalue (row.                            Getcell (1)); }} db.                    Newuser.add (model); } db.                    SaveChanges ();                Return Content ("Import succeeded");            }} catch (Exception) {return Content ("Import Failed"); }}///<summary>//To get the values of columns based on Excel column type///</summary>//&LT;PA Ram Name= "cell" >excel column </param>///<returns></returns> private static string Getcellval UE (Icell cell) {if (cell = = null) return string.            Empty; Switch (cell. Celltype) {case CellType.Blank:return string.                Empty; Case CellType.Boolean:return Cell.                Booleancellvalue.tostring (); Case Celltype. Error:return cell.                Errorcellvalue.tostring (); Case CellType.Numeric:case CellType.Unknown:default:return Cell. ToString ();//this is a trick to get the correct value of the cell. Numericcellvalue would return a numeric value no matter the cell value is a date or a number case CELLTYPE.S Tring:return cell.                Stringcellvalue; Case CellType.Formula:try {hssfformulaevaluator e = new HSS Fformulaevaluator (cell.                        Sheet.workbook);                        E.evaluateincell (cell); return cell.                    ToString (); } catch {return cell.                    Numericcellvalue.tostring (); }            }        }    }

  

MVC Import Export Excel

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.