zoukankan      html  css  js  c++  java
  • NPOI+反射 实现快速导出

    只是觉得这样很方便 记录一下

    公司有封装的方法,不过是查出的Table类型,每次用的时候很都很烦,处理数据也不方便,最主要的是我也没耐心去看,反正在我看来很麻烦,用的时候很头疼。还是习惯通过Model List来处理数据,可以利用Model Class属性来处理数据格式等等

    
    
                var orders=GetOrders();//获取订单列表

    //Excel表头
    string
    [] headerTemp = { "订单号", "下单时间", "订单状态", "店铺名称", "商品名称"};
    //对应的Model Class属性
    string[] propertyNameTemp = { "OrderId", "OrderDate", "OrderStatusString", "StoreName", "ProductName"}; #region excel简单样式设置 HSSFWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1"); ICellStyle othercolstyle = hssfworkbook.CreateCellStyle(); IFont othercolfont = hssfworkbook.CreateFont(); othercolfont.FontName = "微软雅黑"; othercolfont.FontHeightInPoints = 12; othercolstyle.SetFont(othercolfont); othercolstyle.VerticalAlignment = VerticalAlignment.Center; othercolstyle.Alignment = HorizontalAlignment.Center; #endregion for (int i = 0; i <= orders.Count; i++) { IRow row = sheet1.CreateRow(i); row.Height = 22 * 16; for (int j = 0; j < headerTemp.Length; j++) { ICell cell = row.CreateCell(j); cell.CellStyle = othercolstyle; sheet1.SetColumnWidth(j, 12 * 256); if (i == 0) {
                  //第一行设置表头 cell.SetCellValue(headerTemp[j]); }
    else { Type temp = orders[i - 1].GetType(); PropertyInfo propertyInfo = temp.GetProperty(propertyNameTemp[j]); object pvalue = propertyInfo.GetValue(orders[i - 1], null); cell.SetCellValue(pvalue == null ? "" : pvalue.ToString()); } } } // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); hssfworkbook.Write(ms); ms.Seek(0, SeekOrigin.Begin); return File(ms, "application/vnd.ms-excel", string.Format("{0}.xls", DateTime.Now));

    //上面代码 return File为.net mvc中返回方式
    //ashx或aspx页面最后返回方式

    //写入流
    MemoryStream file = new MemoryStream();
    hssfworkbook.Write(file);

    
    

    if (file != null)
    {
    // 写入到客户端
    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpContext.Current.Server.UrlEncode("竞猜用户.xlsx")));
    Response.BinaryWrite(file.ToArray());
    }

     

    每次只需要设置excel表头和对应的Model属性就可以,反射那部分不用动。

    一般像订单状态查出来是int类型的枚举值,可以在Model里扩展枚举属性OrderStatusString

    public string OrderStatusString
    {
          get{return 对应的订单状态枚举;}  
    }
  • 相关阅读:
    【转载】时域信号的频谱、功率谱和功率谱密度计算
    【转载】Chaotic Time-Series Prediction
    【转载】Restarting an analysis in ANSYS
    Interpolation in MATLAB
    【转载】ANSYS 动力分析 (9)
    在oracle中 将一个以逗号隔开的String字符串转换成以单引号逗号隔开的集合
    在java中获取时间,单位毫秒。主要用于查看执行时间效率
    比较两个数组元素是否相等
    oracle 从一张表的数据复制到另一张表中 mapper.xml
    打印错误栈信息:可以捕获具体错误信息
  • 原文地址:https://www.cnblogs.com/betterlife/p/7210040.html
Copyright © 2011-2022 走看看