Advertisement
isotonicq

Untitled

Apr 22nd, 2021
845
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Linq;
  4. using BST.ExcelImporter.Interfaces;
  5. using OfficeOpenXml;
  6. using ExcelRow = BST.ExcelImporter.Models.ExcelRow;
  7. using BST.ExcelImporter.Extensions;
  8.  
  9. namespace BST.ExcelImporter.Controllers
  10. {
  11.     public sealed class ReadFileController : IReadFileController
  12.     {
  13.         //Private
  14.         private readonly FileInfo _file;
  15.  
  16.         //CTOR
  17.         public ReadFileController(string path)
  18.         {
  19.             _file = new FileInfo(path);
  20.         }
  21.        
  22.         //Public
  23.         public ICollection<ExcelRow> Read()
  24.         {
  25.             //Prepare variables
  26.             ICollection<ExcelRow> result = new List<ExcelRow>();
  27.             List<string> headers = new List<string>();
  28.  
  29.             //Read file
  30.             using (ExcelPackage package = new ExcelPackage(_file))
  31.             {
  32.                 //Init excel values
  33.                 ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
  34.                 ExcelAddressBase dimensions = worksheet.GetValuedDimension();
  35.                
  36.                 int colCount = dimensions.End.Column;
  37.                 int rowCount = dimensions.End.Row;
  38.  
  39.                 //Get headers;
  40.                 for (int y = 1; y <= colCount; y++)
  41.                 {
  42.                     headers.Add(worksheet.Cells[1, y].Value.ToString());
  43.                 }
  44.                
  45.                 //Get values
  46.                 for (int x = 2; x <= rowCount; x++)
  47.                 {
  48.                     ExcelRow row = new ExcelRow();
  49.                    
  50.                     for (int y = 1; y <= colCount; y++)
  51.                     {
  52.                         row.Fields.Add(headers[y - 1], worksheet.Cells[x, y]);
  53.                     }
  54.                    
  55.                     result.Add(row);
  56.                 }
  57.             }
  58.            
  59.             //Return
  60.             return result;
  61.         }
  62.     }
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement