背景: 实现导出Excel功能.

技术: ASP.NET  , 采用`Aspose.Cells`第三方组件, C# 实现通用部分.

根据前台Ext Grid完成导入Excel中文列与实际存储列的对应关系. 组织完 Workbook 组织, 保存到Server临时目录, 返回地址下载, 每次都为新故文件名 采用了 随机数:

//_reportName :Excel名称
//_reportName: 报表名称
//_headerStruct: 包含数据库列与Excel中文列的对应关系. (此处取Ext表头)  public string ExportServerExcelFile(Aspose.Cells.Workbook w, string fileName)
        {
            if (!Directory.Exists(Server.MapPath("~/ExportFile/")))
                Directory.CreateDirectory(Server.MapPath("~/ExportFile/"));             w.Save(Server.MapPath("~/ExportFile/") + fileName);             return "http://" + Request.Url.Host + ":" + Request.Url.Port + "/ExportFile/" + fileName;
        } public string ExportExcelAll(string queryP, string _reportName, string _headerStruct)
        {
            DataTable dt = ....; //取查到库中数据
            string jsonData = Ext.Net.JSON.Serialize(dt);             Workbook w =  this.CreateWorkbook(jsonData, _reportName, _headerStruct);
            string fileName = _reportName.Split('(')[0] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";             return this.ExportServerExcelFile(w, fileName);
        } public Workbook CreateWorkbook(string jsonData, string _reportName, string _headerStruct)
        {
            var w = new Workbook();             Worksheet ws = (Worksheet)w.Worksheets[0];
            if (!string.IsNullOrEmpty(_headerStruct))
                SerHeader1(JSON.Deserialize<dynamic[]>(_headerStruct), ws);
            RangeHeader(ws);
            //设置标题
            ws.Cells[0, 0].PutValue(_reportName);
            Range titleRange = ws.Cells.CreateRange(0, 0, 1, lastColIndex);             #region ===样式
            var style = new Style { HorizontalAlignment = TextAlignmentType.Center, Font = { Size = 25, IsBold = true } };
            style.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
            style.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
            var styleFlag = new StyleFlag
            {
                HorizontalAlignment = true,
                VerticalAlignment = true,
                Font = true,
                FontSize = true,
                FontBold = true,
                Borders = true
            };
            titleRange.ApplyStyle(style, styleFlag);
            titleRange.RowHeight = 26;
            titleRange.Merge();             var cellStyle1 = new Style();
            cellStyle1.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
            cellStyle1.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
            cellStyle1.IsTextWrapped = true;             var cellStyleNumber = new Style();
            cellStyleNumber.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
            cellStyleNumber.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
            cellStyleNumber.Number = 2;
            #endregion             //列集合
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength = int.MaxValue;
            List<grid> _Test = serializer.Deserialize<List<grid>>(_headerStruct);             var companies = JSON.Deserialize<Dictionary<string, string>[]>(jsonData);             for (int i = 0; i < companies.Length; i++)
            {
                int tmpColIndex = 0;
                foreach (var item in companies[i])
                {
                    if (headerNames.IndexOf(item.Key) > -1)
                    {
                        var list = _Test.Where(p => p.DataIndex == item.Key).ToList();         //获取列名称
                        var cColumn = list[0];                         //初始样式
                        ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].SetStyle(cellStyle1, true);                         if (cColumn.DataType == "float" || cColumn.DataType == "decimal") //1. 数字类型
                        {
                            if (IsDecimal(item.Value))
                            {
                                ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].PutValue(ToDouble(item.Value));//金额保留2位数
                                //ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].SetStyle(cellStyleNumber);
                            }
                        }
                        else if (cColumn.DataType == "date") //2. 日期类型
                        {
                            ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].PutValue(
                                (string.IsNullOrWhiteSpace(item.Value) ? "" : Convert.ToDateTime(item.Value).ToString("yyyy-MM-dd hh:mm:ss"))
                                );
                        }
                        else //3. 字符串和集合类型auto
                        {
                            ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].PutValue(item.Value);
                        }                         //★获得要隐藏的列
                        if (cColumn.Hiden == true)//列需要隐藏: 字典类型
                        {
                            var index = headerNames.IndexOf(item.Key);//列索引
                            ws.Cells.HideColumn(index);
                        }
                    }
                    tmpColIndex++;
                }
            }             return w;
        }
        
        private void RangeHeader(Worksheet ws)
        {
            for (int row = 1; row <= lastLevel; row++)
            {
                for (int col = 0; col < lastColIndex; col++)
                {
                    var style = new Style
                    {
                        HorizontalAlignment = TextAlignmentType.Center,
                        VerticalAlignment = TextAlignmentType.Center
                    };
                    style.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
                    style.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
                    var styleFlag = new StyleFlag
                    {
                        HorizontalAlignment = true,
                        VerticalAlignment = true,
                        Font = true,
                        FontSize = true,
                        FontBold = true,
                        Borders = true
                    };                     ws.Cells[row, col].SetStyle(style);
                    if (ws.Cells[row, col].Value != null)
                    {
                        RangeCell(ws, row, col);
                    }
                }
            }
            foreach (Range item in rc.Where(m => m != null))
            {
                var style = new Style
                {
                    HorizontalAlignment = TextAlignmentType.Center,
                    VerticalAlignment = TextAlignmentType.Center
                };
                style.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
                style.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
                var styleFlag = new StyleFlag
                {
                    HorizontalAlignment = true,
                    VerticalAlignment = true,
                    Font = true,
                    FontSize = true,
                    FontBold = true,
                    Borders = true
                };                 item.ApplyStyle(style, styleFlag);
                try
                {
                    item.Merge();
                }
                catch (Exception)
                {
                }
            }
        }
        
         /// <summary>
        /// grid表头
        /// </summary>
        [Serializable]
        public class grid
        {
            public string Text { get; set; }
            public string DataIndex { get; set; }
            public string Width { get; set; }
            public List<grid> Cols { get; set; }
            public bool Hiden { get; set; }
            public string xtype { get; set; }
            public string DataType { get; set; }//列类型
        }

其中, 传入

_headerStruct

参数格式截图所示, 包括grid 类用于反序列化, 类似于, 关键用到了Text, DataType, DataIndex 关键, 特殊处理了Ext的多表头, 例如Cols 非末级就忽略了(函数

RangeHeader的作用

):

导出Excel实现 (ASP.NET C# 代码部分)的更多相关文章

  1. vue项目中导出Excel文件功能的前端代码实现

    在项目中遇到了两种不同情况, 1.get请求导出文件,实现起来相对简单 // 导出数据 exportData() { window.location.href = `/oes-content-mana ...

  2. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

  3. [转]Java中导入、导出Excel

    原文地址:http://blog.csdn.net/jerehedu/article/details/45195359 一.介绍 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样 ...

  4. easyui datagrid导出excel

    [第十四篇]easyui datagrid导出excel   <a class="btn btn-app" onclick="exportExcel()" ...

  5. Java中导入、导出Excel

    原文:Java中导入.导出Excel 一.介绍 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已 ...

  6. Java中使用poi导入、导出Excel

    一.介绍 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实际 ...

  7. Npoi导出excel整理(附源码)

    前些日子做了一个简单的winform程序,需要导出的功能,刚开始省事直接使用微软的组件,但是导出之后发现效率极其低下,绝对像web那样使用npoi组件,因此简单的进行了整理,包括直接根据DataTab ...

  8. 【转载】Java导入导出excel

    转自:https://blog.csdn.net/jerehedu/article/details/45195359 目前,比较常用的实现Java导入.导出Excel的技术有两种Jakarta POI ...

  9. Java中导入导出Excel -- POI技术

    一.介绍: 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实 ...

随机推荐

  1. jvm内存快照dump文件太大,怎么分析

    1.场景 通常,使用eclipse的mat图形化工具打开dump的时候都会内存溢出. 对于比较小的dump,eclipse可以打开,但一旦dump文件太大,eclipse就有点束手无策. 这时候怎么办 ...

  2. 算法-最通俗易懂的KMP算法详解

    有些算法,适合从它产生的动机,如何设计与解决问题这样正向地去介绍.但KMP算法真的不适合这样去学.最好的办法是先搞清楚它所用的数据结构是什么,再搞清楚怎么用,最后为什么的问题就会有恍然大悟的感觉.我试 ...

  3. python安装scrapy

    Scrapy基于事件驱动网络框架 Twisted 编写,Twisted是一个异步非阻塞框架. 安装 scrapy 要先安装 Twisted,不然无法安装成功,链接: Python Extension ...

  4. angular js中ng-model时间格式化

    直接上带代码,事实上此时不用ng-model,直接用value即可 <div class="form-group m-b-sm"> <label class=&q ...

  5. angular2升级到angular4历程

    Angular 4 在昨天(2017-03-24)正式发布了,我的系列教程也得更新一下.步骤略繁琐,不用 cli 的项目反倒更简单一些,但是 cli 平时给我们的便利还是很多的,升级最多半年一次而已. ...

  6. LSTM学习—Long Short Term Memory networks

    原文链接:https://colah.github.io/posts/2015-08-Understanding-LSTMs/ Understanding LSTM Networks Recurren ...

  7. Spring Boot的事务管理注解@EnableTransactionManagement的使用

    @EnableTransactionManagement:负责开启springboot 的事物支持,等同于xml配置文件中的 <tx:annotation-driven /> 然后在访问数 ...

  8. How to create your iOS team provisioning profile ?

    From Apple Developer: https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppS ...

  9. 关于使用JPA中@Query注解传递表名/视图名参数的问题

    因碰到需要动态查询不同视图的结果,自己尝试使用@Query注解中传递视图名称参数: @Query("select * from ?1") List<Object> ge ...

  10. Python全栈之路----数据类型—字典

    字典:可变,一种key-value的数据类型 info = { 'stu1101' : 'TengLan Wu' , 'stu1102' : 'LongZe Luola' , 'stu1103' : ...