背景: 实现导出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. element-ui <el-input> +<el-tree>使用

    <template> <!-- 需求:通过点击<el-input> 将<el-tree>树型结构打开,选中<el-tree>某个值显示在<e ...

  2. Aircrack-ng破解WPA/WPA2加密WiFi教程(Kali)

    一.说明 以前学Kali,很多人都笑赞“WiFi破解神器”.我很烦,一是我不会破解二是我觉得他们也不会破解三是我隐约觉得所谓的WiFi破解不是什么技术性的操作. 后来基础知识充分了然后弄了个无线网卡, ...

  3. commons-lang3工具类学习(一)

    一.ArchUtils java运行环境的系统信息工具类 getArch();// 获取电脑处理器体系结构 32 bit.64 bit.unknown    getType();// 返回处理器类型 ...

  4. vuex-Action(异步)

    Action 类似于 mutation,不同在于: Action 提交的是 mutation,而不是直接变更状态. Action 可以包含任意异步操作. const store = new Vuex. ...

  5. python_day4

    昨日回顾:     1. 整型         python2  有长整型        python3  没有长整型     2.布尔值        转换     3.字符串详解        下 ...

  6. python非技术性问题整理

    针对软件安装包,安装时出现下类问题, 解决方法时, 以管理员身份运行命令行, 可以看到,包 正常安装. 在使用bs4,分析html或者xml文档时, 代码无法识别lxml 指令, 可能是python ...

  7. python自学第9天,装饰器

    装饰器:本质是函数(装饰其它函数) 就是为其它函数添加附加功能 原则:1.不能修改被装饰函数的源代码 2.不能修改被装饰的函数的调用方式 实现装饰器知识储备: 1.函数即变量 2.高阶函数:a.把一个 ...

  8. servlet编程操作

    所谓servlet指:服务器处理来自Web浏览器或其他客户端的HTTP请求的服务器程序.客户端向服务器发送Http请求,经Tomcat封装处理转给Servlet容器,Servlet容器在把请求或回应交 ...

  9. Post Order traverse binary tree using non-recursive way

    Process analysis Stack = 5,  Push 3, Stack = 5, 3.    Pre = 5 Current = 3, Pre = 5, Push 2 to the st ...

  10. 小妖精的完美游戏教室——人工智能,A*算法,引言

    今天也要直播魔法,求科学的! 欢迎来到小妖精Balous的完美游戏教室! 经过前两周的学习,相信米娜桑已经对状态机有所了解了呢~虽然状态机能够实现几乎所有的人工智能,但是,在实践中,你们有没有发现,自 ...