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

 更新时间:2014年02月25日 15:24:33   作者:  
这篇文章主要介绍了asp.net导出excel的简单方法实例,需要的朋友可以参考下

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

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

复制代码 代码如下:

/// <summary>
        /// 导出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("/") + @"用户列表.xlsx";
            FileStream file = new FileStream(filepath, FileMode.Create);
            workbook.Write(file);
            ExcelHelper.DownLoad(@"/用户列表.xlsx");
            #region 不启用

            #endregion
            return SuccessMsg("AdminMemberMemberIndex");
        }
//这个是下载到桌面的方法,没实现自选路径
public static void DownLoad(string FileName)
 {
             FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(FileName));
             //以字符流的形式下载文件
             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";
               //通知浏览器下载文件而不是打开
            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>
        /// <param name="file"></param>
        /// <returns>true表示导入成功</returns>
        public bool Impoart(HttpPostedFileBase file)
        {
            try
            {
                //保存excel
                string path = HttpContext.Current.Server.MapPath("/");
                file.SaveAs(path + file.FileName);

                //读取

                FileStream sw = File.Open(path + file.FileName, FileMode.Open, FileAccess.Read);
                IWorkbook workbook = new XSSFWorkbook(sw);
                ISheet sheet1 = workbook.GetSheet("Sheet1");

                //最大行数
                int rowsCount = sheet1.PhysicalNumberOfRows;

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


                //跳过类型不正确的品项
                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;
        }

相关文章

  • 浅析MVP模式中V-P交互问题及案例分享

    浅析MVP模式中V-P交互问题及案例分享

    如果从层次关系来讲,MVP属于Presentation层的设计模式。对于一个UI模块来说,它的所有功能被分割为三个部分,分别通过Model、View和Presenter来承载。Model、View和Presenter相互协作,完成对最初数据的呈现和对用户操作的响应,它们具有各自的职责划分。
    2014-05-05
  • CentOS上运行ZKEACMS的详细过程

    CentOS上运行ZKEACMS的详细过程

    这篇文章主要为大家介绍了CentOS上运行ZKEACMS的详细过程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • HTML服务器控件和WEB服务器控件的区别和联系介绍

    HTML服务器控件和WEB服务器控件的区别和联系介绍

    学习asp.net的时候一会用Html服务器控件,一会用Web服务器控件,起初做起例子来也挺迷糊的,下面对这两个控件研究了一下做个笔记在此与大家分享下,感兴趣的朋友可以了解下
    2013-08-08
  • asp.net TextBox控件设置ReadOnly后,不能回传。

    asp.net TextBox控件设置ReadOnly后,不能回传。

    当把一个TextBox控件ReadOnly属性设置为True后,这个控件就不回传了。
    2009-05-05
  • .NET示波器控件的实例代码分析

    .NET示波器控件的实例代码分析

    本篇文章是对.NET示波器控件进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • .net获取本机公网IP地址示例

    .net获取本机公网IP地址示例

    本文主要介绍了.net获取本机公网IP地址的方法,使用了ip138的数据,大家参考使用吧
    2014-01-01
  • 使用ajax局部刷新gridview进行数据绑定示例

    使用ajax局部刷新gridview进行数据绑定示例

    很多用户都有这样需求,比如:点击按钮,刷新 GridView 中的数据,而不是这个页面刷新。使用简单的 XMLHttpRequest就可以直接实现
    2014-02-02
  • asp.net c#采集需要登录页面的实现原理及代码

    asp.net c#采集需要登录页面的实现原理及代码

    当我们采集页面的时候,如果被采集的网站需要登录才能采集,原理搞清楚了,就好办了,我们所要做的仅仅是在采集的时候(或者说HttpWebRequest提交数据的时候),将Cookie信息放入Http请求头里面就可以了,感兴趣的朋友可以了解下,或许对你有所帮助
    2013-02-02
  • 轻量级ORM框架Dapper应用之安装Dapper

    轻量级ORM框架Dapper应用之安装Dapper

    这篇文章介绍了轻量级ORM框架Dapper的安装方法,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-03-03
  • 浅谈ASP.NET中多层架构

    浅谈ASP.NET中多层架构

    Asp.net的多层架构主要是为了解决数据层,逻辑层,表示层等之间的关系。我的做法是这样的:首先建立一个DataCore的基类。基类里面封装了一些低层的数据库的基本操作,比如说数据库联接,调用存储过程等等。
    2015-06-06

最新评论