C#EXCEL 导入导出

本贴最后更新于 1249 天前,其中的信息可能已经时异事殊

导入

<a href="javascript:void(0)" data-toggle="topjui-menubutton" data-options="event:'import'" onclick="imp()">导入外部数据</a>
//js
function imp() {
        var file = $("#filed").val();
        var year = document.getElementById("year").value;
        var month = document.getElementById("month").value;
        if (file == null || file.length == 0) {
            alert("请先选择上传文件!");
            return false;
        }
        $('#file-form').ajaxSubmit({
            url: "../../controller/CrmCon.ashx?action=importAreaSimulatedProfit&year=" + year + "&month=" + month + "",
            type: "post",
            datatype:'text',
            success: function (data) {
                //返回根据需求可省略
            }
        });
    }

后台代码

 HttpPostedFile filePost = context.Request.Files[0];
 DataTable myDataTable=SaveExcelFile(filePost);
 public static DataTable SaveExcelFile(HttpPostedFile file)
        {
            try
            {
                var fileName = file.FileName.Insert(file.FileName.LastIndexOf('.'), "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                string fileExtName = fileName.Substring(fileName.LastIndexOf(".") + 1);
                var filePath = Path.Combine(HttpContext.Current.Server.MapPath("../upload"), fileName);
                string directoryName = Path.GetDirectoryName(filePath);
                //创建目录
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName); 
                }
                if (File.Exists(HttpContext.Current.Server.MapPath("../upload/" + fileName + "")))
                {
                    File.Delete(HttpContext.Current.Server.MapPath("../upload/" + fileName + ""));
                }
                file.SaveAs(filePath);
                //HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES   
                string connstr2003 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + HttpContext.Current.Server.MapPath("../upload/"+fileName+"") + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                string connstr2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + HttpContext.Current.Server.MapPath("../upload/"+fileName+"") + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
                OleDbConnection conn;
                OleDbDataAdapter myCommand;
                string sql = "select * from [Sheet1$]";
                if (fileExtName == "xls")
                {
                    conn = new OleDbConnection(connstr2003);
                    myCommand = new OleDbDataAdapter(sql, connstr2003);
                }
                else
                {
                    conn = new OleDbConnection(connstr2007);
                    myCommand = new OleDbDataAdapter(sql, connstr2007);
                }
                conn.Open();
                DataTable myDatatable = new DataTable();
                myCommand.Fill(myDatatable);
                conn.Close();
                if (File.Exists(HttpContext.Current.Server.MapPath("../upload/"+fileName+"")))
                {
                    File.Delete(HttpContext.Current.Server.MapPath("../upload/"+fileName+""));
                }
                return myDatatable;
            }
            catch
            {
                return null;
            }
        }

导出

<a href="javascript:void(0)" data-toggle="topjui-menubutton" data-options="event:'export'" onclick="exp()">导出EXCEL</a>
//js
function exp() {
        var year = document.getElementById("year").value;
        var month = document.getElementById("month").value;
        window.open("../../controller/CrmCon.ashx?action=ExportQueryAreaSimulatedProfit&year=" + year + "&month=" + month + "");
    }

后台代码

public void 导出方法(){
string fileName = "xxxxx表_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                string[] colListHead = new string[]
                {
               "EXCEL列名","XXXX", "XXX"
                };
                string[] colList = new string[]
                {
               "与之对应的查询出的数据源列名","XXXX", "XXX"
                };
                System.Data.DataTable dt = Connect.CrmAop.QueryAreaSimulatedProfit(year, month);

                string rpt_name = "sheet1";
                HSSFWorkbook hSSFWorkbook = new HSSFWorkbook();
                System.Collections.Generic.List<HSSFCellStyle> list = new System.Collections.Generic.List<HSSFCellStyle>();
                int num = 0;
                HSSFSheet hssfBase = GetHssfBase(hSSFWorkbook, list, rpt_name+num.ToString() );
                HSSFRow hSSFRow = (HSSFRow)hssfBase.CreateRow(0);
                int num2 = 0;
                int num3 = 0;
                hSSFRow = (HSSFRow)hssfBase.CreateRow(num2);
                for (int i = 0; i < colListHead.Length; i++)
                {
                    string text = colListHead[i];
                    hSSFRow.CreateCell(num3).SetCellValue(text);
                    hSSFRow.Cells[num3].CellStyle = list[0];
                    num3++;
                }
                foreach (System.Data.DataRow dataRow in dt.Rows)
                {
                    num2++;

                    hSSFRow = (HSSFRow)hssfBase.CreateRow(num2);
                    int num4 = 0;
                    for (int i = 0; i < colList.Length; i++)
                    {
                        string text = colList[i];
                        hSSFRow.CreateCell(num4);
                        hSSFRow.Cells[num4].SetCellValue(dataRow[text].ToString());
                        hSSFRow.Cells[num4].CellStyle = list[1];
                        num4++;
                    }
                }
                HttpResponse httpResponse = HttpContext.Current.Response;
                httpResponse.Clear();
                httpResponse.Buffer = true;
                httpResponse.Charset = Encoding.UTF8.BodyName;
                httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
                httpResponse.ContentEncoding = Encoding.UTF8;
                httpResponse.ContentType = "application/vnd.ms-excel;";
                hSSFWorkbook.Write(httpResponse.OutputStream);
                httpResponse.End();
}
 //导出Sheet
        private static HSSFSheet GetHssfBase(HSSFWorkbook hssfworkbook, List<HSSFCellStyle> styleList, string rpt_name)
        {
            HSSFCellStyle hSSFCellStyle = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
            HSSFFont hSSFFont = (HSSFFont)hssfworkbook.CreateFont();
            hSSFCellStyle.SetFont(hSSFFont);
            hSSFCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            hSSFCellStyle.VerticalAlignment = VerticalAlignment.Center;
            hSSFFont.FontHeightInPoints = 10;
            hSSFFont.FontName = "Arial";
            hSSFFont.Boldweight = 700;
            hSSFCellStyle.FillForegroundColor = 22;
            hSSFCellStyle.FillPattern = FillPattern.SolidForeground;
            hSSFCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            hSSFCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            hSSFCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            hSSFCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleList.Add(hSSFCellStyle);
            hSSFCellStyle = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
            hSSFFont = (HSSFFont)hssfworkbook.CreateFont();
            hSSFCellStyle.SetFont(hSSFFont);
            hSSFCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
            hSSFCellStyle.VerticalAlignment = VerticalAlignment.Center;
            hSSFFont.FontHeightInPoints = 9;
            hSSFFont.FontName = "Arial";
            hSSFFont.Boldweight = 400;
            hSSFCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            hSSFCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            hSSFCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            hSSFCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleList.Add(hSSFCellStyle);
            HSSFSheet hSSFSheet = (HSSFSheet)hssfworkbook.CreateSheet(rpt_name);
            hSSFSheet.DefaultColumnWidth = 14;
            return hSSFSheet;
        }

  • C#
    28 引用 • 34 回帖 • 5 关注
  • Excel
    30 引用 • 28 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...

推荐标签 标签

  • 深度学习

    深度学习(Deep Learning)是机器学习的分支,是一种试图使用包含复杂结构或由多重非线性变换构成的多个处理层对数据进行高层抽象的算法。

    40 引用 • 40 回帖 • 1 关注
  • ActiveMQ

    ActiveMQ 是 Apache 旗下的一款开源消息总线系统,它完整实现了 JMS 规范,是一个企业级的消息中间件。

    19 引用 • 13 回帖 • 626 关注
  • Sillot

    Sillot (汐洛)孵化自思源笔记,致力于服务智慧新彖乄,具有彖乄驱动、极致优雅、开发者友好的特点
    Github 地址:https://github.com/Hi-Windom/Sillot

    15 引用 • 6 回帖 • 28 关注
  • 互联网

    互联网(Internet),又称网际网络,或音译因特网、英特网。互联网始于 1969 年美国的阿帕网,是网络与网络之间所串连成的庞大网络,这些网络以一组通用的协议相连,形成逻辑上的单一巨大国际网络。

    96 引用 • 330 回帖
  • IBM

    IBM(国际商业机器公司)或万国商业机器公司,简称 IBM(International Business Machines Corporation),总公司在纽约州阿蒙克市。1911 年托马斯·沃森创立于美国,是全球最大的信息技术和业务解决方案公司,拥有全球雇员 30 多万人,业务遍及 160 多个国家和地区。

    16 引用 • 53 回帖 • 123 关注
  • Unity

    Unity 是由 Unity Technologies 开发的一个让开发者可以轻松创建诸如 2D、3D 多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

    25 引用 • 7 回帖 • 247 关注
  • Spark

    Spark 是 UC Berkeley AMP lab 所开源的类 Hadoop MapReduce 的通用并行框架。Spark 拥有 Hadoop MapReduce 所具有的优点;但不同于 MapReduce 的是 Job 中间输出结果可以保存在内存中,从而不再需要读写 HDFS,因此 Spark 能更好地适用于数据挖掘与机器学习等需要迭代的 MapReduce 的算法。

    74 引用 • 46 回帖 • 548 关注
  • 阿里云

    阿里云是阿里巴巴集团旗下公司,是全球领先的云计算及人工智能科技公司。提供云服务器、云数据库、云安全等云计算服务,以及大数据、人工智能服务、精准定制基于场景的行业解决方案。

    89 引用 • 345 回帖
  • 支付宝

    支付宝是全球领先的独立第三方支付平台,致力于为广大用户提供安全快速的电子支付/网上支付/安全支付/手机支付体验,及转账收款/水电煤缴费/信用卡还款/AA 收款等生活服务应用。

    29 引用 • 347 回帖
  • 职场

    找到自己的位置,萌新烦恼少。

    126 引用 • 1699 回帖
  • 强迫症

    强迫症(OCD)属于焦虑障碍的一种类型,是一组以强迫思维和强迫行为为主要临床表现的神经精神疾病,其特点为有意识的强迫和反强迫并存,一些毫无意义、甚至违背自己意愿的想法或冲动反反复复侵入患者的日常生活。

    15 引用 • 161 回帖 • 5 关注
  • Gitea

    Gitea 是一个开源社区驱动的轻量级代码托管解决方案,后端采用 Go 编写,采用 MIT 许可证。

    4 引用 • 16 回帖
  • Windows

    Microsoft Windows 是美国微软公司研发的一套操作系统,它问世于 1985 年,起初仅仅是 Microsoft-DOS 模拟环境,后续的系统版本由于微软不断的更新升级,不但易用,也慢慢的成为家家户户人们最喜爱的操作系统。

    215 引用 • 462 回帖
  • 服务器

    服务器,也称伺服器,是提供计算服务的设备。由于服务器需要响应服务请求,并进行处理,因此一般来说服务器应具备承担服务并且保障服务的能力。

    124 引用 • 580 回帖
  • Scala

    Scala 是一门多范式的编程语言,集成面向对象编程和函数式编程的各种特性。

    13 引用 • 11 回帖 • 108 关注
  • 生活

    生活是指人类生存过程中的各项活动的总和,范畴较广,一般指为幸福的意义而存在。生活实际上是对人生的一种诠释。生活包括人类在社会中与自己息息相关的日常活动和心理影射。

    228 引用 • 1450 回帖 • 1 关注
  • OpenResty

    OpenResty 是一个基于 NGINX 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。

    17 引用 • 39 关注
  • Sym

    Sym 是一款用 Java 实现的现代化社区(论坛/BBS/社交网络/博客)系统平台。

    下一代的社区系统,为未来而构建

    523 引用 • 4581 回帖 • 690 关注
  • Jenkins

    Jenkins 是一套开源的持续集成工具。它提供了非常丰富的插件,让构建、部署、自动化集成项目变得简单易用。

    51 引用 • 37 回帖
  • SMTP

    SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。SMTP 协议属于 TCP/IP 协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。

    4 引用 • 18 回帖 • 589 关注
  • SQLServer

    SQL Server 是由 [微软] 开发和推广的关系数据库管理系统(DBMS),它最初是由 微软、Sybase 和 Ashton-Tate 三家公司共同开发的,并于 1988 年推出了第一个 OS/2 版本。

    19 引用 • 31 回帖 • 1 关注
  • Oracle

    Oracle(甲骨文)公司,全称甲骨文股份有限公司(甲骨文软件系统有限公司),是全球最大的企业级软件公司,总部位于美国加利福尼亚州的红木滩。1989 年正式进入中国市场。2013 年,甲骨文已超越 IBM,成为继 Microsoft 后全球第二大软件公司。

    103 引用 • 126 回帖 • 447 关注
  • 安装

    你若安好,便是晴天。

    128 引用 • 1184 回帖
  • Mobi.css

    Mobi.css is a lightweight, flexible CSS framework that focus on mobile.

    1 引用 • 6 回帖 • 697 关注
  • 运维

    互联网运维工作,以服务为中心,以稳定、安全、高效为三个基本点,确保公司的互联网业务能够 7×24 小时为用户提供高质量的服务。

    148 引用 • 257 回帖
  • Telegram

    Telegram 是一个非盈利性、基于云端的即时消息服务。它提供了支持各大操作系统平台的开源的客户端,也提供了很多强大的 APIs 给开发者创建自己的客户端和机器人。

    5 引用 • 35 回帖 • 1 关注
  • OpenShift

    红帽提供的 PaaS 云,支持多种编程语言,为开发人员提供了更为灵活的框架、存储选择。

    14 引用 • 20 回帖 • 604 关注