使用Epplus以及Excel将模板导出excel

Posted dayang12525

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Epplus以及Excel将模板导出excel相关的知识,希望对你有一定的参考价值。

1、核心逻辑(为了测试方便,路径直接写死了):

public static void TemplateWrite<T>(List<T> datas, int startRow = 2, string targetPath = @"D:导出excel测试.xlsx", string templatePath = @"D:githubDemoNetCoreDemosrcExcelDemoTemplate	emplate.xlsx")
        {
            var stream = FileToStream(templatePath);

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

                startRow = 3;
                Type myType = typeof(T);

                var pros = myType.GetProperties();

                foreach (var data in datas)
                {
                    worksheet.Cells.AutoFitColumns();//自适应宽度

                    var column = 1;
                    foreach (var item in pros)
                    {
                        //遍历赋值:前提是要顺序一致。
                        var value = item.GetValue(data, null);
                        worksheet.Cells[startRow, column].Value = value;
                        column++;
                    }

                    startRow++;
                }
                FileInfo fs = new FileInfo(targetPath);
                package.SaveAs(fs);
            }
        }

2、测试Model

  public class Students
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int ClassNum { get; set; }
        public decimal Math { get; set; }
        public decimal Lang { get; set; }
        public string dec { get; set; }
    }

3、模板

技术图片

 

 4、调用方法:

 static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            List<Students> students = new List<Students>();
            students.Add(new Students() { Name = "张三", Age = 5, ClassNum = 6, Lang = 90, Math = 89,dec= "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" });
            students.Add(new Students() { Name = "李四", Age = 8, ClassNum = 5, Lang = 70, Math = 99, dec = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" });

            EpplusExcelHelper.TestTemplateWrite(students);
        }

5、运行,查看运行结果:

技术图片

 

以上是关于使用Epplus以及Excel将模板导出excel的主要内容,如果未能解决你的问题,请参考以下文章

导出Excel之Epplus使用教程4(其他设置)

使用 EPPLUS 从列表导出到 Excel

导出Excel之Epplus使用教程2(样式设置)

C# NPOI导出Excel和EPPlus导出Excel比较

导出Excel之Epplus使用教程3(图表设置)

Epplus:导出Excel