c# npoi下载导出excel(奇思妙想通过字段属性和反射处理)

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Weixiao.Common
{
    [AttributeUsage(AttributeTargets.All)]
    public class NpoiAttribute : Attribute
    {
        /// <summary>
        /// 文件名称
        /// </summary>
        public string FileName { get; set; }
        /// <summary>
        /// 文件路径
        /// </summary>
        public string FilePath { get; set; }
        /// <summary>
        /// 文件后缀(.xls/.xlsx)
        /// </summary>
        public string FileSuffix { get; set; }
        /// <summary>
        /// 工作本
        /// </summary>
        public string SheetName { get; set; }
        public NpoiAttribute(string fileName, string filePath, string sheetName, string fileSuffix)
        {
            FileName = fileName;
            FilePath = filePath;
            SheetName = sheetName;
            FileSuffix = fileSuffix;
        }
        public NpoiAttribute(string fileName, string filePath, string sheetName)
        {
            FileName = fileName;
            FilePath = filePath;
            SheetName = sheetName;
            FileSuffix = ".xlsx";
        }
        public NpoiAttribute()
        {
        }
    }
    [AttributeUsage(AttributeTargets.All)]
    public class NpoiRowAttribute : Attribute
    {
        /// <summary>
        /// 表头
        /// </summary>
        public string TabTitle { get; set; }
        public NpoiRowAttribute(string tabTitle)
        {
            TabTitle = tabTitle;
        }
        public NpoiRowAttribute()
        {
        }
    }
    public class NpoiUtil
    {
        /// <summary>
        /// excel导出(配合NpoiAttribute)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList">数据源</param>
        /// <param name="filePath">文件路径</param>
        /// <param name="fileName">文件名称</param>
        public static string CreateByAttribute<T>(List<T> dataList,string rootPath, string filePath = null, string fileName = null)
        {
            var tp = typeof(T);
            NpoiAttribute npoiAttr = new NpoiAttribute();
            foreach (System.Attribute a in tp.GetCustomAttributes(true))
            {
                if (a is NpoiAttribute)
                {
                    npoiAttr = (NpoiAttribute)a;
                }
            }
            IWorkbook workbook;
            if (npoiAttr.FileSuffix == ".xls") workbook = new HSSFWorkbook();
            else workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet(npoiAttr.SheetName);
            var titleCellIndex = 0;//表头列数
            var rowIndex = 0;//行数
            var titleRow = sheet.CreateRow(rowIndex);
            rowIndex++;
            // 冻结第一行
            sheet.CreateFreezePane(0, 1, 0, 1);
            var titleDic = new Dictionary<string, int>();
            foreach (var pro in tp.GetProperties())
            {
                if (pro.PropertyType.Namespace != "System")
                {//非基础变量暂不支持
                    continue;
                }
                //var x = pro.PropertyType.Name.ToLower();
                //var intoTypeList = new string[] { "int32", "int64", "int", "bool", "decimal", "string", "nullable`1" };
                //if (intoTypeList.FirstOrDefault(d=>d.ToLower()==pro.PropertyType.Name.ToLower()) is null)
                //{
                //    continue;
                //}
                titleDic.Add(pro.Name, titleCellIndex);
                var tabTitle = pro.Name;
                foreach (Attribute fa in pro.GetCustomAttributes(true))
                {
                    if (fa is NpoiRowAttribute)
                    {
                        var faa = (NpoiRowAttribute)fa;
                        tabTitle = faa.TabTitle;
                        break;
                    }
                }
                titleRow.CreateCell(titleCellIndex).SetCellValue(tabTitle);
                titleCellIndex++;
            }
            foreach (var item in dataList)
            {
                var dataRow = sheet.CreateRow(rowIndex);
                rowIndex++;
                foreach (var p in tp.GetProperties())
                {
                    var td = titleDic.FirstOrDefault(t => t.Key == p.Name);
                    if (string.IsNullOrEmpty(td.Key))
                    {
                        continue;
                    }
                    dataRow.CreateCell(td.Value).SetCellValue(p.GetValue((T)item) == null ? "" : p.GetValue((T)item).ToString());
                }
            }
            npoiAttr.FilePath = string.IsNullOrEmpty(filePath) ? npoiAttr.FilePath : filePath;
            npoiAttr.FileName = string.IsNullOrEmpty(fileName) ? npoiAttr.FileName : fileName;
            //if (!Directory.Exists(npoiAttr.FilePath)) Directory.CreateDirectory(npoiAttr.FilePath);
            //todo:抽空检查下,为啥没有在wwwroot下
            if (!Directory.Exists(Path.Combine(rootPath,npoiAttr.FilePath))) {
                Directory.CreateDirectory(Path.Combine(rootPath, npoiAttr.FilePath));
            }
           // var path1 = Directory.GetCurrentDirectory();
            var path = Path.Combine(npoiAttr.FilePath ?? "upload", $"{npoiAttr.FileName ?? "数据"}{npoiAttr.FileSuffix ?? ".xlsx"}");
            FileStream sw = File.Create(Path.Combine(rootPath,path));
            workbook.Write(sw);
            sw.Close();
            return path;
        }
        public static void Create(WoorkBook work)
        {
            IWorkbook workbook;
            if (work.Suffix.ToLower() == ".xls") workbook = new HSSFWorkbook();
            else workbook = new XSSFWorkbook();
            foreach (var sheet in work.Sheets)
            {
                var _sheet = workbook.CreateSheet(sheet.Name);
                var rowIndex = 0;
                if (sheet.Title != null)
                {//表示有标题
                    var row = _sheet.CreateRow(rowIndex);
                    for (int i = 0; i < sheet.Title.Count; i++)
                    {
                        row.CreateCell(i).SetCellValue(sheet.Title[i]);
                    }
                    rowIndex++;
                }
                for (int i = rowIndex; i < sheet.Value.Count; i++)
                {//内容
                    var rowValue = _sheet.CreateRow(i);
                    for (int j = 0; j < sheet.Value[i].Count; j++)
                    {
                        rowValue.CreateCell(j).SetCellValue(sheet.Value[i][j].ToString());
                    }

                }
            }

        }
    }
    public class WoorkBook
    {
        /// <summary>
        /// 文件名称(别写后缀了)
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 文件路径
        /// </summary>
        public string Path { get; set; }
        /// <summary>
        /// 文件后缀".xls"或者“.xlsx”
        /// </summary>
        public string Suffix { get; set; }
        public List<Sheet> Sheets { get; set; }
    }
    public class Sheet
    {
        /// <summary>
        /// 工作单元名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 标题
        /// </summary>
        public List<string> Title { get; set; }
        /// <summary>
        /// 值
        /// </summary>
        public List<List<object>> Value { get; set; }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值