Abp import& export

安装EPPlus包
EPPlus is a .NET library that reads and writes Excel files using the Office Open XML format (xlsx). EPPlus has no dependencies other than .NET.
EPPlus只依赖.NET,用于读写xlsx格式的excel

参考:https://github.com/JanKallman/EPPlus

参考abp-demo

在这里插入图片描述

Import

class EpPlusExcelImporterBase<TEntity>
{
    public List<TEntity> ProcessExcelFile(byte[] fileBytes, Func<ExcelWorksheet, int, TEntity> processExcelRow)
    {
        var entities = new List<TEntity>();
        using (var stream = new MemoryStream(fileBytes))
        {
        using (var excelPackage = new ExcelPackage(stream))
        {
            foreach (var worksheet in excelPackage.Workbook.Worksheets)
            {
            var entitiesInWorksheet = ProcessWorksheet(worksheet, processExcelRow);
            entities.AddRange(entitiesInWorksheet);
            }
        }
        }

        return entities;
    }

    private List<TEntity> ProcessWorksheet(ExcelWorksheet worksheet, Func<ExcelWorksheet, int, TEntity> processExcelRow)
    {
        var entities = new List<TEntity>();
        for (var i = worksheet.Dimension.Start.Row + 1; i <= worksheet.Dimension.End.Row; i++)
        {
        try
        {
            var entity = processExcelRow(worksheet, i);
            if (entity != null)
            {
            entities.Add(entity);
            }
        }
        catch (Exception)
        { }
        }
        return entities;
    }
}

Import

 public abstract class EpPlusExcelExporterBase: AprilAppServiceBase, ITransientDependency
    {
        private readonly ITempFileCacheManager _tempFileCacheManager;
        protected EpPlusExcelExporterBase(ITempFileCacheManager tempFileCacheManager)
        {
            _tempFileCacheManager = tempFileCacheManager;
        }
        protected FileDto CreateExcelPackage(string fileName, Action<ExcelPackage> creator)
        {
            var file = new FileDto(fileName, MimeTypeNames.ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet);
            using (var excelPackage = new ExcelPackage())
            {
                creator(excelPackage);
                Save(excelPackage, file);
            }
            return file;
        }

        protected void Save(ExcelPackage excelPackage, FileDto file)
        {
            _tempFileCacheManager.setFile(file.FileToken, excelPackage.GetAsByteArray());
        }
    }