asp. net exports simple method instances of excel

  • 2020-11-26 18:45:50
  • OfStack

excel operations, the most commonly used is the export and import, not to mention the code.

This example is implemented using NPOI, don't spray if you like...


/// <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 column 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("/") + @" List of users .xlsx";
            FileStream file = new FileStream(filepath, FileMode.Create);
            workbook.Write(file);
            ExcelHelper.DownLoad(@"/ List of users .xlsx");
            #region  Is not enabled 
            #endregion
            return SuccessMsg("AdminMemberMemberIndex");
        }
// This is the way to download to the desktop, no optional path is implemented 
public static void DownLoad(string FileName)
 {
             FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(FileName));
             // Download the file as a stream of characters 
             FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(FileName), FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
              fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            HttpContext.Current.Response.ContentType = "application/octet-stream";
               // Notify the browser to download the file instead of opening it 
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileInfo.Name, System.Text.Encoding.UTF8));
          HttpContext.Current.Response.BinaryWrite(bytes);
           HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

Above is the export, and now I'm going to introduce the import.


/// <summary>
        ///  Import data 
        /// </summary>
        /// <param name="file"></param>
        /// <returns>true Indicates successful import </returns>
        public bool Impoart(HttpPostedFileBase file)
        {
            try
            {
                // save 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 sheet1 = workbook.GetSheet("Sheet1");
                // The largest number of lines 
                int rowsCount = sheet1.PhysicalNumberOfRows;
                // Determine if the first line conforms to the specification    That is Excel The column 
                IRow firstRow = sheet1.GetRow(0);
                if (
                    !(firstRow.GetCell(0).ToString() == " The name of the " && firstRow.GetCell(1).ToString() == " Referred to as" " &&
                      firstRow.GetCell(2).ToString() == " classification " && firstRow.GetCell(3).ToString() == " Reference price " &&
                      firstRow.GetCell(4).ToString() == " The introduction "))
                {
                    return false;
                }

                // Skip items of incorrect type 
                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;
                        }
                    }
                    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;
        }


Related articles: