using System; using System.IO; using CsvHelper; using CsvHelper.Configuration; using CsvHelper.Excel; namespace InventoryTraker.Web.Utilities { public class ExcelParserBase : IDisposable { protected readonly CsvReader CsvReader; protected ExcelParserBase(FileSystemInfo excelFile, CsvConfiguration csvConfiguration) { CsvReader = OpenExcel(excelFile, csvConfiguration); } protected ExcelParserBase(FileSystemInfo excelFile) : this(excelFile, new CsvConfiguration { HasHeaderRecord = false, IgnoreBlankLines = false, IgnoreReadingExceptions = true }) { } internal static CsvReader OpenExcel(FileSystemInfo excelFile, CsvConfiguration csvConfiguration = null) { if (!excelFile.Exists) throw new FileNotFoundException($"Cannot find file '{excelFile.Name}'"); var excelParser = csvConfiguration != null ? new ExcelParser(excelFile.FullName, csvConfiguration) : new ExcelParser(excelFile.FullName); return new CsvReader(excelParser); } protected string[] GetNextCsvRowValues() { // get values from row if (!CsvReader.Read()) return null; return CsvReader.CurrentRecord; } public void Dispose() { CsvReader.Dispose(); } } }