Esempio n. 1
0
        private ImportResult ReadXlsx(string filePath, int sheetIndex = 0, int maxRows = 0, bool headerRow = true)
        {
            var result = new ImportResult();

            IList <string[]> lstValues = new List <string[]>();

            try
            {
                var reader = new XlsxReader(filePath)
                {
                    CurrentSheet = sheetIndex
                };
                reader.ReadRecord();
                result.ColumnCount = reader.ColumnCount;

                if (headerRow && reader.RecordCount > 0)
                {
                    result.Columns = reader.Values;


                    for (int i = 1; i < reader.RecordCount && (maxRows <= 0 || i - 1 < maxRows); i++)
                    {
                        reader.ReadRecord();
                        lstValues.Add(reader.Values);
                    }
                }
                else if (!headerRow)
                {
                    for (int i = 0; i < reader.RecordCount && (maxRows <= 0 || i < maxRows); i++)
                    {
                        bool record = reader.ReadRecord();
                        lstValues.Add(reader.Values);
                    }
                }

                result.StatusMessage = string.Format(
                    "Operation completed on {0} record(s).  {1} Columns Detected",
                    reader.RecordCount,
                    reader.ColumnCount);
            }
            catch (Exception ex)
            {
                result.StatusMessage = string.Format("Exception thrown: {0}", ex.Message);
            }

            result.Values = lstValues;
            return(result);
        }