zoukankan      html  css  js  c++  java
  • webapi list model 导出excel

          public IHttpActionResult GetCFXOListExcel()

          {

            DataTable dt = C_CardFX.GetCardFXOrderList(DataHelper.connStr, parameters, out PageCount, out recordCount, out totalInCome, out totalPrice);



           var list = dt.ToEntity<T_DTO_CardFX.CardFXOrderList>(); list.ForEach(o => { o.statusName = getStatus(o.status); }); #region 生成excel var browser = String.Empty; if (HttpContext.Current.Request.UserAgent != null) { browser = HttpContext.Current.Request.UserAgent.ToUpper(); } HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK); #region 内容 // Excel列的名称 Dictionary<string, string> cellheader = new Dictionary<string, string> { { "gameName", "游戏" }, { "orderNo", "订单号" }, { "title", "信息" }, { "number", "数量" }, { "price", "价格" }, { "inCome", "提成" }, { "statusName", "状态" }, { "tradeTime", "时间" }, }; var info = EntityListToExcel2003(cellheader, list, "用户信息"); #endregion string fileName = "分销" + DateTime.Now.ToString("yyyyMMddHHmmssfff")+ ".xlsx"; Stream stream = new MemoryStream(info); httpResponseMessage.Content = new StreamContent(stream); httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = browser.Contains("FIREFOX") ? Path.GetFileName(fileName) : HttpUtility.UrlEncode(Path.GetFileName(fileName)) }; return ResponseMessage(httpResponseMessage); #endregion
          }

    同样需要用到npoi  2.0;

            /// <summary>
            /// 实体类集合导出到Excle2003
            /// </summary>
            /// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } };</param>
            /// <param name="enList">数据源</param>
            /// <param name="sheetName">工作表名称</param>
            /// <returns>byte[]</returns>
            [NonAction]
            public byte[] EntityListToExcel2003(Dictionary<string, string> cellHeard, IList enList, string sheetName)
            {
                try
                {
                    // 2.解析单元格头部,设置单元头的中文名称
                    HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿
                    ISheet sheet = workbook.CreateSheet(sheetName); // 工作表
                    IRow row = sheet.CreateRow(0);
                    List<string> keys = cellHeard.Keys.ToList();
                    for (int i = 0; i < keys.Count; i++)
                    {
                        row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值
                    }
                    // 3.List对象的值赋值到Excel的单元格里
                    int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头)
                    foreach (var en in enList)
                    {
                        IRow rowTmp = sheet.CreateRow(rowIndex);
                        for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值
                        {
                            string cellValue = ""; // 单元格的值
                            object properotyValue = null; // 属性的值
                            System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息
    
                            // 3.1 若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName
                            if (keys[i].IndexOf(".") >= 0)
                            {
                                // 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理)
                                string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                                string subClassName = properotyArray[0]; // '.'前面的为子类的名称
                                string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称
                                System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型
                                if (subClassInfo != null)
                                {
                                    // 3.1.2 获取子类的实例
                                    var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null);
                                    // 3.1.3 根据属性名称获取子类里的属性类型
                                    properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName);
                                    if (properotyInfo != null)
                                    {
                                        properotyValue = properotyInfo.GetValue(subClassEn, null); // 获取子类属性的值
                                    }
                                }
                            }
                            else
                            {
                                // 3.2 若不是子类的属性,直接根据属性名称获取对象对应的属性
                                properotyInfo = en.GetType().GetProperty(keys[i]);
                                if (properotyInfo != null)
                                {
                                    properotyValue = properotyInfo.GetValue(en, null);
                                }
                            }
                            // 3.3 属性值经过转换赋值给单元格值
                            if (properotyValue != null)
                            {
                                cellValue = properotyValue.ToString();
                                // 3.3.1 对时间初始值赋值为空
                                if (cellValue.Trim() == "0001/1/1 0:00:00" || cellValue.Trim() == "0001/1/1 23:59:59")
                                {
                                    cellValue = string.Empty;
                                }
                            }
    
                            // 3.4 填充到Excel的单元格里
                            rowTmp.CreateCell(i).SetCellValue(cellValue);
                        }
                        rowIndex++;
                    }
                    MemoryStream ms = new MemoryStream();
                    workbook.Write(ms);
                    byte[] data = ms.ToArray();
                    return data;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
  • 相关阅读:
    Mysql练习#1-建表
    Mysql学习笔记#7-范式
    Git学习笔记#9-标签
    Git学习笔记#8-操作冲突
    Git学习笔记#7-分支操作
    Git学习笔记#6-远程仓库(GitHub)
    Git学习笔记#5-文件删除
    Git学习笔记#4-版本回退
    Git学习笔记#3-修改文件与撤销
    免费分享老男孩全栈9期视频,共126天
  • 原文地址:https://www.cnblogs.com/zzgxl/p/10190182.html
Copyright © 2011-2022 走看看