简单的excel导入导出示例分享

   2015-09-09 0
核心提示:这篇文章主要介绍了简单的excel导入导出示例分享,需要的朋友可以参考下

复制代码 代码如下:

/// <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;
        }

 
标签: excel 导入 导出
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • Perl操作Mysql数据库 perl操作excel
    一. 安装DBI模块步骤1:从TOOLS栏目中下载DBI.zip,下载完后用winzip解开到一个temp目录,共有三个文件:ReadmeDBI.ppdDBI.tar.gz步骤2: 在DOS窗口下,temp目录中运行下面的DOS命令:ppm install DBI.ppd 如果提示无效命令,可在perl/bin目录下运行 二. 安装DBD
    02-09
  • C#/VB.NET 获取Excel中图片所在的行、列坐标位置
    C#/VB.NET 获取Excel中图片所在的行、列坐标位
    本文以C#和vb.net代码示例展示如何来获取Excel工作表中图片的坐标位置。这里的坐标位置是指图片左上角顶点所在的单元格行和列位置,横坐标即顶点所在的第几列、纵坐标即顶点所在的第几行。下面是获取图片位置的详细方法及步骤。【程序环境】按照如下方法来引
    02-09
  • python 使用pandas,完成对excel的操作: 遍历
    excel有针对偏度的计算函数 skew(), 但是不清楚怎么使用excel进行遍历, 数据量很大。尝试使用python进行解决。第一次学习python,没想到了在克服安装各种包的难过之后,居然成功实现了。python3.3:#this is a test case# -*- coding: gbk -*-print("hello py
    02-09
  • Delphi操作Excel(2) ---Stringgrid导出到Excel
    最近编了一个小软件,需要将Stringgrid中的内容导出到Excel中。由于使用的是Delphi2010 + Office2010,中间有点小曲折,现把代码贴出来,供参考。代码procedure TFormMain.btn3Click(Sender: TObject);varExcelApp,workbook,sheet:Variant;begindlgSavedlg1.F
    02-09
  • csv,txt,excel文件之间的转换,perl脚本
    最近接触一些需要csv,txt,excel文件之间的转换,根据一些网上搜索加上自己的改动,实现自己想要的结果为主要目的,代码的出处已经找不到了,还请见谅,以下主要是针对csvexcel 和txtexcel写的perl脚本。主要用到的模块是: Text::CSVSpreadsheet::WriteExcel
    02-09
  • 使用Perl提取Excel中的IO_MUX perl处理excel内容
    使用Perl提取Excel中的IO_MUX perl处理excel内
    关键问题提取数据格式化输出循环嵌套数据结构构建坐标映射,逆向提取关键字描述在IC集成中,我们使用Excel表格规划设计的IC引脚功能映射需要转化到Verilog层次,这个过程耗时耗力,但其中有一些规律,可以通过Perl将其格式化提取出部分可用的信息,应用得当可
    02-09
  • MATLAB读写Excel文件中的数据
    读取:%读取filename文件中指定表的数据,存入dataRead矩阵中dataRead=xlsread('filename.xls',sheet); 写入:%将矩阵dataWrite中的数据写入filename表中,从C1单元格开始xlswrite('filename.xls',dataWrite','C1'); 作者:耑新新,发布于  博客园转载请
    02-09
  • R语言学习笔记之: 论如何正确把EXCEL文件喂给R
     博客总目录:http://www.cnblogs.com/weibaar/p/4507801.html  ----前言: 应用背景兼吐槽继续延续之前每个月至少一次更新博客,归纳总结学习心得好习惯。这次的主题是论R与excel的结合,又称 论如何正确把EXCEL文件喂给R处理 分为: 1、 xlsx包安装及注
    02-09
  • R语言使用过程中出现的问题--读取EXCEL文件
    方法一:按照R导论中的方法,使用RODBC包,library(RODBC)channel-odbcConnectExcel("file.xlsx")da2-sqlFetch(channel,"Sheet1")odbcClose(channel)结果:未能成功,原因是odbcConnectExcel is only usable with 32-bit Windows 即只能在32位的电脑中使用,6
    02-09
  • [译] Ruby如何访问Excel文件
    [译] Ruby如何访问Excel文件
     BY: MATT NEDRICH   翻译:佣工7001     本文中,我将会评判几种Ruby语言访问Excel文件的库。我将要讨论针对不同格式的Excel文件访问的现有的几个Ruby库。本文中更多地聚焦于读取Excel文件,但是也对与更改/写入Excel文件稍作了些讨论。如果你迫不及
    02-09
点击排行