首页 > 其他分享 >.Net Excel操作之NPOI(二)常用操作封装

.Net Excel操作之NPOI(二)常用操作封装

时间:2022-11-28 14:00:24浏览次数:37  
标签:cellStyle headStyle fields Excel NPOI Add new Net

一、Excel数据导出常用操作

1.指定表头和描述

2.指定数据库中读出的数据集合

二、ExcelExport封装

/// <summary>
/// Excel常用的表格导出逻辑封装
/// 单表写入
/// </summary>
public class ExcelExport
{
    /// <summary>
    /// 导出的Excel文件名称+路径
    /// </summary>
    public string FullName { get; set; }
    /// <summary>
    /// 导出的字段名称和描述
    /// </summary>
    public Dictionary<string, string> Fields { get; set; }

    private HSSFWorkbook _workbook = null;
    private ISheet _sheet = null;
    /// <summary>
    /// 创建实例,验证导出文件名
    /// </summary>
    /// <param name="FullName"></param>
    /// <param name="Fields"></param>
    public ExcelExport(string FullName, Dictionary<string, string> Fields)
    {
        this.FullName = FullName;
        this.Fields = Fields;
        Check();
        _workbook = new HSSFWorkbook();
        _sheet = _workbook.CreateSheet("Sheet1");
    }
    /// <summary>
    /// 验证Excel文件名
    /// </summary>
    private void Check()
    {
        try
        {
            FileInfo info = new FileInfo(this.FullName);
            string[] extentions = new string[] {
                ".xls",
                ".xlsx"
            };
            if (extentions.Any(q => q == info.Extension) == false)
                throw new Exception("excel文件的扩展名不正确,应该为xls或xlsx");
            if (info.Exists == false)
                info.Create().Close();
        }
        catch (Exception ex)
        {
            throw new Exception("创建Excel文件失败", ex);
        }
    }

    /// <summary>
    /// 执行导出操作
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    public void Export<T>(List<T> list)
    {
        //写入表格头
        WriteHead();
        //写入数据
        ICellStyle cellStyle = _workbook.CreateCellStyle();
        cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");//为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
        cellStyle.BorderBottom = BorderStyle.Thin;
        cellStyle.BorderLeft = BorderStyle.Thin;
        cellStyle.BorderRight = BorderStyle.Thin;
        cellStyle.BorderTop = BorderStyle.Thin;
        cellStyle.VerticalAlignment = VerticalAlignment.Center;
        cellStyle.Alignment = HorizontalAlignment.Center;

        IFont cellFont = _workbook.CreateFont();
        cellFont.Boldweight = (short)FontBoldWeight.Normal;
        cellStyle.SetFont(cellFont);

        //建立行内容,从1开始
        int rowInex = 1;

        foreach (var rowItem in list)
        {
            //创建行
            IRow row = _sheet.CreateRow(rowInex);
            row.HeightInPoints = 25;

            int cellIndex = 0;
            foreach (var cellItem in this.Fields)
            {
                //创建单元格
                ICell cell = row.CreateCell(cellIndex);
                //反射获取属性的值
                PropertyInfo info = rowItem.GetType().GetProperty(cellItem.Key);
                if (info == null)
                {
                    cell.SetCellValue($"'{cellItem.Key}'属性不存在");
                }
                else
                {
                    object value = info.GetValue(rowItem);
                    if (value != null)
                        cell.SetCellValue(value.ToString());
                }
                cell.CellStyle = cellStyle;
                cellIndex++;
            }
            //进入下一次循环
            rowInex++;
        }

        //自适应列宽度
        for (int i = 0; i < this.Fields.Count; i++)
        {
            _sheet.AutoSizeColumn(i);
        }

        //导出到文件
        WriteFile();
    }
    /// <summary>
    /// 写入表头
    /// </summary>
    private void WriteHead()
    {
        //设置表头样式
        ICellStyle headStyle = _workbook.CreateCellStyle();
        headStyle.BorderBottom = BorderStyle.Thin;
        headStyle.BorderLeft = BorderStyle.Thin;
        headStyle.BorderRight = BorderStyle.Thin;
        headStyle.BorderRight = BorderStyle.Thin;
        headStyle.Alignment = HorizontalAlignment.Center;
        headStyle.FillForegroundColor = HSSFColor.Blue.Index;
        headStyle.VerticalAlignment = VerticalAlignment.Center;

        IFont headFont = _workbook.CreateFont();
        headFont.Boldweight = (short)FontBoldWeight.Bold;
        headStyle.SetFont(headFont);

        IRow row = _sheet.CreateRow(0);
        row.HeightInPoints = 30;

        int index = 0;
        foreach (var item in this.Fields)
        {
            ICell cell = row.CreateCell(index);
            cell.SetCellValue(item.Value);
            cell.CellStyle = headStyle;
            index++;
        }
    }
    /// <summary>
    /// 创建文件到磁盘
    /// </summary>
    private void WriteFile()
    {
        using (FileStream fs = new FileStream(this.FullName, FileMode.OpenOrCreate))
        {
            _workbook.Write(fs);
            fs.Flush();
            fs.Close();
        }
    }
}

三、使用示例

1.匿名对象集合导出

Dictionary<string, string> fields = new Dictionary<string, string>();
fields.Add("ID", "主键");
fields.Add("Name", "姓名");
fields.Add("Age", "年龄");
fields.Add("Birthday", "生日");
ExcelExport _export = new ExcelExport(LocalPathHelper.GetCurrentData() + "/export1.xls", fields);


List<object> list = new List<object>() {
    new {ID=1,Name="张三丰",Age=20,Birthday=DateTime.Now },
    new {ID=2,Name="王芳",Age=30,Birthday=DateTime.Now }
};
_export.Export(list);

2.List集合导出

TestOne _Context = new DBA.TestOne();
List<Member_Info> list = _Context.Member_Info.ToList();
Dictionary<string, string> fields = new Dictionary<string, string>();
fields.Add("MemberID", "主键");
fields.Add("code", "账号");
fields.Add("RealName", "姓名");
fields.Add("IsActive", "是否激活");
fields.Add("commission", "奖金余额");

//使用
ExcelExport _export = new ExcelExport(LocalPathHelper.GetCurrentData() + "\\export2.xls", fields);
//_export.Export(list);
_export.Export<Member_Info>(list);

 

标签:cellStyle,headStyle,fields,Excel,NPOI,Add,new,Net
From: https://www.cnblogs.com/funiyi816/p/16932010.html

相关文章

  • pytest + excel参数驱动
    背景最近紧急支持一个接口测试,打算把接口的参数都放到execl中维护,且一个接口需要请求两次。思路1.execl中构造参数接口需要请求两次或者多次,比较两次后台返回的结果,那......
  • Centos 7.9 部署Kubernetes集群 (基于containerd 运行时)
    前言当Kubernetes社区宣布1.20版本之后会逐步弃用dockershim,当时也有很多自媒体在宣传Kubernetes弃用Docker。其实,我觉得这是一种误导,也许仅仅是为了蹭热度。dockersh......
  • 此功能需要连接到internet。是否允许office连接到internet
     问题在OneNote中进行一些操作的时候提示:此功能需要连接到internet。是否允许office连接到internet  解决方法1.快捷键Win+R,打开"运行"对话框 2.输......
  • .NET 6 实现滑动验证码(二)、基本数据
    上一节,介绍了滑动验证码的基本情况,也创建了一个.NET6的工程。本节内容是创建一些基础类。目录CaptchaData.csCaptchaValidateData.csImageCaptchaInfo.csResource.csSl......
  • .Net 6 配置日志
    前言  .Net6与之前的配置有点不一样了记录下日志配置方式。当前日志以Serilog为例,.Net6的日志由内置的Logger获取,然后可以交给Serilog|NLog等框架处理,框架通过他......
  • [Office] 如何阻止 Word 和 Excel 打开新文档的同时弹出已最小化的文档
    Word按Win+R,输入regedit打开注册表编辑器,转到HKEY_CLASSES_ROOT\Word.Document.12\shell\Open\command,右侧有个默认项,双击修改值为"C:\ProgramFiles(x86)\Micros......
  • java将List<Map<String,Object>>导出Excel
    遇到了个需要导出Excel的需求,经过百度查到方法在此记录一下:publicstaticvoidcreateExcel(List<Map<String,Object>>mapList,Stringfilename,Stringtitle,Http......
  • SQL serve 安装报错,缺少.net3.5组件
    今天安装sqlserver2014,遇到服务器没有安装.net3.5,的报错,上网搜索一番,找到一篇博文(非常详细,拷贝进来以备后用)操作之后略有区别,为表尊重原文地址https://www.cnblogs.co......
  • Use Kubekey to quickly deploy Kubernetes
    IntroductionStartwritingdeploymentprofilesStartthedeploymentDeploymentcomplete,checkpodstatusIntroductionKubekeyisanopensourceKubernetes......
  • .NET 生成可跨平台得图片二维码
    下载包nugetSkiaSharp创建帮助类VerificationCodeHelper点击查看代码publicclassVerifyCodeHelper{///<summary>///获取图像数字验证码......