Asp.net Simple Method for exporting excel

Source: Internet
Author: User

This article mainly introduces a simple example of how to export an excel file from asp.net. For more information, see

Excel operations are most commonly used for export and import. This example uses NPOI .... The Code is as follows: /// <summary> /// export Excel /// </summary> /// <param name = "stime"> </param> /// <param name = "etime"> </param> // <returns> </returns> public ActionResult Export (FormCollection frm) {DataTable dts = new DataTable (); dts = _ shopMemeber. exportMemberData (frm); IWorkbook workbook = new XSSFWorkbook (); ISheet sheet = workbook. createSheet (); IRow headerRow = sheet. createRow (0); foreach (DataColumn col Umn in dts. columns) headerRow. createCell (column. ordinal ). setCellValue (column. caption); int rowIndex = 1; foreach (DataRow row in dts. rows) {IRow dataRow = sheet. createRow (rowIndex); foreach (DataColumn column in dts. columns) {dataRow. createCell (column. ordinal ). setCellValue (row [column]. toString ();} rowIndex ++;} string filepath = Server. mapPath ("/") + @ ".xlsx"; FileStream file = new FileStr Eam (filepath, FileMode. create); workbook. write (file); ExcelHelper. downLoad (@ "/ .xlsx"); # region not enabled # endregion return SuccessMsg ("AdminMemberMemberIndex");} // This is the method for downloading to the desktop, public static void DownLoad (string FileName) {FileInfo fileInfo = new FileInfo (HttpContext. current. server. mapPath (FileName); // download the file FileStream fs = new FileStream (HttpContext. current. server. mapPath (FileName), F IleMode. open); byte [] bytes = new byte [(int) fs. length]; fs. read (bytes, 0, bytes. length); fs. close (); HttpContext. current. response. contentType = "application/octet-stream"; // notifies the browser to download the file instead of opening HttpContext. current. response. addHeader ("Content-Disposition", "attachment; filename =" + HttpUtility. urlEncode (fileInfo. name, System. text. encoding. UTF8); HttpContext. current. response. binaryWrite (bytes); HttpCont Ext. Current. Response. Flush (); HttpContext. Current. Response. End () ;}the above is the export. Next I will introduce the import. The Code is as follows: /// <summary> /// import data /// </summary> /// <param name = "file"> </param> /// <returns> true indicates that the import is successful. </returns> public bool Impoart (HttpPostedFileBase file) {try {// Save the excel string path = HttpContext. current. server. mapPath ("/"); file. saveAs (path + file. fileName); // read FileStream sw = File. open (path + file. fileName, FileMode. open, FileAccess. read); IWorkbook workbook = new XSSFWorkbook (sw); ISheet sh Eet1 = workbook. getSheet ("Sheet1"); // maximum number of rows int rowsCount = sheet1.PhysicalNumberOfRows; // determine whether the first row complies with the specifications, that is, the column name IRow firstRow = sheet1.GetRow (0) in Excel; if (! (FirstRow. getCell (0 ). toString () = "name" & firstRow. getCell (1 ). toString () = "abbreviation" & firstRow. getCell (2 ). toString () = "category" & firstRow. getCell (3 ). toString () = "reference price" & firstRow. getCell (4 ). toString () = "Product Introduction") {return false;} // skip an incorrect item for (int I = 1; I <rowsCount; I ++) {IRow row = sheet1.GetRow (I); Shop_Product product = new Shop_Product (); string category = row. getCell (2 )! = Null? Row. GetCell (2). ToString (): null; if (! String. IsNullOrEmpty (category) {var cate = _ unitOfWork. Shop_ProductCategoryRepository (). GetAll (). FirstOrDefault (t => t. Name = category); if (cate! = Null) {product. productCategoryName = cate. name; product. shop_ProductCategory_ID = cate. ID;} else {continue;} product. PName = row. getCell (0 )! = Null? Row. GetCell (0). ToString (): null; product. PCName = row. GetCell (1 )! = Null? Row. GetCell (1). ToString (): null; if (row. GetCell (3 )! = Null) {product. Price = Double. Parse (row. GetCell (3). ToString ();} product. Description = row. GetCell (4 )! = Null? Row. getCell (4 ). toString (): null; _ unitOfWork. shop_ProductRepository (). insert (product);} _ unitOfWork. save () ;}catch {return false;} return true ;}

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.