建议收藏:.net core 使用EPPlus导入导出Excel详细案例,精心整理源码已更新至开源模板

还记得刚曾经因为导入导出不会做而发愁的自己吗?我见过自己前同事因为一个导出改了好几天,然后我们发现虽然有开源的库但是用起来却不得心应手,主要是因为百度使用方案的时候很多方案并不能解决问题。

尤其是尝试新技术那些旧的操作还会有所改变,为了节约开发时间,我们把解决方案收入到一个个demo中,方便以后即拿即用。而且这些demo有博客文档支持,帮助任何人非常容易上手开发跨平台的.net core。随着时间的推移,我们的demo库会日益强大请及时收藏GitHub

一、首先在Common公用项目中引用EPPlus.Core类库和Json序列化的类库及读取配置文件的类库

Install-Package EPPlus.Core -Version 1.5.4
Install-Package Newtonsoft.Json -Version 12.0.3-beta2
Install-Package Microsoft.Extensions.Configuration.Json -Version 3.0.0

二、在Common公用项目中添加相关操作类OfficeHelper和CommonHelper及ConfigHelper

建议收藏:.net core 使用EPPlus导入导出Excel详细案例,精心整理源码已更新至开源模板_第1张图片

 1.OfficeHelper中Excel的操作方法

#region Excel

        #region EPPlus导出Excel
        /// 
        /// datatable导出Excel
        /// 
        /// 数据源
        /// webRoot文件夹
        /// 文件名
        /// 自定义列名(不传默认dt列名)
        /// 失败返回错误信息,有数据返回路径
        /// 
        public static bool DTExportEPPlusExcel(DataTable dt, string sWebRootFolder, string sFileName, string[] sColumnName, ref string msg)
        {
            try
            {
                if (dt == null || dt.Rows.Count == 0)
                {
                    msg = "数据为空";
                    return false;
                }

                //转utf-8
                UTF8Encoding utf8 = new UTF8Encoding();
                byte[] buffer = utf8.GetBytes(sFileName);
                sFileName = utf8.GetString(buffer);

                //判断文件夹,不存在创建
                if (!Directory.Exists(sWebRootFolder))
                    Directory.CreateDirectory(sWebRootFolder);

                //删除大于30天的文件,为了保证文件夹不会有过多文件
                string[] files = Directory.GetFiles(sWebRootFolder, "*.xlsx", SearchOption.AllDirectories);
                foreach (string item in files)
                {
                    FileInfo f = new FileInfo(item);
                    DateTime now = DateTime.Now;
                    TimeSpan t = now - f.CreationTime;
                    int day = t.Days;
                    if (day > 30)
                    {
                        File.Delete(item);
                    }
                }

                //判断同名文件
                FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                if (file.Exists)
                {
                    //判断同名文件创建时间
                    file.Delete();
                    file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                }
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    //添加worksheet
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sFileName.Split('.')[0]);

                    //添加表头
                    int column = 1;
                    if (sColumnName.Count() == dt.Columns.Count)
                    {
                        foreach (string cn in sColumnName)
                        {
                            worksheet.Cells[1, column].Value = cn.Trim();//可以只保留这个,不加央视,导出速度也会加快

                            worksheet.Cells[1, column].Style.Font.Bold = true;//字体为粗体
                            worksheet.Cells[1, column].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;//水平居中
                            worksheet.Cells[1, column].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;//设置样式类型
                            worksheet.Cells[1, column].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(159, 197, 232));//设置单元格背景色
                            column++;
                        }
                    }
                    else
                    {
                        foreach (DataColumn dc in dt.Columns)
                        {
                            worksheet.Cells[1, column].Value = dc.ColumnName;//可以只保留这个,不加央视,导出速度也会加快

                            worksheet.Cells[1, column].Style.Font.Bold = true;//字体为粗体
                            worksheet.Cells[1, column].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;//水平居中
                            worksheet.Cells[1, column].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;//设置样式类型
                            worksheet.Cells[1, column].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(159, 197, 232));//设置单元格背景色
                            column++;
                        }
                    }

                    //添加数据
                    int row = 2;
                    foreach (DataRow dr in dt.Rows)
                    {
                        int col = 1;
                        foreach (DataColumn dc in dt.Columns)
                        {
                            worksheet.Cells[row, col].Value = dr[col - 1].ToString();//这里已知可以减少一层循环,速度会上升
                            col++;
                        }
                        row++;
                    }

                    //自动列宽,由于自动列宽大数据导出严重影响速度,我这里就不开启了,大家可以根据自己情况开启
                    //worksheet.Cells.AutoFitColumns();

                    //保存workbook.
                    package.Save();
                }
                return true;
            }
            catch (Exception ex)
            {
                msg = "生成Excel失败:" + ex.Message;
                CommonHelper.WriteErrorLog("生成Excel失败:" + ex.Message);
                return false;
            }

        }
        /// 
        /// Model导出Excel
        /// 
        /// 数据源
        /// webRoot文件夹
        /// 文件名
        /// 自定义列名
        /// 失败返回错误信息,有数据返回路径
        /// 
        public static bool ModelExportEPPlusExcel(List myList, string sWebRootFolder, string sFileName, string[] sColumnName, ref string msg)
        {
            try
            {
                if (myList == null || myList.Count == 0)
                {
                    msg = "数据为空";
                    return false;
                }

                //转utf-8
                UTF8Encoding utf8 = new UTF8Encoding();
                byte[] buffer = utf8.GetBytes(sFileName);
                sFileName = utf8.GetString(buffer);

                //判断文件夹,不存在创建
                if (!Directory.Exists(sWebRootFolder))
                    Directory.CreateDirectory(sWebRootFolder);

                //删除大于30天的文件,为了保证文件夹不会有过多文件
                string[] files = Directory.GetFiles(sWebRootFolder, "*.xlsx", SearchOption.AllDirectories);
                foreach (string item in files)
                {
                    FileInfo f = new FileInfo(item);
                    DateTime now = DateTime.Now;
                    TimeSpan t = now - f.CreationTime;
                    int day = t.Days;
                    if (day > 30)
                    {
                        File.Delete(item);
                    }
                }

                //判断同名文件
                FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                if (file.Exists)
                {
                    //判断同名文件创建时间
                    file.Delete();
                    file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                }
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    //添加worksheet
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sFileName.Split('.')[0]);

                    //添加表头
                    int column = 1;
                    if (sColumnName.Count() > 0)
                    {
                        foreach (string cn in sColumnName)
                        {
                            worksheet.Cells[1, column].Value = cn.Trim();//可以只保留这个,不加央视,导出速度也会加快

                            worksheet.Cells[1, column].Style.Font.Bold = true;//字体为粗体
                            worksheet.Cells[1, column].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;//水平居中
                            worksheet.Cells[1, column].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;//设置样式类型
                            worksheet.Cells[1, column].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(159, 197, 232));//设置单元格背景色
                            column++;
                        }
                    }

                    //添加数据
                    int row = 2;
                    foreach (T ob in myList)
                    {
                        int col = 1;
                        foreach (System.Reflection.PropertyInfo property in ob.GetType().GetRuntimeProperties())
                        {
                            worksheet.Cells[row, col].Value = property.GetValue(ob);//这里已知可以减少一层循环,速度会上升
                            col++;
                        }
                        row++;
                    }

                    //自动列宽,由于自动列宽大数据导出严重影响速度,我这里就不开启了,大家可以根据自己情况开启
                    //worksheet.Cells.AutoFitColumns();

                    //保存workbook.
                    package.Save();
                }
                return true;
            }
            catch (Exception ex)
            {
                msg = "生成Excel失败:" + ex.Message;
                CommonHelper.WriteErrorLog("生成Excel失败:" + ex.Message);
                return false;
            }

        }
        #endregion

        #region EPPluse导入

        #region 转换为datatable
        public static DataTable InputEPPlusByExcelToDT(FileInfo file)
        {
            DataTable dt = new DataTable();
            if (file != null)
            {
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    try
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                        dt = WorksheetToTable(worksheet);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            return dt;
        }
        /// 
        /// 将worksheet转成datatable
        /// 
        /// 待处理的worksheet
        /// 返回处理后的datatable
        public static DataTable WorksheetToTable(ExcelWorksheet worksheet)
        {
            //获取worksheet的行数
            int rows = worksheet.Dimension.End.Row;
            //获取worksheet的列数
            int cols = worksheet.Dimension.End.Column;

            DataTable dt = new DataTable(worksheet.Name);
            DataRow dr = null;
            for (int i = 1; i <= rows; i++)
            {
                if (i > 1)
                    dr = dt.Rows.Add();

                for (int j = 1; j <= cols; j++)
                {
                    //默认将第一行设置为datatable的标题
                    if (i == 1)
                        dt.Columns.Add(GetString(worksheet.Cells[i, j].Value));
                    //剩下的写入datatable
                    else
                        dr[j - 1] = GetString(worksheet.Cells[i, j].Value);
                }
            }
            return dt;
        }
        private static string GetString(object obj)
        {
            try
            {
                return obj.ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion

        #region 转换为IEnumerable
        /// 
        /// 从Excel中加载数据(泛型)
        /// 
        /// 每行数据的类型
        /// Excel文件名
        /// 泛型列表
        public static IEnumerable LoadFromExcel(FileInfo existingFile) where T : new()
        {
            //FileInfo existingFile = new FileInfo(FileName);//如果本地地址可以直接使用本方法,这里是直接拿到了文件
            List resultList = new List();
            Dictionary<string, int> dictHeader = new Dictionary<string, int>();

            using (ExcelPackage package = new ExcelPackage(existingFile))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];

                int colStart = worksheet.Dimension.Start.Column;  //工作区开始列
                int colEnd = worksheet.Dimension.End.Column;       //工作区结束列
                int rowStart = worksheet.Dimension.Start.Row;       //工作区开始行号
                int rowEnd = worksheet.Dimension.End.Row;       //工作区结束行号

                //将每列标题添加到字典中
                for (int i = colStart; i <= colEnd; i++)
                {
                    dictHeader[worksheet.Cells[rowStart, i].Value.ToString()] = i;
                }

                List propertyInfoList = new List(typeof(T).GetProperties());

                for (int row = rowStart + 1; row <=rowEnd; row++)
                {
                    T result = new T();

                    //为对象T的各属性赋值
                    foreach (PropertyInfo p in propertyInfoList)
                    {
                        try
                        {
                            ExcelRange cell = worksheet.Cells[row, dictHeader[p.Name]]; //与属性名对应的单元格

                            if (cell.Value == null)
                                continue;
                            switch (p.PropertyType.Name.ToLower())
                            {
                                case "string":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "int16":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "int32":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "int64":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "decimal":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "double":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "datetime":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "boolean":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "byte":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "char":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                case "single":
                                    p.SetValue(result, cell.GetValue());
                                    break;
                                default:
                                    break;
                            }
                        }
                        catch (KeyNotFoundException ex)
                        { }
                    }
                    resultList.Add(result);
                }
            }
            return resultList;
        } 
        #endregion
        #endregion

        #endregion

2.ConfigHelper添加读取配置文件方法(了解更多看我过去的文章)

private static IConfiguration _configuration;

        static ConfigHelper()
        {
            //在当前目录或者根目录中寻找appsettings.json文件
            var fileName = "Config/ManagerConfig.json";

            var directory = AppContext.BaseDirectory;
            directory = directory.Replace("\\", "/");

            var filePath = $"{directory}/{fileName}";
            if (!File.Exists(filePath))
            {
                var length = directory.IndexOf("/bin");
                filePath = $"{directory.Substring(0, length)}/{fileName}";
            }

            var builder = new ConfigurationBuilder()
                .AddJsonFile(filePath, false, true);

            _configuration = builder.Build();
        }

        public static string GetSectionValue(string key)
        {
            return _configuration.GetSection(key).Value;
        }

3.CommonHelper中加入json相关操作

/// 
        /// 得到一个包含Json信息的JsonResult
        /// 
        /// 服务器处理是否成功 1.成功 -1.失败 0.没有数据
        /// 报错消息
        /// 携带的额外信息
        /// 
        public static string GetJsonResult(int code, string msg, object data = null)
        {
            var jsonObj = new { code = code, msg = msg, data = data };
            return Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj);
        }

三、添加OfficeController控制器和ManagerConfig配置文件

建议收藏:.net core 使用EPPlus导入导出Excel详细案例,精心整理源码已更新至开源模板_第2张图片

 

 1.ManagerConfig配置(了解更多看我过去的文章)

{
  "FileMap": {
    "ImgPath": "D:\\myfile\\TemplateCore\\TemplateCore\\wwwroot\\UpImg\\",
    "ImgWeb": "http://127.0.0.1:1994/UpImg/",
    "FilePath": "D:\\myfile\\TemplateCore\\TemplateCore\\wwwroot\\UpFile\\",
    "FileWeb": "http://127.0.0.1:1994/UpFile/",
    "VideoPath": "D:\\myfile\\TemplateCore\\TemplateCore\\wwwroot\\UpVideo\\",
    "VideoWeb": "http://127.0.0.1:1994/UpVideo/",
    "Web": "http://127.0.0.1:1994/"
  }
}

2.OfficeController控制器添加Excel处理相应方法

#region EPPlus导出Excel
        public string DTExportEPPlusExcel()
        {
            string code = "fail";
            DataTable tblDatas = new DataTable("Datas");
            DataColumn dc = null;
            dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;//自动增加
            dc.AutoIncrementSeed = 1;//起始为1
            dc.AutoIncrementStep = 1;//步长为1
            dc.AllowDBNull = false;//

            dc = tblDatas.Columns.Add("Product", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("Version", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("Description", Type.GetType("System.String"));

            DataRow newRow;
            newRow = tblDatas.NewRow();
            newRow["Product"] = "大话西游";
            newRow["Version"] = "2.0";
            newRow["Description"] = "我很喜欢";
            tblDatas.Rows.Add(newRow);

            newRow = tblDatas.NewRow();
            newRow["Product"] = "梦幻西游";
            newRow["Version"] = "3.0";
            newRow["Description"] = "比大话更幼稚";
            tblDatas.Rows.Add(newRow);

            newRow = tblDatas.NewRow();
            newRow["Product"] = "西游记";
            newRow["Version"] = null;
            newRow["Description"] = "";
            tblDatas.Rows.Add(newRow);

            for (int x = 0; x < 100000; x++)
            {
                newRow = tblDatas.NewRow();
                newRow["Product"] = "西游记"+x;
                newRow["Version"] = ""+x;
                newRow["Description"] = x;
                tblDatas.Rows.Add(newRow);
            }
            string fileName = "MyExcel.xlsx";
            string[] nameStrs = new string[tblDatas.Rows.Count];//每列名,这里不赋值则表示取默认
            string savePath = "wwwroot/Excel";//相对路径
            string msg = "Excel/"+ fileName;//文件返回地址,出错就返回错误信息。
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();  //开始监视代码运行时间
            bool b = OfficeHelper.DTExportEPPlusExcel(tblDatas, savePath, fileName, nameStrs, ref msg) ;
            TimeSpan timespan = watch.Elapsed;  //获取当前实例测量得出的总时间
            watch.Stop();  //停止监视
            if (b)
            {
                code = "success";
            }
            return "{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\",\"timeSeconds\":\"" + timespan.TotalSeconds + "\"}";
        }
        public string ModelExportEPPlusExcel()
        {
            string code = "fail";
            List
articleList = new List
(); for (int x = 0; x < 100000; x++) { Article article = new Article(); article.Context = "内容:"+x; article.Id = x + 1; article.CreateTime = DateTime.Now; article.Title = "标题:" + x; articleList.Add(article); } string fileName = "MyModelExcel.xlsx"; string[] nameStrs = new string[4] {"Id", "Title", "Context", "CreateTime" };//按照模型先后顺序,赋值需要的名称 string savePath = "wwwroot/Excel";//相对路径 string msg = "Excel/" + fileName;//文件返回地址,出错就返回错误信息。 System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); //开始监视代码运行时间 bool b = OfficeHelper.ModelExportEPPlusExcel(articleList, savePath, fileName, nameStrs, ref msg); TimeSpan timespan = watch.Elapsed; //获取当前实例测量得出的总时间 watch.Stop(); //停止监视 if (b) { code = "success"; } return "{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\",\"timeSeconds\":\"" + timespan.TotalSeconds + "\"}"; } #endregion #region EPPlus导出数据 public async Task<string> ExcelImportEPPlusDTJsonAsync() { IFormFileCollection files = Request.Form.Files; DataTable articles = new DataTable(); int code = 0; string msg = "失败!"; var file = files[0]; string path = ConfigHelper.GetSectionValue("FileMap:FilePath") + files[0].FileName; using (FileStream fs = System.IO.File.Create(path)) { await file.CopyToAsync(fs); fs.Flush(); } System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); //开始监视代码运行时间 FileInfo fileExcel = new FileInfo(path); articles = OfficeHelper.InputEPPlusByExcelToDT(fileExcel); TimeSpan timespan = watch.Elapsed; //获取当前实例测量得出的总时间 watch.Stop(); //停止监视 code = 1; msg = "成功!"; string json = CommonHelper.GetJsonResult(code, msg, new { articles, timespan }); return json; } public async Task<string> ExcelImportEPPlusModelJsonAsync() { IFormFileCollection files = Request.Form.Files; List
articles = new List
(); int code = 0; string msg = "失败!"; var file = files[0]; string path = ConfigHelper.GetSectionValue("FileMap:FilePath")+files[0].FileName; using (FileStream fs = System.IO.File.Create(path)) { await file.CopyToAsync(fs); fs.Flush(); } System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); //开始监视代码运行时间 FileInfo fileExcel = new FileInfo(path); articles=OfficeHelper.LoadFromExcel
(fileExcel).ToList(); TimeSpan timespan = watch.Elapsed; //获取当前实例测量得出的总时间 watch.Stop(); //停止监视 code = 1;msg = "成功!"; string json = CommonHelper.GetJsonResult(code, msg, new { articles, timespan }); return json; } #endregion

四、前端请求设计

 

"margin-top:30px;">

EPPlus导出案例

EPPlus导入案例

class="col-xs-12 col-sm-4 col-md-4" style="width:100%;">
class="file-container" style="display:inline-block;position:relative;overflow: hidden;vertical-align:middle"> "file" accept=".xls,.xlsx" id="ExcelToModel" οnchange="ExcelToModel(this.files[0])" style="position:absolute;top:0;left:0;font-size:34px; opacity:0">
"filename" style="vertical-align: middle">未上传文件 "ToModel">


class="col-xs-12 col-sm-4 col-md-4" style="width:100%;">
class="file-container" style="display:inline-block;position:relative;overflow: hidden;vertical-align:middle"> "file" accept=".xls,.xlsx" id="ExcelToDT" οnchange="ExcelToDT(this.files[0])" style="position:absolute;top:0;left:0;font-size:34px; opacity:0">
"filename1" style="vertical-align: middle">未上传文件 "ToDT">

上面的上传为了美观用了bootstrap的样式,如果你喜欢原生可以把两个导入案例通过如下代码替换,其它条件无需改变。

".xls,.xlsx" type="file" id="ExcelToModel" style="display:initial;" />
".xls,.xlsx" type="file" id="ExcelToDT" style="display:initial;" />

五、那么看下效果吧,我们这里模拟了10w条数据进行了简单实验,一般要求满足应该没什么问题。

开源地址 动动小手,点个推荐吧!

 

注意:我们机遇屋该项目将长期为大家提供asp.net core各种好用demo,旨在帮助.net开发者提升竞争力和开发速度,建议尽早收藏该模板集合项目。

 

你可能感兴趣的:(技术)