欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c#使用EPPlus封裝excel表格導(dǎo)入功能的問題

 更新時(shí)間:2021年04月12日 10:53:09   作者:崩壞的領(lǐng)航員  
這篇文章主要介紹了c#使用EPPlus封裝excel表格導(dǎo)入功能的問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

前言

最近做系統(tǒng)的時(shí)候有很多 excel導(dǎo)入 的功能,以前我前后端都做的時(shí)候是在前端解析,然后再做個(gè)批量插入的接口

我覺著這樣挺好的,后端部分可以做的很簡(jiǎn)單(很偷懶的)

但是因?yàn)楦鞣N各樣的原因,最終還是需要做個(gè)專門的 excel導(dǎo)入 接口

遇到的問題

由于之前從來(lái)沒有在后端部分處理過表格,所以我選擇看一下同事的代碼是怎么寫的

雖然我之前沒寫過相關(guān)的業(yè)務(wù),但是直覺的認(rèn)為這樣寫非常麻煩,那個(gè) ExcelHelper 好像也沒干什么事,我希望一套操作下來(lái)可以把 excel 轉(zhuǎn)成能夠直接傳入 AddRange 進(jìn)行批量新增的實(shí)體集合

所以我就決定自己封裝。

結(jié)果展示(略)

public ICollection<TestDto> ExcelImport(IFormFile file)
{
    var config = ExcelCellOption<TestDto>
    .GenExcelOption("姓名", item => item.Name)
    .Add("年齡", item => item.Age, item => int.Parse(item))
    .Add("性別", item => item.Gender, item => item == "男")
    .Add("身高", item => item.Height, item => double.Parse(item));

    ICollection<TestDto> result = ExcelOperation.ExcelToEntity(file.OpenReadStream(), config);

    return result;
}

最終可以直接生成"初始化"數(shù)據(jù)的 result

代碼/設(shè)計(jì)/想法

我希望使用的時(shí)候通過傳入 表格字段數(shù)據(jù)實(shí)體.屬性 的關(guān)系集合

實(shí)現(xiàn)解析表格的同時(shí)生成對(duì)應(yīng)的 實(shí)體對(duì)象

然后我對(duì)上述 關(guān)系 的定義如下

public class ExcelCellOption<T>
{
    /// <summary>
    /// 對(duì)應(yīng)excel中的header表頭(title)
    /// </summary>
    public string ExcelField { get; set; }
    /// <summary>
    /// 對(duì)應(yīng)字段的屬性(實(shí)際上包含PropName)
    /// </summary>
    public PropertyInfo Prop { get; set; }
    /// <summary>
    /// 就是一個(gè)看起來(lái)比較方便的標(biāo)識(shí)
    /// </summary>
    public string PropName { get; set; }
    /// <summary>
    /// 轉(zhuǎn)換 表格 數(shù)據(jù)的方法(委托)
    /// </summary>
    public Func<string, object> Action { get; set; }
}

之后給他加了個(gè)靜態(tài)方法 GenExcelOption<E> 生成關(guān)系集合 ICollection<ExcelCellOption<T>>

public static ICollection<ExcelCellOption<T>> GenExcelOption<E>(string field,
            Expression<Func<T, E>> prop, Func<string, object> action = null)
{
    var member = prop.GetMember();
    return new List<ExcelCellOption<T>>{
        new ExcelCellOption<T>
        {
            PropName = member.Name,
            Prop = (PropertyInfo)member,
            ExcelField = field,
            Action = action
        }
    };
}

為了方便之后加新的配置項(xiàng)

給返回類型 ICollection<ExcelCellOption<T>> 搞個(gè)擴(kuò)展方法 Add

public static class ExcelOptionExt
{
    public static ICollection<ExcelCellOption<T>> Add<T, E>(this ICollection<ExcelCellOption<T>> origin,
    string field, Expression<Func<T, E>> prop, Func<string, object> action = null)
    {
        var member = prop.GetMember();
        origin.Add(new ExcelCellOption<T>
        {
            PropName = member.Name,
            Prop = (PropertyInfo)member,
            ExcelField = field,
            Action = action
        });
        return origin;
    }
}

使用的時(shí)候就可以根據(jù)excel表格生成對(duì)應(yīng)的 關(guān)系集合 (配置)

var config = ExcelCellOption<TestDto>
.GenExcelOption("姓名", item => item.Name)
.Add("年齡", item => item.Age, item => int.Parse(item))
.Add("性別", item => item.Gender, item => item == "男")
.Add("身高", item => item.Height, item => double.Parse(item));

有了配置之后需要根據(jù)配置解析excel生成數(shù)據(jù)實(shí)體了

寫了個(gè)方法如下

public class ExcelOperation
{
    /// <summary>
    /// 將表格數(shù)據(jù)轉(zhuǎn)換為指定的數(shù)據(jù)實(shí)體
    /// </summary>
    public static ICollection<T> ExcelToEntity<T>(Stream excelStream, ICollection<ExcelCellOption<T>> options)
    {
        using ExcelPackage pack = new(excelStream);
        var sheet = pack.Workbook.Worksheets[1];
        int rowCount = sheet.Dimension.Rows, colCount = sheet.Dimension.Columns;
        // 獲取對(duì)應(yīng)設(shè)置的 表頭 以及其 column下標(biāo)
        var header = sheet.Cells[1, 1, 1, colCount ]
        .Where(item => options.Any(opt => opt.ExcelField == item.Value?.ToString().Trim()))
        .ToDictionary(item => item.Value?.ToString().Trim(), item => item.End.Column);
        List<T> data = new();
        // 將excel 的數(shù)據(jù)轉(zhuǎn)換為 對(duì)應(yīng)實(shí)體
        for (int r = 2; r <= rowCount; r++)
        {
            // 將單行數(shù)據(jù)轉(zhuǎn)換為 表頭:數(shù)據(jù) 的鍵值對(duì)
            var rowData = sheet.Cells[r, 1, r, colCount]
            .Where(item => header.Any(title => title.Value == item.End.Column))
            .Select(item => new KeyValuePair<string, string>(header.First(title => title.Value == item.End.Column).Key, item.Value?.ToString().Trim()))
            .ToDictionary(item => item.Key, item => item.Value);
            var obj = Activator.CreateInstance(typeof(T));
            // 根據(jù)對(duì)應(yīng)傳入的設(shè)置 為obj賦值
            foreach (var option in options)
            {
                if (!string.IsNullOrEmpty(option.ExcelField))
                {
                    var value = rowData.ContainsKey(option.ExcelField) ? rowData[option.ExcelField] : string.Empty;
                    if (!string.IsNullOrEmpty(value))
                        option.Prop.SetValue(obj, option.Action == null ? value : option.Action(value));
                }
                // 可以用來(lái)初始化與表格無(wú)關(guān)的字段 如 創(chuàng)建時(shí)間 Guid主鍵 之類的東西
                else
                    option.Prop.SetValue(obj, option.Action == null ? null : option.Action(string.Empty));
            }
            data.Add((T)obj);
        }
        return data;
    }
}

最終調(diào)用

ExcelOperation.ExcelToEntity(file.OpenReadStream(), config)

傳入文件流和配置集合即可

完整代碼

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Internal;
using OfficeOpenXml;

namespace XXX.XXX.XXX.XXX
{
    public class ExcelOperation
    {
        /// <summary>
        /// 將表格數(shù)據(jù)轉(zhuǎn)換為指定的數(shù)據(jù)實(shí)體
        /// </summary>
        public static ICollection<T> ExcelToEntity<T>(Stream excelStream, ICollection<ExcelCellOption<T>> options)
        {
            using ExcelPackage pack = new(excelStream);
            var sheet = pack.Workbook.Worksheets[1];
            int rowCount = sheet.Dimension.Rows, colCount = sheet.Dimension.Columns;
            // 獲取對(duì)應(yīng)設(shè)置的 表頭 以及其 column
            var header = sheet.Cells[1, 1, 1, sheet.Dimension.Columns]
            .Where(item => options.Any(opt => opt.ExcelField == item.Value.ToString()))
            .ToDictionary(item => item.Value.ToString(), item => item.End.Column);
            List<T> data = new();
            // 將excel 的數(shù)據(jù)轉(zhuǎn)換為 對(duì)應(yīng)實(shí)體F
            for (int r = 2; r <= rowCount; r++)
            {
                // 將單行數(shù)據(jù)轉(zhuǎn)換為 表頭:數(shù)據(jù) 的鍵值對(duì)
                var rowData = sheet.Cells[r, 1, r, colCount]
                .Where(item => header.Any(title => title.Value == item.End.Column))
                .Select(item => new KeyValuePair<string, string>(header.First(title => title.Value == item.End.Column).Key, item.Value?.ToString()))
                .ToDictionary(item => item.Key, item => item.Value);
                var obj = Activator.CreateInstance(typeof(T));
                // 根據(jù)對(duì)應(yīng)傳入的設(shè)置 為obj賦值
                foreach (var option in options)
                {
                    if (!string.IsNullOrEmpty(option.ExcelField))
                    {
                        var value = rowData.ContainsKey(option.ExcelField) ? rowData[option.ExcelField] : string.Empty;
                        if (!string.IsNullOrEmpty(value))
                            option.Prop.SetValue(obj, option.Action == null ? value : option.Action(value));
                    }
                    // 可以用來(lái)初始化與表格無(wú)關(guān)的字段 如 創(chuàng)建時(shí)間 Guid主鍵 之類的東西
                    else
                        option.Prop.SetValue(obj, option.Action == null ? null : option.Action(string.Empty));
                }
                data.Add((T)obj);
            }
            return data;
        }
    }

    public class ExcelCellOption<T>
    {
        /// <summary>
        /// 對(duì)應(yīng)excel中的header字段
        /// </summary>
        public string ExcelField { get; set; }
        /// <summary>
        /// 對(duì)應(yīng)字段的屬性(實(shí)際上包含PropName)
        /// </summary>
        public PropertyInfo Prop { get; set; }
        /// <summary>
        /// 就是一個(gè)看起來(lái)比較方便的標(biāo)識(shí)
        /// </summary>
        public string PropName { get; set; }
        /// <summary>
        /// 轉(zhuǎn)換 表格 數(shù)據(jù)的方法
        /// </summary>
        public Func<string, object> Action { get; set; }
        public static ICollection<ExcelCellOption<T>> GenExcelOption<E>(string field, Expression<Func<T, E>> prop, Func<string, object> action = null)
        {
            var member = prop.GetMember();
            return new List<ExcelCellOption<T>>{
                new ExcelCellOption<T>
                {
                    PropName = member.Name,
                    Prop = (PropertyInfo)member,
                    ExcelField = field,
                    Action = action
                }
            };
        }
    }

    public static class ExcelOptionAdd
    {
        public static ICollection<ExcelCellOption<T>> Add<T, E>(this ICollection<ExcelCellOption<T>> origin, string field, Expression<Func<T, E>> prop, Func<string, object> action = null)
        {
            var member = prop.GetMember();
            origin.Add(new ExcelCellOption<T>
            {
                PropName = member.Name,
                Prop = (PropertyInfo)member,
                ExcelField = field,
                Action = action
            });
            return origin;
        }
    }
}

其實(shí)這已經(jīng)是舊版本了

新的版本過幾天大概會(huì)發(fā)

到此這篇關(guān)于c#使用EPPlus封裝excel表格導(dǎo)入功能的問題的文章就介紹到這了,更多相關(guān)c#使用EPPlus封裝excel表格導(dǎo)入內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論