将模型导出为.xlsx遵守SOLID原则

时间:2016-09-16 14:46:11

标签: c# oop solid-principles

对不起我的英语!

我的数据库有两个包含测试结果的表格:

dbo.Result enter image description here

第二张表中只有关于学校的信息:

dbo.School
enter image description here

此类记录可能为40.000-70.000。最后,我需要得到这样的报告文件(pdf):

enter image description here

我的解决方案:

  1. 创建Excel-temple;
  2. 从数据库导入数据并导出此Excel-temple;
  3. 另存为.pdf;
  4. 然后是每条记录(人)的第1步。
  5. enter image description here

    LearnerReport.cs

    namespace so16092016.Models
    {
        public class LearnerReport
        {
            public string SNS { get; set; } //Surname Name SecondName
            public string SchoolName { get; set; }
            public string ClassName { get; set; }
            public int TestResult5 { get; set; }
        }
    }
    

    Program.cs的

    using Excel = Microsoft.Office.Interop.Excel;
    
    namespace so16092016
    {
        class Program
        {
            static void Main(string[] args)
            {
                resultsEntities context = new resultsEntities();
                ResultsRepository resultsRepository = new ResultsRepository(context);
                var ma_results = resultsRepository.GetTList().Where(x => x.SubjectCode == 2); //получить результаты по математике
    
                Excel.Application app = new Excel.Application();
                app.DisplayAlerts = false;
                Excel.Workbook book_template = app.Workbooks.Open(@"шаблон_отчета.xlsx");
                Excel._Worksheet sheet_template = book_template.Sheets["отчет"];
    
                foreach(var ob in ma_results)
                {
                    //1. Создаем объкт LearnerReport из БД
                    LearnerReport report = new LearnerReport
                    {
                        SNS = $"{ob.surname} {ob.name} {ob.SecondName}",
                        SchoolName = ob.SchoolName,
                        ClassName = ob.ClassName,
                        TestResult5 = ob.TestResult5                     
                    };
    
                    //2. Экспорт объкта LearnerReport в шаблон xlsx
                    sheet_template.Range["C4"].Value2 = report.SNS;
                    sheet_template.Range["C5"].Value2 = report.SchoolName;
                    sheet_template.Range["C6"].Value2 = report.ClassName;
                    sheet_template.Range["C9"].Value2 = report.TestResult5;
    
                    //3. Сохраняем полученный файл в .pdf на рабочем столе
                    string file_name = $@"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\{report.SNS}.pdf";
                    sheet_template.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, file_name);
                }
    
                book_template.Close(0);
                book_template = null;
                app.Quit();
                app = null;
            }
        }
    }
    

    我需要什么:应用程序运行良好,并为我提供正确的结果报告。但是你看到代码对OOP / SOLID不好。因此很难扩展。帮助我/显示正确的模式来完成这项任务:

    • 导出到.xls的逻辑必须是模型方法或需要创建 这个分开的班级经理?
    • 哪个必须通过数据库对象进行模型报告?

2 个答案:

答案 0 :(得分:2)

一种可能的改进是将导出逻辑提取到单独的服务:

static void Main(string[] args)
    {
        resultsEntities context = new resultsEntities();
        ResultsRepository resultsRepository = new ResultsRepository(context);
        var ma_results = resultsRepository.GetTList().Where(x => x.SubjectCode == 2); //получить результаты по математике

        IReportService reportService = new ExcelReportService();

        reportService.GenerateReport(ma_results);
    }

    public interface IReportService
    {
        void GenerateReport(IEnumerable<StudentDto> students);
    }

    public class ExcelReportService:IReportService
    {
        public void GenerateReport(IEnumerable<StudentDto> students)
        {
            Excel.Application app = new Excel.Application();
            app.DisplayAlerts = false;
            Excel.Workbook book_template = app.Workbooks.Open(@"шаблон_отчета.xlsx");
            Excel._Worksheet sheet_template = book_template.Sheets["отчет"];

            foreach (var ob in students)
            {
                //1. Создаем объкт LearnerReport из БД
                LearnerReport report = new LearnerReport
                {
                    SNS = $"{ob.surname} {ob.name} {ob.SecondName}",
                    SchoolName = ob.SchoolName,
                    ClassName = ob.ClassName,
                    TestResult5 = ob.TestResult5
                };

                //2. Экспорт объкта LearnerReport в шаблон xlsx
                sheet_template.Range["C4"].Value2 = report.SNS;
                sheet_template.Range["C5"].Value2 = report.SchoolName;
                sheet_template.Range["C6"].Value2 = report.ClassName;
                sheet_template.Range["C9"].Value2 = report.TestResult5;

                //3. Сохраняем полученный файл в .pdf на рабочем столе
                string file_name = $@"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\{report.SNS}.pdf";
                sheet_template.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, file_name);
            }

            book_template.Close(0);
            book_template = null;
            app.Quit();
            app = null;
        }
    }

答案 1 :(得分:1)

我认为以更容易编辑的格式保存Excel模板会更容易,而不像Excel那样

  • XML Spreadsheet 2003 (*.xml)
  • Single File Web Page (*.mht,*.mhtml)
  • Web Page (*.htm,*.html)

您可以在模板中使用占位符,例如{report.SNS},并在XML / HTML中替换它们,或者在Excel中替换为:

for(;;) 
{
    var cell = sheet_template.UsedRange.Find("{*}", Type.Missing, XlFindLookIn.xlValues, 
        XlLookAt.xlWhole, XlSearchOrder.xlByRows, XlSearchDirection.xlNext);

    if(cell == null) break; 

    var value = cell.Value2 as string;
    switch (value)
    {
        case "{report.SNS}": cell.Value2 = report.SNS; break;
     // case "{report.SchoolName}": .. etc.

        default: // log issue
    }
}