using ExcelDataReader; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOB_UT_NEXT { /// /// Gestione lettura excel: /// https://github.com/ExcelDataReader/ExcelDataReader /// public class ExcelMan { protected string _path { get; set; } = ""; /// /// Avvio componente x il file indicato /// /// public ExcelMan(string filePath) { // verifico esistenza file... if (File.Exists(filePath)) { _path = filePath; } } public DataSet getDataSet() { DataSet result = new DataSet(); using (var stream = File.Open(_path, FileMode.Open, FileAccess.Read)) { // Auto-detect format, supports: // - Binary Excel files (2.0-2003 format; *.xls) // - OpenXml Excel files (2007 format; *.xlsx, *.xlsb) using (var reader = ExcelReaderFactory.CreateReader(stream)) { // 2. Use the AsDataSet extension method //result = reader.AsDataSet(); // The result of each spreadsheet is in result.Tables // modalità lettura con intestazione result = reader.AsDataSet(new ExcelDataSetConfiguration() { ConfigureDataTable = (_) => new ExcelDataTableConfiguration() { UseHeaderRow = true } }); #if false result = reader.AsDataSet(); #endif } } return result; } public IExcelDataReader getExcelReader() { // ExcelDataReader works with the binary Excel file, so it needs a FileStream // to get started. This is how we avoid dependencies on ACE or Interop: FileStream stream = File.Open(_path, FileMode.Open, FileAccess.Read); // We return the interface, so that IExcelDataReader reader = null; try { if (_path.EndsWith(".xls")) { reader = ExcelReaderFactory.CreateBinaryReader(stream); } if (_path.EndsWith(".xlsx")) { reader = ExcelReaderFactory.CreateOpenXmlReader(stream); } return reader; } catch (Exception) { throw; } } public IEnumerable getWorksheetNames() { var reader = this.getExcelReader(); var workbook = reader.AsDataSet(); var sheets = from DataTable sheet in workbook.Tables select sheet.TableName; return sheets; } public IEnumerable getData(string sheet, bool firstRowIsColumnNames = true) { var reader = this.getExcelReader(); //reader.IsFirstRowAsColumnNames = firstRowIsColumnNames; var workSheet = reader.AsDataSet().Tables[sheet]; var rows = from DataRow a in workSheet.Rows select a; return rows; } } }