Esempio n. 1
0
        private ExcelProviderAttribute GetExcelProviderAttribute(INamedTypeSymbol classSymbol)
        {
            var attributes = classSymbol.GetAttributes()
                             .Single(x => x.AttributeClass !.ToDisplayString() == ExcelProviderAttribute.TypeFullName)
                             .NamedArguments;

            var templatePathAtt  = attributes.FirstOrDefault(x => x.Key == nameof(ExcelProviderAttribute.TemplatePath));
            var sheetPositionAtt = attributes.FirstOrDefault(x => x.Key == nameof(ExcelProviderAttribute.SheetPosition));
            var sheetNameAtt     = attributes.FirstOrDefault(x => x.Key == nameof(ExcelProviderAttribute.SheetName));

            var templatePath  = templatePathAtt.Value.Value.ToString();
            var sheetPosition = sheetPositionAtt.Value.Value.ToInt32Safe();
            var sheetName     = sheetNameAtt.Value.Value.ToStringSafe();

            var result = new ExcelProviderAttribute();

            result.TemplatePath = templatePath;
            result.SheetName    = sheetName;
            if (sheetPosition.HasValue)
            {
                result.SheetPosition = sheetPosition.Value;
            }
            return(result);
        }
Esempio n. 2
0
        private static IEnumerable <FieldMapInfo> GetExcelColumns(INamedTypeSymbol classSymbol, ExcelProviderAttribute attributes)
        {
            var templatePath = attributes.TemplatePath;

            if (!File.Exists(templatePath))
            {
                var location = classSymbol.Locations.FirstOrDefault();
                var basePath = string.IsNullOrWhiteSpace(location?.GetLineSpan().Path) ? "" : Path.GetDirectoryName(location.GetLineSpan().Path);
                templatePath = Path.Combine(basePath, templatePath);
                if (!File.Exists(templatePath))
                {
                    throw new ArgumentException($"Excel template file not found: {attributes.TemplatePath}");
                }
            }

            using var workbook = ExcelExtensions.OpenWorkbook(templatePath);
            var sheet = attributes.SheetName.IsNullOrEmpty()
                ? workbook.Worksheet(attributes.SheetPosition)
                : workbook.Worksheet(attributes.SheetName);

            for (var i = 1; i <= sheet.ColumnUsedCount(); i++)
            {
                var headerCell = sheet.Row(1).Cell(i);
                yield return(new FieldMapInfo
                {
                    SourceName = headerCell.Value.ToString(),
                    PropertyName = headerCell.Value.ToString().Replace(" ", ""),
                    DataType = GetFieldDataType(sheet, i)
                });
            }
        }