Ejemplo n.º 1
0
        /// <summary>
        /// Main run method for performing our calculations and storing data.
        /// </summary>
        /// <param name="cancelToken">The cancel token.</param>
        public void Run(CancellationTokenSource cancelToken)
        {
            string fullFileName = AbsoluteFileName;

            if (fullFileName != null && File.Exists(fullFileName))
            {
                // Open the file
                FileStream stream = File.Open(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read);

                // Create a reader.
                IExcelDataReader excelReader;
                if (Path.GetExtension(fullFileName).Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
                {
                    throw new Exception("EXCEL file must be in .xlsx format. Filename: " + fullFileName);
                }
                else
                {
                    // Reading from a OpenXml Excel file (2007 format; *.xlsx)
                    excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }

                // Read all sheets from the EXCEL file as a data set
                // excelReader.IsFirstRowAsColumnNames = true;
                DataSet dataSet = excelReader.AsDataSet(new ExcelDataSetConfiguration()
                {
                    ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                    {
                        UseHeaderRow = true
                    }
                });

                // Write all sheets that are specified in 'SheetNames' to the data store
                foreach (DataTable table in dataSet.Tables)
                {
                    bool keep = StringUtilities.IndexOfCaseInsensitive(this.SheetNames, table.TableName) != -1;
                    if (keep)
                    {
                        TruncateDates(table);
                        StorageWriter.WriteTable(table);
                    }
                }

                // Close the reader and free resources.
                excelReader.Close();
            }
            else
            {
                throw new ApsimXException(this, string.Format("Unable to read Excel file '{0}': file does not exist.", fullFileName));
            }
        }