c# 基于NPOI实现Excel读写

1.在NuGet安装NPOI对应的依赖包

NuGet包管理

2.自定义工具类(修改命名空间即可)

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Reflection;

namespace Model.Helper
{
    public class ExcelHelper
    {

        /// <summary>
        /// 写入excel文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">文件名称(也可以是文件路径)</param>
        /// <param name="dataList">数据列表(数据库查询结果)</param>
        /// <param name="propetryDictinory">实体类属性对应的中文名称(用于在报表上展示)</param>
        /// <param name="version">excel版本(低于2007默认为0,2007及以上为1)</param>
        /// <returns></returns>
        public static bool writeExcel<T>(string fileName,List<T> dataList,
            Dictionary<string,string> propetryDictinory,int version=0)
        {
            try
            {
                //【1】.创建工作簿 2007之前用HSSFWorkbook 2007之后用XSSFWorkbook  
                IWorkbook? workBook = null;
                // 根据版本号创建不同版本的excel
                workBook = version == 0 ? new HSSFWorkbook() : new XSSFWorkbook();
                // 每个工作簿有多个sheet,创建一个sheet
                ISheet sheet = workBook.CreateSheet("sheet1");
                // 在工作表中创建标题行
                IRow titleRow = sheet.CreateRow(0);
                // 放入属性对应的中文名称
                Type type = typeof(T);
                PropertyInfo[] propertyInfos = type.GetProperties();
                for (int i = 0; i < propetryDictinory.Count; i++)
                {
                    ICell cell = titleRow.CreateCell(i);
                    cell.SetCellValue(propetryDictinory[propertyInfos[i].Name]);
                }
                // 创建数据行
                for (int i = 0; i < dataList.Count; i++)
                {
                    IRow row = sheet.CreateRow(i + 1);

                    for (int j = 0; j < propetryDictinory.Count; j++)
                    {
                        ICell cell = row.CreateCell(j);
                        if (cell != null)
                        {
                            object? temp = propertyInfos[j].GetValue(dataList[i]);
                            string? data = temp == null ? "" : temp.ToString();
                            cell.SetCellValue(data);
                        }
                    }
                }
                using (FileStream fs = File.OpenWrite(fileName))
                {
                    workBook.Write(fs);
                    return true;
                }

            }
            catch (Exception e) {
                e.ToString();
                return false;
            }
        }

        /// <summary>
        /// 读取Excel数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">文件名称(也可以是文件路径</param>
        /// <param name="t">excel数据对应的实体类型,使用new的方式传入匿名实例化的对象即可</param>
        /// <param name="version">excel版本(低于2007默认为0,2007及以上为1)</param>
        /// <returns></returns>
        public static List<T> readExcel<T>(string fileName,T t, int version=0)
        {
            List<T> dataList = new List<T>();
            try
            {
                using (FileStream fs= File.OpenRead(fileName))
                {
                    //【1】.创建工作簿 2007之前用HSSFWorkbook 2007之后用6XSSFWorkbook  
                    IWorkbook? workBook = null;
                    // 根据版本号创建不同版本的excel
                    workBook = version == 0 ? new HSSFWorkbook(fs) : new XSSFWorkbook(fs);
                    // 获取工作表
                    ISheet sheet = workBook.GetSheetAt(0);
                    // 初始化反射
                    Type type = typeof(T);

                    if (type == null) {
                        throw new Exception("数据对应的类不存在!");
                    }

                    // 获取excel中的数据 忽略标题行
                    for (int i = 1; i < sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        object? obj = Activator.CreateInstance(type);
                        PropertyInfo[] propertyInfos = type.GetProperties();
                        for (int j = 0; j < row.LastCellNum; j++)
                        {
                            ICell cell = row.GetCell(j);
                            propertyInfos[j].SetValue(obj, Convert.ChangeType(cell.ToString(), propertyInfos[j].PropertyType));
                        }
                        dataList.Add((T)obj);
                    }
                }
            }
            catch (Exception e)
            {
                _ = e.StackTrace;
                return null;
            }


            return dataList;
        }
        
    }
}

调用示例:“Report.xls”:文件名,reportDatas:数据列表List集合,propetryDic:属性名对应的中文名字典

ExcelHelper.writeExcel("Report.xls", reportDatas, propetryDic)

ps:要求net版本7.3以上,若低于7.3需要修改部分代码

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace DAL.util
{
    public class ExcelHelper
    {

        /// <summary>
        /// 写入excel文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">文件名称(也可以是文件路径)</param>
        /// <param name="dataList">数据列表(数据库查询结果)</param>
        /// <param name="propetryDictinory">实体类属性对应的中文名称(用于在报表上展示)</param>
        /// <param name="version">excel版本(低于2007默认为0,2007及以上为1)</param>
        /// <returns></returns>
        public static bool writeExcel<T>(string fileName, List<T> dataList,
            Dictionary<string, string> propetryDictinory, int version = 0)
        {
            try
            {
                //【1】.创建工作簿 2007之前用HSSFWorkbook 2007之后用XSSFWorkbook  
                IWorkbook workBook = null;
                // 根据版本号创建不同版本的excel
                if (version == 0)
                {
                    workBook = new HSSFWorkbook();
                }
                else
                {
                    workBook = new XSSFWorkbook();
                }
                // 每个工作簿有多个sheet,创建一个sheet
                ISheet sheet = workBook.CreateSheet("sheet1");
                // 在工作表中创建标题行
                IRow titleRow = sheet.CreateRow(0);
                // 放入属性对应的中文名称
                Type type = typeof(T);
                PropertyInfo[] propertyInfos = type.GetProperties();
                for (int i = 0; i < propetryDictinory.Count; i++)
                {
                    ICell cell = titleRow.CreateCell(i);
                    cell.SetCellValue(propetryDictinory[propertyInfos[i].Name]);
                }
                // 创建数据行
                for (int i = 0; i < dataList.Count; i++)
                {
                    IRow row = sheet.CreateRow(i + 1);

                    for (int j = 0; j < propetryDictinory.Count; j++)
                    {
                        ICell cell = row.CreateCell(j);
                        if (cell != null)
                        {
                            object temp = propertyInfos[j].GetValue(dataList[i]);
                            string data = temp == null ? "" : temp.ToString();
                            cell.SetCellValue(data);
                        }
                    }
                }
                using (FileStream fs = File.OpenWrite(fileName))
                {
                    workBook.Write(fs);
                    return true;
                }

            }
            catch (Exception e)
            {
                e.ToString();
                return false;
            }
        }

        /// <summary>
        /// 读取Excel数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">文件名称(也可以是文件路径</param>
        /// <param name="t">excel数据对应的实体类型,使用new的方式传入匿名实例化的对象即可</param>
        /// <param name="version">excel版本(低于2007默认为0,2007及以上为1)</param>
        /// <returns></returns>
        public static List<T> readExcel<T>(string fileName, T t, int version = 0)
        {
            List<T> dataList = new List<T>();
            try
            {
                using (FileStream fs = File.OpenRead(fileName))
                {
                    //【1】.创建工作簿 2007之前用HSSFWorkbook 2007之后用6XSSFWorkbook  
                    IWorkbook workBook = null;
                    // 根据版本号创建不同版本的excel
                    if (version == 0)
                    {
                        workBook = new HSSFWorkbook(fs);
                    }
                    else
                    {
                        workBook = new XSSFWorkbook(fs);
                    }
                    // 获取工作表
                    ISheet sheet = workBook.GetSheetAt(0);
                    // 初始化反射
                    Type type = typeof(T);

                    if (type == null)
                    {
                        throw new Exception("数据对应的类不存在!");
                    }

                    // 获取excel中的数据 忽略标题行
                    for (int i = 1; i < sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        object obj = Activator.CreateInstance(type);
                        PropertyInfo[] propertyInfos = type.GetProperties();
                        for (int j = 0; j < row.LastCellNum; j++)
                        {
                            ICell cell = row.GetCell(j);
                            propertyInfos[j].SetValue(obj, Convert.ChangeType(cell.ToString(), propertyInfos[j].PropertyType));
                        }
                        dataList.Add((T)obj);
                    }
                }
            }
            catch (Exception e)
            {
                _ = e.StackTrace;
                return null;
            }


            return dataList;
        }

    }
}

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值