asp.net导出excel示例代码

asp.net导出excel示例代码
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// www.jbxue.com
           _unitOfWork.Shop_ProductRepository().Insert(product);
                }
                _unitOfWork.Save();
            }
            catch
            {
                return false;
            }
            return true;
        }
posted on 2014-02-26 06:45 snowfly123 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/linuxnotes/p/3568221.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/408083.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何方便的让你的集合引发改变事件

在我们开发自定义控件的过程中,我们常常会给控件添加集合属性。比如定制Grid控件就会有Column集合。当集合属性发生变化时&#xff0c;比如添加新元素&#xff0c;删除新元素&#xff0c;我们要通知控件去重绘以反映新的变化。我们可以创建一个集合类&#xff0c;在类里添加一个…

[汇编语言]-第八章 div指令,伪指令dd,dup

1- div除法指令 (1) 除数: 有8位和16位两种,在一个寄存器或内存单元中. (2) 被除数: 默认放在AX和DX或AX中 除数为8位, 被除数为16位, 默认在AX中存放. 除数为16位, 被除数为32位, 在DX或AX中存放. AX存放低16位,DX存放高16位. (3) 结果 除数为8位, 则AL存储除法操作的商, AH存…

System.Data.SQLite(SQLite ADO.NET 2.0的提供程序,已经包含Sqlite引擎)

今天在研究其他的技术的时候&#xff0c;重新查看了一下Sqlite在.NET下的最新实现。结果发现这样一个好东西。下面把其首页的说明翻译如下&#xff1a;System.Data.SQLite 是一个原始SQLite的加强版. 它将是一个原版的sqlite3.dll完全替代品 (你甚至就可以把它重命名为sqlite3…

lambda表达式浅析【C++学习笔记】

lambda表达式浅析【C学习笔记】 基本用法: auto f [/*捕获列表*/](/*参数*/)->int /*后置返回值类型*/{/** 函数体*/};捕获列表: [] : 不捕获任何变量 [变量名] : 表示值捕获,不可修改 [] :按值捕获所有变量,不可修改 [&] : 按引用捕获可以修改 [this] : 在类中捕…

【Cocos2d-x for WP8 学习整理】(2)Cocos2d-Html5 游戏 《Fruit Attack》 WP8移植版 开源...

【Cocos2d-x for WP8 学习整理】&#xff08;2&#xff09;Cocos2d-Html5 游戏 《Fruit Attack》 WP8移植版 开源 原文:【Cocos2d-x for WP8 学习整理】&#xff08;2&#xff09;Cocos2d-Html5 游戏 《Fruit Attack》 WP8移植版 开源这一阵花了些时间&#xff0c;把 cocos2d-h…

react学习(64)--简单的锚点封装

render() {const {anchors [], //锚点数组&#xff0c;link-节点id&#xff0c;title-显示文字content, //左侧内容} this.props;return (<div style{{ display: flex }}><div style{{ flex: 9, overflow: hidden }}>{content || this.props.children}</div&g…

碰撞,处理碰撞,发射 Learn Unreal Engine (with C++)

本文使用打砖块游戏举例 碰撞,处理碰撞 碰撞就相当于一个Actor进入另一个Box中,用这个思路就可以处理碰撞了 OnComponentBeginOverlap 当某些内容开始重叠此组件时调用的事件&#xff0c;例如玩家进入触发器。 **委托 事件 **1 AddDynamic( UserObject, FuncName ) 用于…

在Solaris系统下如何更改网络配置?

修改/etc/hostname.qfe0 >附檔名,依照網卡種類不同,有不同的名稱再依照上述檔案內容,再去查看/etc/hosts中相對應的名稱,並修改IP转载于:https://blog.51cto.com/youjianhello/12461

react学习(65)--ant design加载中

import { Spin } from antd;ReactDOM.render(<Spin />, mountNode);

传送,条件加速 Learn Unreal Engine (with C++)

本文以吃豆人游戏为例UE4项目: 自制UE4 小游戏 (gitee.com) 传送 pawn进入box触发OnActorBeginOverlap获取目标位置,下一帧将pawn坐标更改为目标位置 首先需要重叠函数与开始重叠事件绑定 OnActorBeginOverlap.AddDynamic(this, &ATeleporterActor::OnOverlapBegin);头文件…

ADSL路由器的设置

关于将ADSL 路由器的设置&#xff0c;其实ADSL 路由器的设置并不是很难&#xff0c;以TL-R4XX系列路由器为例&#xff0c;简要说明ADSL 路由器的设置&#xff0c;首先MODEM、路由器、电脑连结起来&#xff0c;网络必需畅通&#xff0c;ADSL 路由器地址出厂默认IP地址&#xff1…

web.xml中 Log4jConfigListener配置

使用Log4jConfigListener有如如下好处&#xff1a; 1. 动态的改变记录级别和策略&#xff0c;不需要重启Web应用&#xff0c;如《Effective Enterprise Java》所说。 2. 把log文件定在 /WEB-INF/logs/ 而不需要写绝对路径。 因为 系统把web目录的路径压入一个叫webapp.ro…

获取摄像机,摄像机切换Learn Unreal Engine (with C++)

摄像机应该是使用最普遍的组件了 获取摄像机,摄像机切换 新建C类(以CameraActor为父类) 将摄像机在地图中放置 头文件声明 virtual void BeginPlay() override;UPROPERTY(EditAnywhere, BlueprintReadWrite)UBoxComponent* OverlapVolume; // 盒体组件,用于检测人物碰撞UPR…

BIOS详情设置续一

高级芯片组特征Configure DRAM Timing&#xff08;设置内存时钟&#xff09;  此设置决定DRAM 的时钟设置是否由读取内存模组上的SPD&#xff08;Serial PresenceDetect&#xff09;EPROM 内容决定。设置为By SPD允许内存时钟根据SPD的设置由BIOS自动决定配置&#xff1b;设置…

android报错及解决1--Bitmap加载时,报bitmap size exceeds VM budget

报错描述&#xff1a; 用Bitmap加载图片资源时&#xff0c;报错java.lang.OutOfMemoryError: bitmap size exceeds VM budget 原因分析&#xff1a; android系统限制&#xff0c;只给图片分配8M内存&#xff0c;超过就蹦。图片虽然几十K&#xff0c;可能是压缩格式&#xff0c;…

react学习(67)--git 屏蔽文件不被追踪

bash # 屏蔽文件不被 git 追踪 git update-index --assume-unchanged [FILE]# 如果要还原的话&#xff0c;使用命令&#xff1a; git update-index --no-assume-unchanged [FILE]

华三1822-24路由交换机配置例子

华三1822-24路由交换机配置例子#sysname Quidway#super password level 3 cipher xxxxxxx#FTP server enable#web set-package force flash:/http.zip#radius scheme system#domain system #local-user dgbg_adminpassword cipher xxxxxxxservice-type telnet terminal#dhcp se…