zl程序教程

您现在的位置是:首页 >  工具

当前栏目

asp.net导出excel的简单方法实例

2023-06-13 09:15:18 时间

excel的操作,最常用的就是导出和导入,废话不多说上代码。

本例使用NPOI实现的,不喜勿喷哈。。。。

复制代码代码如下:


///<summary>
       ///导出Excel
       ///</summary>
       ///<paramname="stime"></param>
       ///<paramname="etime"></param>
       ///<returns></returns>
       publicActionResultExport(FormCollectionfrm)
       {
           DataTabledts=newDataTable();
           dts=_shopMemeber.ExportMemberData(frm);
           IWorkbookworkbook=newXSSFWorkbook();
           ISheetsheet=workbook.CreateSheet();
           IRowheaderRow=sheet.CreateRow(0);
           foreach(DataColumncolumnindts.Columns)
               headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);
           introwIndex=1;
           foreach(DataRowrowindts.Rows)
           {
               IRowdataRow=sheet.CreateRow(rowIndex);
               foreach(DataColumncolumnindts.Columns)
               {
                   dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
               }
               rowIndex++;
           }
           stringfilepath=Server.MapPath("/")+@"用户列表.xlsx";
           FileStreamfile=newFileStream(filepath,FileMode.Create);
           workbook.Write(file);
           ExcelHelper.DownLoad(@"/用户列表.xlsx");
           #region不启用

           #endregion
           returnSuccessMsg("AdminMemberMemberIndex");
       }
//这个是下载到桌面的方法,没实现自选路径
publicstaticvoidDownLoad(stringFileName)
 {
            FileInfofileInfo=newFileInfo(HttpContext.Current.Server.MapPath(FileName));
            //以字符流的形式下载文件
            FileStreamfs=newFileStream(HttpContext.Current.Server.MapPath(FileName),FileMode.Open);
           byte[]bytes=newbyte[(int)fs.Length];
             fs.Read(bytes,0,bytes.Length);
           fs.Close();
           HttpContext.Current.Response.ContentType="application/octet-stream";
              //通知浏览器下载文件而不是打开
           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();
       }

上面是导出,下面我介绍下导入。

复制代码代码如下:


///<summary>
       ///导入数据
       ///</summary>
       ///<paramname="file"></param>
       ///<returns>true表示导入成功</returns>
       publicboolImpoart(HttpPostedFileBasefile)
       {
           try
           {
               //保存excel
               stringpath=HttpContext.Current.Server.MapPath("/");
               file.SaveAs(path+file.FileName);

               //读取

               FileStreamsw=File.Open(path+file.FileName,FileMode.Open,FileAccess.Read);
               IWorkbookworkbook=newXSSFWorkbook(sw);
               ISheetsheet1=workbook.GetSheet("Sheet1");

               //最大行数
               introwsCount=sheet1.PhysicalNumberOfRows;

               //判断首行是否符合规范 也就是Excel中的列名
               IRowfirstRow=sheet1.GetRow(0);
               if(
                   !(firstRow.GetCell(0).ToString()=="名称"&&firstRow.GetCell(1).ToString()=="简称"&&
                     firstRow.GetCell(2).ToString()=="分类"&&firstRow.GetCell(3).ToString()=="参考价"&&
                     firstRow.GetCell(4).ToString()=="商品介绍"))
               {
                   returnfalse;
               }


               //跳过类型不正确的品项
               for(inti=1;i<rowsCount;i++)
               {
                   IRowrow=sheet1.GetRow(i);
                   Shop_Productproduct=newShop_Product();

                   stringcategory=row.GetCell(2)!=null?row.GetCell(2).ToString():null;
                   if(!string.IsNullOrEmpty(category))
                   {
                       varcate=
                           _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
           {
               returnfalse;
           }

           returntrue;
       }