将模型导出为.xlsx符合SOLID原则

将模型导出为.xlsx符合SOLID原则

问题描述:

对不起我的英语请!将模型导出为.xlsx符合SOLID原则

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

dbo.Result enter image description here

二表中有关于学校只是信息:

dbo.School
enter image description here

这样的记录可能会是40.000-70.000。最后我需要得到报告文件(PDF)是这样的:

enter image description here

我的解决办法:

  1. 创建Excel的寺庙;
  2. 从数据库导入数据并导出到Excel-temple中;
  3. 另存为.pdf;
  4. 然后步骤1为每个记录(人)。

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 = [email protected]"{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必须模型的方法或需要创建 分离类经理呢?
  • 哪必须通过数据库对象进行模型报告?
+0

你知道什么思考?你总是可以创建一个接受一个对象或一个对象列表的导出类,利用反射来建立属性名称和值.. http://stackoverflow.com/questions/30756869/c-sharp-generic-excel-exporter-使用反射 – Adam

+0

也检查此链接(从上面的链接),别人已经完成了辛苦的工作,所以你不必:) http://epplus.codeplex.com/ – Adam

+0

你也可以看看SQL Server报表生成器和SSRS https://msdn.microsoft.com/zh-cn/library/dd255291.aspx – Slai

的一个可能的改进是出口逻辑提取到单独的服务:

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 = [email protected]"{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; 
     } 
    } 

我认为这将是更容易保存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 
    } 
} 
+0

我同意 - 这将很容易和快速。但编辑后,我可以将XML转换为PDF?有时我会在我的excel模板中使用图表。无论如何,我必须使用Excel应用程序,不是吗? – adamshakhabov

+0

@adamshakhabov如果使用依赖于这些值的图表或其他动态内容,那么最简单的方法可能是在Excel中打开以转换为pdf。还有其他方法可以在不使用Excel的情况下转换为pdf格式,但我不知道推荐。 – Slai