Created
November 18, 2015 14:53
-
-
Save amogram/a17952294d638127de30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using ExcelImporter.Util.XmlModel; | |
using OfficeOpenXml; | |
using OfficeOpenXml.Table; | |
namespace ExcelImporter.Util.ExcelReader | |
{ | |
public class ExcelReader | |
{ | |
private readonly string _fileLocation; | |
public ExcelReader(string fileLocation) | |
{ | |
if (fileLocation == null) | |
{ | |
throw new ArgumentNullException(nameof(fileLocation)); | |
} | |
_fileLocation = fileLocation; | |
} | |
public void ReadFile() | |
{ | |
// Get the file we are going to process | |
var existingFile = new FileInfo(_fileLocation); | |
// Open and read the xlsx file. | |
using (var package = new ExcelPackage(existingFile)) | |
{ | |
// Get the work book in the file | |
var workbook = package.Workbook; | |
if (workbook?.Worksheets.Count > 0) | |
{ | |
// Get the first worksheet | |
ExcelWorksheet currentWorksheet = workbook.Worksheets.First(); | |
// Get Tables from the first worksheet | |
var table = currentWorksheet.Tables["SiteStructure"]; | |
if (table != null) | |
{ | |
// read le table | |
GetSiteStructureTable(table); | |
} | |
} | |
} | |
} | |
public ExcelModel.ExcelModel GetExcelModel() | |
{ | |
var model = new ExcelModel.ExcelModel(); | |
// magic happens here | |
return model; | |
} | |
private static void GetSiteStructureTable(ExcelTable table) | |
{ | |
var sites = new List<Site>(); | |
var address = table.Address; | |
var cells = table.WorkSheet.Cells; | |
var firstRow = address.Start.Row; | |
if (table.ShowHeader) | |
{ | |
firstRow++; | |
} | |
var lastRow = address.End.Row; | |
for (int row = firstRow; row <= lastRow; row++) | |
{ | |
sites.Add(new Site | |
{ | |
Title = cells[row, table.Columns["Site Title"].Id].Value.ToString(), | |
Description = cells[row, table.Columns["Description"].Id].Value.ToString(), | |
Url = cells[row, table.Columns["Url"].Id].Value.ToString(), | |
Template = cells[row, table.Columns["Template"].Id].Value.ToString() | |
}); | |
} | |
#if DEBUG | |
foreach (var site in sites) | |
{ | |
Console.WriteLine($"{site.Title} | {site.Description} | {site.Url} | {site.Template}"); | |
} | |
#endif | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment