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 对应的订单状态枚举;}  
    }
  • 相关阅读:
    sqlalchemy
    nginx配置文件,做多个项目代理
    pyspider
    Mysql原理+ 多实例 +表损坏
    Spring 学习-AOP
    java 基础 --- 动态代理和静态代理
    Spring 学习-IoC
    [转]字符编码笔记:ASCII,Unicode 和 UTF-8
    JVM(五) class类文件的结构
    数据结构(四)--- 红黑树(RedBlock-Tree)
  • 原文地址:https://www.cnblogs.com/betterlife/p/7210040.html
Copyright © 2011-2022 走看看