Exemplo n.º 1
0
        /// <summary>
        /// Parse xlsx sheet data into a list of dynamic objects
        /// it will search on given sheetname ( it not null ) or on any sheets ( if null )
        /// it will list for given columnNames ( if not null ) or for all columns ( if null )
        /// if columnNamesIgnoreCase result object will contains lowercase properties
        /// </summary>
        public static IEnumerable <ImportXlsxDataSheet> ParseXlsxData(this string xlsxPathfilename,
                                                                      string _sheetName            = null,
                                                                      bool sheetNameIgnoreCase     = true,
                                                                      HashSet <string> columnNames = null,
                                                                      bool columnNamesIgnoreCase   = true,
                                                                      string[] valid_sheetnames    = null)
        {
            var    wb        = new XLWorkbook(xlsxPathfilename);
            string sheetName = _sheetName;

            IXLWorksheet ws = null;

            if (sheetName == null)
            {
                foreach (var _ws in wb.Worksheets)
                {
                    if (valid_sheetnames != null && !valid_sheetnames.Any(r => r.ToLower() == _ws.Name.ToLower()))
                    {
                        continue;
                    }

                    yield return(new ImportXlsxDataSheet(_ws.Name, _ws.ParseXlsxData(columnNames, columnNamesIgnoreCase)));
                }
            }
            else
            {
                if (sheetNameIgnoreCase)
                {
                    sheetName = _sheetName.ToLower();
                    ws        = wb.Worksheets.FirstOrDefault(w => w.Name.ToLower() == sheetName);
                }
                else
                {
                    ws = wb.Worksheets.FirstOrDefault(w => w.Name == sheetName);
                }

                yield return(new ImportXlsxDataSheet(sheetName, ws.ParseXlsxData(columnNames, columnNamesIgnoreCase)));
            }
        }