最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

前言

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

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

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

遇到的問題

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

雖然我之前沒寫過相關(guān)的業(yè)務(wù),但是直覺的認(rèn)為這樣寫非常麻煩,那個(gè) ExcelHelper 好像也沒干什么事,我希望一套操作下來可以把 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í)生成對應(yīng)的 實(shí)體對象

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

public class ExcelCellOption<T>
{
    /// <summary>
    /// 對應(yīng)excel中的header表頭(title)
    /// </summary>
    public string ExcelField { get; set; }
    /// <summary>
    /// 對應(yīng)字段的屬性(實(shí)際上包含PropName)
    /// </summary>
    public PropertyInfo Prop { get; set; }
    /// <summary>
    /// 就是一個(gè)看起來比較方便的標(biāo)識
    /// </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表格生成對應(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;
        // 獲取對應(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)換為 對應(yīng)實(shí)體
        for (int r = 2; r <= rowCount; r++)
        {
            // 將單行數(shù)據(jù)轉(zhuǎn)換為 表頭:數(shù)據(jù) 的鍵值對
            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ù)對應(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));
                }
                // 可以用來初始化與表格無關(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;
            // 獲取對應(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)換為 對應(yīng)實(shí)體F
            for (int r = 2; r <= rowCount; r++)
            {
                // 將單行數(shù)據(jù)轉(zhuǎn)換為 表頭:數(shù)據(jù) 的鍵值對
                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ù)對應(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));
                    }
                    // 可以用來初始化與表格無關(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>
        /// 對應(yīng)excel中的header字段
        /// </summary>
        public string ExcelField { get; set; }
        /// <summary>
        /// 對應(yīng)字段的屬性(實(shí)際上包含PropName)
        /// </summary>
        public PropertyInfo Prop { get; set; }
        /// <summary>
        /// 就是一個(gè)看起來比較方便的標(biāo)識
        /// </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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C#難點(diǎn)逐個(gè)擊破(9):類型轉(zhuǎn)換

    C#難點(diǎn)逐個(gè)擊破(9):類型轉(zhuǎn)換

    類型之間的轉(zhuǎn)換可以分為隱式轉(zhuǎn)換與顯式轉(zhuǎn)換,如int類型可直接轉(zhuǎn)換為long類型。
    2010-02-02
  • C#壓縮和解壓文件的兩種方法

    C#壓縮和解壓文件的兩種方法

    在C#中,我們可以使用內(nèi)置的System.IO命名空間下的幾個(gè)類來處理文件的壓縮和解壓縮,主要涉及到兩個(gè)常用的庫:System.IO.Compression和WinRAR,以下是使用這些類進(jìn)行文件壓縮和解壓縮的基本步驟,需要的朋友可以參考下
    2024-08-08
  • 詳解C#如何實(shí)現(xiàn)樹形圖列表

    詳解C#如何實(shí)現(xiàn)樹形圖列表

    這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)樹形圖列表,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以了解一下
    2022-12-12
  • C#實(shí)現(xiàn)生成指定圖片的縮略圖

    C#實(shí)現(xiàn)生成指定圖片的縮略圖

    這篇文章主要為大家詳細(xì)介紹了如何使用C#實(shí)現(xiàn)生成指定圖片的縮略圖,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-04-04
  • C#中Array的存儲結(jié)構(gòu)簡單介紹

    C#中Array的存儲結(jié)構(gòu)簡單介紹

    本文將從一個(gè)數(shù)組的基礎(chǔ)操作開始,逐步來推導(dǎo)數(shù)組的在C#基礎(chǔ)操作、數(shù)組在CoreCLR的維護(hù)策略,數(shù)組在C++的內(nèi)存分配等階段具體是如何實(shí)現(xiàn)的,感興趣的朋友跟隨小編一起看看吧
    2023-11-11
  • C#實(shí)現(xiàn)多種圖片格式轉(zhuǎn)換的示例詳解

    C#實(shí)現(xiàn)多種圖片格式轉(zhuǎn)換的示例詳解

    這篇文章主要為大家詳細(xì)介紹了C#如何實(shí)現(xiàn)多種圖片格式轉(zhuǎn)換,例如轉(zhuǎn)換成圖標(biāo)圖像ICO,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • C#中判斷某類型是否可以進(jìn)行隱式類型轉(zhuǎn)換

    C#中判斷某類型是否可以進(jìn)行隱式類型轉(zhuǎn)換

    在我們采用反射動(dòng)態(tài)調(diào)用一些方法時(shí),常常涉及到類型的轉(zhuǎn)換,直接判斷類型是否相符有時(shí)不能判斷調(diào)用方法是否合適
    2013-04-04
  • C# 基礎(chǔ)入門--常量

    C# 基礎(chǔ)入門--常量

    本文主要介紹了C#中常量的相關(guān)知識,具有很好的參考價(jià)值。下面跟著小編一起來看下吧
    2017-03-03
  • C#單向鏈表實(shí)現(xiàn)非升序插入方法的實(shí)例詳解

    C#單向鏈表實(shí)現(xiàn)非升序插入方法的實(shí)例詳解

    單向鏈表是一種數(shù)據(jù)結(jié)構(gòu),其中元素以線性方式連接在一起,每個(gè)元素都指向下一個(gè)元素,非升序插入意味著元素不是按升序(從小到大)插入鏈表中,本文給大家介紹了C#單向鏈表實(shí)現(xiàn)非升序插入方法的實(shí)例,需要的朋友可以參考下
    2024-03-03
  • C#異步的世界(上)

    C#異步的世界(上)

    這篇文章主要介紹了C#異步的世界,對異步感興趣的同學(xué),可以參考下
    2021-04-04

最新評論

忻州市| 宜春市| 汉源县| 工布江达县| 讷河市| 永登县| 辽宁省| 邮箱| 莱阳市| 额济纳旗| 拜泉县| 乡宁县| 城市| 楚雄市| 东光县| 黄陵县| 达尔| 乐业县| 苍山县| 建阳市| 油尖旺区| 巫溪县| 山西省| 师宗县| 肇州县| 汝城县| 霍邱县| 龙里县| 贵阳市| 黑河市| 图片| 皮山县| 丹东市| 平山县| 常熟市| 磐石市| 柏乡县| 游戏| 汤阴县| 汽车| 新和县|