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;
 
                    _unitOfWork.Shop_ProductRepository().Insert(product);
                }
 
                _unitOfWork.Save();
            }
            catch
            {
                return false;
            }
 
            return true;
        }
 

时间: 2024-08-04 07:20:06

asp.net导出excel的简单方法的相关文章

php不使用插件导出excel的简单方法

 这篇文章主要介绍了php不使用插件导出excel的简单方法,首先获取需要导出的数据的数组,数组的格式在下面.之后就是定义文件名称和需要导出的excel的样式,最后就是循环数组,输出数据了   代码如下: $filename=date("Y年m月d日")."数据信息统计结果.xls";     //文件名 $ua = $_SERVER["HTTP_USER_AGENT"];  //中文文件名不乱码 if (preg_match("/MS

php不使用插件导出excel的简单方法_php实例

复制代码 代码如下: $filename=date("Y年m月d日")."数据信息统计结果.xls";     //文件名$ua = $_SERVER["HTTP_USER_AGENT"];   //中文文件名不乱码if (preg_match("/MSIE/", $ua)) {      $filename=urlencode($filename);} else if (preg_match("/Firefox/&

【译】Asp.Net 导出 Excel 数据的9种方案

原文 http://www.cnblogs.com/garydot/archive/2012/06/04/excel-export.html 简介 Excel 的强大之处在于它不仅仅只能打开Excel格式的文档,它还能打开CSV格式.Tab格式.website table 等多钟格式的文档.它具备自动识别行号,字符,格式化数字等功能,例如:如果你在Excel 单元格中输入数字 "123456789012" 会自动转化为"1.23457E+11". 背景介绍 正因为E

asp.net datagrid 导出excel二种方法

asp教程.net datagrid 导出excel二种方法 文章为你提供二款datagrid 导出excel的代码一款是利用vb.net 导出excel一种是利用c# datagrid 导出excel的实例代码. */ //c#:   private void exporttoexcel()         {             savefiledialog savefiledialog = new savefiledialog();             savefiledialog

从SQL Server中导入/导出 Excel 的基本方法

excel|server 从SQL Server中导入/导出 Excel 的基本方法 /*===================  导入/导出 Excel 的基本方法 ===================*/ 从Excel文件中,导入数据到SQL数据库中,很简单,直接用下面的语句: /*===================================================================*/--如果接受数据导入的表已经存在insert into 表 select

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

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

ASP.net 导出excel,无法kill进程。(在线等待...)

问题描述 遇到一个问题,在win7下开发的,asp.net导出excel(2007),在正常情况下,能够顺利导出,且进程正常结束,但是当创建excel进程之后,出现异常了,启动publicstaticvoidKillExcelProcess(){System.Diagnostics.Process[]excelProcesses=System.Diagnostics.Process.GetProcessesByName("EXCEL");DateTimestartTime=newDat

asp.net导出Excel类库代码分享

 这篇文章主要介绍了asp.net导出Excel类库代码,有需要的朋友可以参考一下    代码如下: using System; using System.Collections.Generic; using System.Reflection; using System.Web; using Excel = Microsoft.Office.Interop.Excel;   /// <summary> ///ExcelClass 的摘要说明 /// </summary> publ

asp.net-关于ASP.NET导出Excel的问题

问题描述 关于ASP.NET导出Excel的问题 我们这边有一个ASP.NET导出Excel的功能,但是在导出的时候,有些情况下是正常的,有些情况就直接导出了整个页面,请问各位大神大概是什么原因导致的?代码如下: //Excel2007的连接字符串 string strCon = ""Provider=Microsoft.ACE.OLEDB.12.0;Data Source="" + filePath + "";Extended Properti