C# WebApi导出Excel 直接返回一个远程Excel地址 链接访问下载

        /// <summary>

        /// 导出方案列表

        /// </summary>

        [HttpGet, HttpPost]

        public Object ExportProgramme(ExportProgrammeReq req)

        {

            var virtualPath = “/UploadFile/Export/”;

            var path = HttpContext.Current.Server.MapPath(virtualPath);

            if (!Directory.Exists(path))

            {

                Directory.CreateDirectory(path);

            }

            var name = “快报名方案列表.xlsx”; //Excel名字

            path += name;

            var models = ProgrammerService.ExportProgramme(req);

            var viewModels = new ExportProgrammeViewModel().GetViewModels(models);

            var dataTable = ExcelHelp.ListToDataTable(viewModels);

            //datatable转成字节流            

            var bytes = ExcelHelp.GetExcelForXLSX(dataTable, GetColumnName);

            var stream = new MemoryStream(bytes);

            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))

            {

                byte[] data = stream.ToArray();

                fs.Write(data, 0, data.Length);

                fs.Flush();

                data = null;

            }

            stream.Close();

            stream.Dispose();

            

            return PictureHelper.ConcatPicUrl(virtualPath + name); ;

        }

        /// <summary>
        /// 根据字段名称获取对应的列名
        /// </summary>
        public static string GetColumnName(string columnName)
        {
            var convertColumnName = string.Empty;
            switch (columnName)
            {
                case “ProgrammeName”:
                    convertColumnName = “方案名称”;
                    break;
                case “TypeName”:
                    convertColumnName = “方案类型”;
                    break;
                case “PassDate”:
                    convertColumnName = “过期时间”;
                    break;
                case “Status”:
                    convertColumnName = “状态”;
                    break;
                case “State”:
                    convertColumnName = “是否启用”;
                    break;
                case “ViewCount”:
                    convertColumnName = “浏览次数”;
                    break;
                case “EnrollCount”:
                    convertColumnName = “报名人数”;
                    break;
                case “ToOtherCount”:
                    convertColumnName = “转赠次数”;
                    break;
            }
            return convertColumnName;
        }

 public static DataTable ListToDataTable<T>(List<T> entitys)
        {
            //生成DataTable的structure
            //生产代码中,应将生成的DataTable结构Cache起来,此处略
            var dt = new DataTable();

            //检查实体集合不能为空 todo:
            if (entitys == null || entitys.Count < 1)
            {
                return dt;
            }
            //取出第一个实体的所有Propertie
            var entityType = entitys[0].GetType();
            var entityProperties = entityType.GetProperties();

            for (var i = 0; i < entityProperties.Length; i++)
            {
                //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                dt.Columns.Add(entityProperties[i].Name);
            }
            //将所有entity添加到DataTable中
            foreach (object entity in entitys)
            {
                //检查所有的的实体都为同一类型
                if (entity.GetType() != entityType)
                {
                    throw new Exception(“要转换的集合元素类型不一致”);
                }
                var entityValues = new object[entityProperties.Length];
                for (var i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;

        }

        //获取列名委托方法
        public delegate string GetColumnName(string columnName);

public static byte[] GetExcelForXLSX(DataTable dt, GetColumnName getColumnName)
        {
            var xssfworkbook = new XSSFWorkbook();
            var sheet = xssfworkbook.CreateSheet(“Sheet”);
            //表头
            var row = sheet.CreateRow(0);

            for (var i = 0; i < dt.Columns.Count; i++)
            {
                var cell = row.CreateCell(i);
                //列名称,数据库中字段
                var columnName = dt.Columns[i].ColumnName;
                var convertColumnName = getColumnName(columnName);
                cell.SetCellValue(convertColumnName);
            }

            //数据
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                var row1 = sheet.CreateRow(i + 1);
                for (var j = 0; j < dt.Columns.Count; j++)
                {
                    var cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }
            //转为字节数组
            var stream = new MemoryStream();
            xssfworkbook.Write(stream);
            var buf = stream.ToArray();
            return buf;

        }

    原文作者:Todd-Li
    原文地址: https://blog.csdn.net/qq_35309370/article/details/80421878
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞