码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-04-28 14:52:09      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:temp   导出   list   each   prope   oid   bsp   class   http   

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

public static void TemplateWrite<T>(List<T> datas, int startRow = 2, string targetPath = @"D:\导出excel测试.xlsx", string templatePath = @"D:\github\Demo\NetCoreDemo\src\ExcelDemo\Template\template.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

标签:temp   导出   list   each   prope   oid   bsp   class   http   

原文地址:https://www.cnblogs.com/dayang12525/p/12793966.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!