c\#EPPlus 로 엑셀 표 가 져 오기 기능 을 봉인 하 는 문제

머리말
최근 에 시스템 을 할 때 엑셀 가 져 오 는 기능 이 많 았 습 니 다.예전 에 제 가 앞 뒤 끝 을 다 할 때 전단 에서 분석 한 다음 에 대량으로 삽입 하 는 인 터 페 이 스 를 만 들 었 습 니 다.
나 는 이렇게 하 는 것 이 매우 좋다 고 생각한다.백 엔 드 부분 은 매우 간단하게 할 수 있다.
그러나 여러 가지 이유 로 결국 전문 적 인 엑셀 인 터 페 이 스 를 만들어 야 한다.
닥 친 문제
이전에 백 엔 드 부분 에서 표를 처리 한 적 이 없 기 때문에 나 는 동료의 코드 를 어떻게 쓰 는 지 보 려 고 한다.

비록 저 는 관련 업 무 를 써 본 적 이 없 지만 직관 적 으로 이렇게 쓰 는 것 이 매우 번거롭다 고 생각 합 니 다.그것ExcelHelper은 아무 일 도 하지 않 은 것 같 습 니 다.저 는 한 가지 조작 을 통 해 엑셀 을 직접 전달 할 수 있 는AddRange으로 전환 시 켜 대량으로 추 가 된 실체 집합 을 할 수 있 기 를 바 랍 니 다.
그래서 제 가 포장 하기 로 했 어 요.
결과 전시(약)

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;
}
최종 적 으로'초기 화'데 이 터 를 직접 생 성 할 수 있 는result코드/디자인/아이디어
저 는 사용 할 때 들 어 오 는 . 의 관 계 를 통 해 집합 하고 싶 습 니 다.
분석 표를 실현 하 는 동시에 대응 하 는 것 을 생 성 합 니 다 그리고 상기 관계 에 대한 정 의 는 다음 과 같다.

public class ExcelCellOption<T>
{
    /// <summary>
    ///   excel  header  (title)
    /// </summary>
    public string ExcelField { get; set; }
    /// <summary>
    ///        (     PropName)
    /// </summary>
    public PropertyInfo Prop { get; set; }
    /// <summary>
    ///               
    /// </summary>
    public string PropName { get; set; }
    /// <summary>
    ///            (  )
    /// </summary>
    public Func<string, object> Action { get; set; }
}
이후 그 에 게 정적 방법GenExcelOption<E>생 성 관계 집합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
        }
    };
}
편 의 를 위해 새로운 설정 항목 을 추가 합 니 다.
반환 형식ICollection<ExcelCellOption<T>>확장 방법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;
    }
}
사용 할 때 excel 표 에 따라 대응 하 는 관계 집합 을 생 성 할 수 있 습 니 다(설정)

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));
설정 이 있 으 면 설정 에 따라 엑셀 을 분석 하여 데이터 실 체 를 생 성 해 야 합 니 다.
다음 과 같은 방법 을 썼 습 니 다.

public class ExcelOperation
{
    /// <summary>
    ///                
    /// </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;
        //                column  
        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            
        for (int r = 2; r <= rowCount; r++)
        {
            //            :       
            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));
            //            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));
                }
                //                        Guid        
                else
                    option.Prop.SetValue(obj, option.Action == null ? null : option.Action(string.Empty));
            }
            data.Add((T)obj);
        }
        return data;
    }
}
최종 호출

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>
        ///                
        /// </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;
            //                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            F
            for (int r = 2; r <= rowCount; r++)
            {
                //            :       
                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));
                //            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));
                    }
                    //                        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>
        ///   excel  header  
        /// </summary>
        public string ExcelField { get; set; }
        /// <summary>
        ///        (     PropName)
        /// </summary>
        public PropertyInfo Prop { get; set; }
        /// <summary>
        ///               
        /// </summary>
        public string PropName { get; set; }
        /// <summary>
        ///            
        /// </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;
        }
    }
}
사실 이게 옛날 버 전이 에 요.
새로운 버 전이 며칠 지나 면 아마 나 올 거 예요.
c\#EPPlus 를 사용 하여 엑셀 표 가 져 오기 기능 을 봉인 하 는 문제 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 관련 c\#EPPlus 를 사용 하여 엑셀 표 가 져 오기 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 바 랍 니 다!

좋은 웹페이지 즐겨찾기