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();
            foreach (DataColumn column in dts.Columns)
                headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);
            int rowIndex = ;
            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, , 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();
                if (
                    !(firstRow.GetCell().ToString() == "名称" && firstRow.GetCell().ToString() == "简称" &&
                      firstRow.GetCell().ToString() == "分类" && firstRow.GetCell().ToString() == "参考价" &&
                      firstRow.GetCell().ToString() == "商品介绍"))
                {
                    return false;
                }                 //跳过类型不正确的品项
                for (int i = ; i < rowsCount; i++)
                {
                    IRow row = sheet1.GetRow(i);
                    Shop_Product product = new Shop_Product();
                    string category = row.GetCell() != null ? row.GetCell().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() != null ? row.GetCell().ToString() : null;
                    product.PCName = row.GetCell() != null ? row.GetCell().ToString() : null;
                    if (row.GetCell() != null)
                    {
                        product.Price = Double.Parse(row.GetCell().ToString());
                    }
                    product.Description = row.GetCell() != null ? row.GetCell().ToString() : null; // www.jbxue.com
           _unitOfWork.Shop_ProductRepository().Insert(product);
                }
                _unitOfWork.Save();
            }
            catch
            {
                return false;
            }
            return true;
        }

asp.net导出excel示例代码的更多相关文章

  1. asp.net导出excel-一行代码实现excel、xml、pdf、word、html、csv等7种格式文件导出功能而且美观-SNF快速开发平台

    分享: 腾讯微博  新浪微博   搜狐微博   网易微博  腾讯朋友  百度贴吧  豆瓣   QQ好友  人人网 作者:王春天  原文地址:http://www.cnblogs.com/spring_ ...

  2. [转] Asp.Net 导出 Excel 数据的9种方案

    湛刚 de BLOG 原文地址 Asp.Net 导出 Excel 数据的9种方案 简介 Excel 的强大之处在于它不仅仅只能打开Excel格式的文档,它还能打开CSV格式.Tab格式.website ...

  3. Asp.net导出Excel续章(自定义合并单元格,非Office组件)

    结合上次写的导出Excel方法,这次上头要求我将列头进行一下合并 以前的效果: 改进后的效果: 在上篇文章中写到了Excel的导出方法,这次为了避免在生产环境中使用Office组件,服务器各种权限配置 ...

  4. NPOI导出Excel示例

    摘要:使用开源程序NPOI导出Excel示例.NPOI首页地址:http://npoi.codeplex.com/,NPOI示例博客:http://tonyqus.sinaapp.com/. 示例编写 ...

  5. asp.net 导出excel文件

    之前做过winfrom程序的导出excel文件的功能,感觉非常简单.现在试着做asp.net中导出excel的功能,之前用的是Microsoft.Office.Interop.Excel这个对象来实现 ...

  6. asp.net导出excel并弹出保存提示框

    asp.net导出excel并弹出保存提示框 2013-07-12 | 阅:1  转:78   |  分享  腾讯空间 人人网 开心网 新浪微博 腾讯微博 搜狐空间 推荐给朋友 举报          ...

  7. ASP.NET导出EXCEL类

    最新ASP.NET导出EXCEL类 说明:可以导出ASP.NET页面和DATAGRID(WebControl)数据,可以导出表单头 using System;using System.Data;usi ...

  8. SpringBoot使用Easypoi导出excel示例

    SpringBoot使用Easypoi导出excel示例 https://blog.csdn.net/justry_deng/article/details/84842111

  9. asp.net webform/mvc导出Excel通用代码

    最近将自己在项目中经常用到的excel导出方法分析如下,如有不妥之处望他人指出,如果有更好的方法希望展示出来互相学习. //导出事件 protected void btnexcel_Click(obj ...

随机推荐

  1. java 的数据类型

    java 的数据类型有基本类型和引用类型 java的类的关系:有继承,有依赖,有关联,聚合,组成.

  2. ListView中使用type需要注意的东西

    在使用ListView时,如果使用了getItemViewType, 记得他的值一定要是从0开始计数的. 且要覆盖getViewTypeCount方法.并且让getViewTypeCount>g ...

  3. (转)如何检查系统是否支持Zend Optimizer

    原文地址:http://blog.chinaunix.net/uid-25266990-id-2978539.html Zend Optimizer 主要有两个功能: 1.可以加速 PHP 脚本的执行 ...

  4. 基于RBAC模型的通用企业权限管理系统

    1. 为什么我们需要基于RBAC模型的通用企业权限管理系统 管理信息系统是一个复杂的人机交互系统,其中每个具体环节都可能受到安全威胁.构建强健的权限管理系统,保证管理信息系统的安全性是十分重要的.权限 ...

  5. Shell | grep with n following lines

    'foo' sample.txt ➜ dex-method-counts git:(master) ./dex-method-counts ~/Downloads/n.apk | 'hui' hui: ...

  6. cocos2d 3.0自定义事件答疑解惑

    疑惑一:在事件分发中修改订阅者 ,对于这个的理解. 事件的分发是可以嵌套的,cocos2dx使用_inDispatch来保存当前嵌套的深度,当调用第一个dispatchEvent的时候,_inDisp ...

  7. 压缩上传并预览 flash

    最近研究一个功能:用as3写的上传图片并实现预览.觉得花了很多时间也学到很多知识,将自己的所得记录下来供大家分享. 首先是预览功能的实现,大家自然而然就想到了loader来加载图片并显示,由于项目没有 ...

  8. 分享一个MVC的多层架构,欢迎大家拍砖斧正

    如果你对项目管理.系统架构有兴趣,请加微信订阅号"softjg",加入这个PM.架构师的大家庭 多层架构是开发人员在开发过程当中面对复杂且易变的需求采取的一种以隔离控制为主的应对策 ...

  9. 第4章 awk编程

    1 awk编程模型       2 awk用法 调用awk有三种方法(与sed类似): 在Shell命令行输入命令调用awk,格式为: awk [-F 域分隔符] 'awk程序段' 输入文件 将awk ...

  10. Collection集合之六大接口(Collection、Set、List、Map、Iterator和Comparable)

    首先,我们先看一下Collection集合的基本结构: 1.Collection接口 Collection是最基本集合接口,它定义了一组允许重复的对象.Collection接口派生了两个子接口Set和 ...