c#使用EPPlus封裝excel表格導(dǎo)入功能的問題
前言
最近做系統(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)換
類型之間的轉(zhuǎn)換可以分為隱式轉(zhuǎn)換與顯式轉(zhuǎn)換,如int類型可直接轉(zhuǎn)換為long類型。2010-02-02
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)換
在我們采用反射動(dòng)態(tài)調(diào)用一些方法時(shí),常常涉及到類型的轉(zhuǎn)換,直接判斷類型是否相符有時(shí)不能判斷調(diào)用方法是否合適2013-04-04
C#單向鏈表實(shí)現(xiàn)非升序插入方法的實(shí)例詳解
單向鏈表是一種數(shù)據(jù)結(jié)構(gòu),其中元素以線性方式連接在一起,每個(gè)元素都指向下一個(gè)元素,非升序插入意味著元素不是按升序(從小到大)插入鏈表中,本文給大家介紹了C#單向鏈表實(shí)現(xiàn)非升序插入方法的實(shí)例,需要的朋友可以參考下2024-03-03

