示例#1
0
        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <param name="fileStream">excel文件流</param>
        /// <param name="ext">excel后缀</param>
        /// <param name="importBook">导入模型</param>
        /// <param name="outPutErrorStream">错误输出流</param>
        /// <returns>导入结果</returns>
        public ImportResult ImportExcel(Stream fileStream, ExtEnum ext, ImportBook importBook, Stream outPutErrorStream = null)
        {
            var ret    = new ImportResult();
            var sheets = importBook.Sheets.Select(m => this.CreateResultSheetInstance(m.GetType().GenericTypeArguments[0], m)).ToArray();

            ret.SetSheets(sheets);
            IWorkbook workbook;

            try
            {
                workbook = WorkbookGenerator.GetIWorkbook(fileStream, ext);
            }
            catch (Exception ex)
            {
                ret.SetBookFormatErrorMessage(ex.Message, ex);
                return(ret);
            }

            var errorStyleGenerator = new ImporterErrorStyleGenerator(workbook, importBook.DataErrorForegroundColor, importBook.RepeatedErrorForegroundColor, importBook.DefaultForegroundColor);

            for (var i = 0; i < workbook.NumberOfSheets; i++)
            {
                var sheet      = workbook.GetSheetAt(i);
                var sheetModel = ret.Sheets.FirstOrDefault(m => m.SheetIndex == i || m.SheetName == sheet.SheetName);
                if (sheetModel == null)
                {
                    continue;
                }

                sheetModel.SheetIndex = i;
                sheetModel.SheetName  = sheet.SheetName;

                this.ParseSheetToModel(sheet, sheetModel);
                if (outPutErrorStream != null)
                {
                    errorStyleGenerator.InitStyle(sheet, sheetModel.HeaderRowIndex);
                    errorStyleGenerator.SetErrorStyle(sheet, sheetModel);
                }
            }

            if (outPutErrorStream != null)
            {
                workbook.Write(outPutErrorStream);
            }

            return(ret);
        }