示例#1
0
        public void ReadEmployeeExcelFile_ShouldReturnCorrectResult()
        {
            // Arrange
            using var excelFileStream = File.Open(Path.Combine(Environment.CurrentDirectory + "\\MockData", "Employee.xlsx"), FileMode.Open, FileAccess.Read);

            // Act
            var results = new ExcelService().ReadEmployeeExcelFile(excelFileStream);

            // Assert
            Assert.Equal(3, results.Count);

            Assert.Equal("001", results[0].EmployeeNumber);
            Assert.Equal("John", results[0].FirstName);
            Assert.Equal("Doe", results[0].LastName);
            Assert.Equal("Regular", results[0].EmployeeStatus);

            Assert.Equal("002", results[1].EmployeeNumber);
            Assert.Equal("Jane", results[1].FirstName);
            Assert.Equal("Doe", results[1].LastName);
            Assert.Equal("Contractor", results[1].EmployeeStatus);

            Assert.Equal("003", results[2].EmployeeNumber);
            Assert.Equal("Harry", results[2].FirstName);
            Assert.Equal("Potter", results[2].LastName);
            Assert.Equal("Regular", results[2].EmployeeStatus);
        }
        public DemoDetailsViewModel(
            IDemosService demosService, IDialogService dialogService, ISteamService steamService,
            ICacheService cacheService, ExcelService excelService, IRoundService roundService)
        {
            _demosService  = demosService;
            _dialogService = dialogService;
            _steamService  = steamService;
            _cacheService  = cacheService;
            _excelService  = excelService;
            _roundService  = roundService;

            Sources = Source.Sources;

            if (IsInDesignMode)
            {
                DispatcherHelper.CheckBeginInvokeOnUI(async() =>
                {
                    Demo = await _cacheService.GetDemoDataFromCache(string.Empty);
                    PlayersTeam1Collection = CollectionViewSource.GetDefaultView(Demo.TeamCT.Players);
                    PlayersTeam2Collection = CollectionViewSource.GetDefaultView(Demo.TeamT.Players);
                    RoundsCollection       = CollectionViewSource.GetDefaultView(Demo.Rounds);
                });
            }

            Messenger.Default.Register <LoadDemoFromAppArgument>(this, HandleLoadFromArgumentMessage);
        }
示例#3
0
        /// <summary>
        ///     Exports only the selected item
        /// </summary>
        private void ExportSelectedItem()
        {
            List <ItemObject> templateList = new List <ItemObject>();

            templateList.Add(this.SelectedTemplate);
            ExcelService.CreateTemplateWorkbook(templateList);
        }
示例#4
0
        public JsonResult ExportAll()
        {
            var sql = @" select u.ID as UserId,u.Name as UserName,us.Score,us.CreateTime,us.UpdateTime  FROM [WaterSupplySecurity].[dbo].[UserScore] us inner join [dbo].[User] u on u.ID = us.UserID  ";

            var dt = DbHelperSQL.Query(sql).Tables[0];

            DataTable dtExport = new DataTable();

            dtExport.Columns.Add("用户ID");
            dtExport.Columns.Add("用户姓名");
            dtExport.Columns.Add("分数");
            dtExport.Columns.Add("开始时间");
            dtExport.Columns.Add("结束时间");

            foreach (DataRow d in dt.Rows)
            {
                DataRow drExport = dtExport.NewRow();
                drExport["用户ID"] = d["UserId"];
                drExport["用户姓名"] = d["UserName"];
                drExport["分数"]   = d["Score"];
                drExport["开始时间"] = d["CreateTime"].ToString();
                drExport["结束时间"] = d["UpdateTime"].ToString();
                dtExport.Rows.Add(drExport);
            }

            var msg = "";

            ExcelService.DataTableToExcel(dtExport, out msg, "所有分数汇总_" + DateTime.Now.ToString("yyyyMMddHHmmss"));

            return(Json("", JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        ///     Adds the selected field to the bottom of the excel columns
        /// </summary>
        public void AddFieldToExcelColumns()
        {
            string field = this.SelectedField;

            if (this.SelectedField == "-TEXT-")
            {
                TextPromptView textWindow = new TextPromptView
                {
                    DataContext = new TextPromptViewModel("Add Field", "Field", "string")
                };
                textWindow.ShowDialog();
                if (textWindow.DialogResult == true)
                {
                    field = '"' + (textWindow.DataContext as TextPromptViewModel).Field1Value + '"';
                }
                else
                {
                    return;
                }
            }

            ExcelCell newCell = new ExcelCell(
                this.ExcelId,
                this.ExcelColumns.Count + 1,
                field, "",
                this.ExcelCustomer,
                ExcelService.ReturnColumLetter(this.ExcelColumns.Count + 1));

            this.ExcelColumns.Add(newCell);
        }
示例#6
0
        private ConfigurarPlanilhaResponseViewModel ConfigurarPlanilha(string caminhoPlanilha)
        {
            ConfigurarPlanilhaResponseViewModel vm;

            try
            {
                _excelService = new ExcelService(caminhoPlanilha);
                IExcelService _excelServiceAD = new ExcelService(@"..\..\Resources\ad.xlsx");

                _ADService = new ADService(_excelServiceAD);
                var email = _authService.GetLoggedUser();
                var configurarPlanilhaRequestUseCase = new ConfigurarPlanilhaInteractor(_excelService, _ADService);
                var ConfigurarPlanilhaRequestMessage = new ConfigurarPlanilhaRequestMessage(email, "Horários");
                var responseMessage = configurarPlanilhaRequestUseCase.Handle(ConfigurarPlanilhaRequestMessage);
                var configurarPlanilhaResponsePresenter = new ConfigurarPlanilhaResponsePresenter();
                vm = configurarPlanilhaResponsePresenter.Handle(responseMessage);
            }
            catch (IOException ex)
            {
                vm = new ConfigurarPlanilhaResponseViewModel(false, "Feche a planilha de controle de ponto antes de iniciar o programa");
            }
            catch (Exception ex)
            {
                vm = new ConfigurarPlanilhaResponseViewModel(false, ex.Message);
            }

            return(vm);
        }
示例#7
0
        private void submit_Click(object sender, EventArgs e)
        {
            ExcelService calcSheet = new ExcelService();

            Status[]         outStatus;
            RangeCoordinates rangeCoordinates   = new RangeCoordinates();
            string           sheetName          = "Sheet1";
            string           targetWorkbookPath = "http://vsmoss/sites/intranet/Docs/Expense%20Calculators/Mileage%20Calculator.xlsx";

            calcSheet.Credentials = System.Net.CredentialCache.DefaultCredentials;

            try
            {
                string id = calcSheet.OpenWorkbook(
                    targetWorkbookPath, "en-US", "en-US", out outStatus);

                object rateCell = calcSheet.GetCell(
                    id, sheetName, 1, 1, true, out outStatus);
                calcSheet.SetCell(id, sheetName, 1, 0, mileage.Value);
                calcSheet.Calculate(id, sheetName, rangeCoordinates);
                object reimbursementCell = calcSheet.GetCell(
                    id, sheetName, 1, 2, true, out outStatus);

                rate.Text          = rateCell.ToString();
                reimbursement.Text = reimbursementCell.ToString();

                calcSheet.CloseWorkbook(id);
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }
示例#8
0
        public void CreateComponents_HasValues_ShouldMatch()
        {
            #region Assemble


            OptionService optionService = new OptionService(new TestOptionRepository(), new TestRequestRepository());
            ExcelService  excelService  = new ExcelService(true, new ItemService(new FakeWorkbookReader(), new TestItemRepository(), new TestTemplateRepository()), optionService, new TestTemplateRepository(), new TestRequestRepository());
            string        components    = "RP1234^RP2345(4)";
            string        components2   = "FR1234";
            string        components3   = "POD1234^RP1234";
            string        components4   = "POD1234^RP1234(S)";

            #endregion // Assemble

            #region Act

            string result1 = excelService.ModifyComponents(components);
            string result2 = excelService.ModifyComponents(components2);
            string result3 = excelService.ModifyComponents(components3);
            string result4 = excelService.ModifyComponents(components4);

            #endregion // Act

            #region Assert

            Assert.AreEqual("RP1234(1)^RP2345(4)", result1);
            Assert.AreEqual("FR1234(1)", result2);
            Assert.AreEqual("POD1234(1)^RP1234(1)", result3);
            Assert.AreEqual("POD1234(1)^RP1234(S)", result4);

            #endregion // Assert
        }
示例#9
0
        public void ReturnVariantGroupId_HasValues_ShouldMatch()
        {
            #region Assemble


            GlobalData.ClearValues();
            OptionService optionService = new OptionService(new TestOptionRepository(), new TestRequestRepository());
            ExcelService  excelService  = new ExcelService(true, new ItemService(new FakeWorkbookReader(), new TestItemRepository(), new TestTemplateRepository()), optionService, new TestTemplateRepository(), new TestRequestRepository());
            string        itemId1       = "RP1234";
            string        itemId2       = "FR1234";
            string        itemId3       = "POD1234";
            string        itemId4       = "FR1234BLK22X34";

            #endregion // Assemble

            #region Act

            string result1 = excelService.ReturnVariantGroupId(itemId1);
            string result2 = excelService.ReturnVariantGroupId(itemId2);
            string result3 = excelService.ReturnVariantGroupId(itemId3);
            string result4 = excelService.ReturnVariantGroupId(itemId4);

            #endregion // Act

            #region Assert

            Assert.AreEqual("1234", result1);
            Assert.AreEqual("1234", result2);
            Assert.AreEqual("1234", result3);
            Assert.AreEqual("1234", result4);

            #endregion // Assert
        }
示例#10
0
        public void WriteCellData()
        {
            var binExcel    = File.ReadAllBytes(@"test.xlsx");
            var base64Excel = Convert.ToBase64String(binExcel);

            var json = @"{
                ""Tabelle1!B3"":""This is a test too"",
                ""Tabelle2!A2"": 1234
            }";

            var data = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);

            using (var excelService = new ExcelService(base64Excel))
            {
                var actualResult = excelService.WriteCellData(data);
                // not a very goot assert
                Assert.NotEmpty(actualResult);

                var tempPath = Path.GetTempFileName() + ".xlsx";
                File.WriteAllBytes(tempPath, Convert.FromBase64String(actualResult));

                // check manually
                Console.WriteLine(tempPath);
            }
        }
示例#11
0
        public void ReturnNumberOfComponents_HasValues_ShouldMatch()
        {
            #region Assemble


            GlobalData.ClearValues();
            OptionService OptionService = new OptionService(new TestOptionRepository(), new TestRequestRepository());
            ExcelService  excelService  = new ExcelService(true, new ItemService(new FakeWorkbookReader(), new TestItemRepository(), new TestTemplateRepository()), OptionService, new TestTemplateRepository(), new TestRequestRepository());
            string        components    = "RP1234^RP2345(4)";
            string        components2   = "FR1234";
            string        components3   = "POD1234^RP1234";
            string        components4   = "POD1234^RP1234(S)";

            #endregion // Assemble

            #region Act

            string result1 = excelService.ReturnNumberOfComponents(components);
            string result2 = excelService.ReturnNumberOfComponents(components2);
            string result3 = excelService.ReturnNumberOfComponents(components3);
            string result4 = excelService.ReturnNumberOfComponents(components4);

            #endregion // Act

            #region Assert

            Assert.AreEqual("5", result1);
            Assert.AreEqual("1", result2);
            Assert.AreEqual("2", result3);
            Assert.AreEqual("2", result4);

            #endregion // Assert
        }
示例#12
0
        protected async Task ReadExcelFile(IMatFileUploadEntry[] files)
        {
            var file = files.FirstOrDefault();

            if (file == null)
            {
                ErrorMessage = "No File Found";
                return;
            }

            var filename = file.Name;

            if (!filename.Contains(".xls"))
            {
                ErrorMessage = "Invalid file format. Please use .xlsx or .xls file type.";
                StateHasChanged();
                return;
            }
            var playlistName = filename.Substring(0, filename.IndexOf("-", StringComparison.Ordinal));

            await AddNewPlaylist(playlistName);

            var videos = await ExcelService.Import(file);

            if (SelectedPlaylist == null)
            {
                return;
            }
            foreach (var video in videos)
            {
                await Database.AddVideoToPlaylist(video, SelectedPlaylist);
            }
        }
示例#13
0
        public int CreateTransformationSet(string userName, string setName, string fullPath)
        {
            TransformationSet set;
            List <TransformationViewModel> transformations = new List <TransformationViewModel>();

            IExcelService destFile = new ExcelService();

            destFile.InputFileName = fullPath;
            destFile.LoadData(userName, FileType.Destination);

            set = TransformationSet_Read(setName, userName);

            if (set == null)
            {
                set = CreateNewSet(userName, setName, transformations, destFile);
            }
            else
            {
                UpdateExistingSet(set, transformations, destFile);
            }

            int result = set.Id;

            return(result);
        }
示例#14
0
        public async Task <FileDto> SearchTendersToXLS(TenderSearchDto searchDto)
        {
            var currentUser = await _userService.GetCurrentUserAsync();

            var company = await _dataContext.Companies
                          .Include(c => c.Subscriptions)
                          .ThenInclude(s => s.Tariff)
                          .SingleOrDefaultAsync(c => c.Id == currentUser.Id);

            if (!company.Subscriptions?.Any(s => s.Active && s.EndDate > DateTime.Now.Date && s.Tariff.ExportToXL) ?? true)
            {
                throw new BusinessException("Выгрузка Exel не доступна. Продлить тариф можно в личном кабинете");
            }

            var query = await SearchTendersByPatternQuery(searchDto, auto : false);

            var results = await query.ToListAsync();

            using var stream = ExcelService.CreateTendersXLSXToStream(results);

            return(new FileDto()
            {
                Content = stream.ToArray(),
                ContentType = "application/vnd.ms-excel",
                Name = "Tenders.xlsx"
            });
        }
        public static void FormateDocument(string fileName, List <DealNumberInfo> reportList)
        {
            ExcelService excel = new ExcelService(fileName);

            int iRow = 2;

            foreach (var item in reportList)
            {
                excel.SetCells(iRow, "A", item.dealNumber);
                excel.SetCells(iRow, "B", item.auctionDate);
                excel.SetCells(iRow, "C", item.auctionNumber);
                excel.SetCells(iRow, "D", item.customerName);
                excel.SetCells(iRow, "E", item.lotCode);
                excel.SetCells(iRow, "F", item.supplierName);
                excel.SetCells(iRow, "G", item.finalPriceOffer);
                excel.SetCells(iRow, "H", item.debt);
                excel.SetCells(iRow, "I", item.traderName);
                excel.SetCells(iRow, "J", item.brokerName);

                iRow++;
            }

            excel.CloseWorkbook(true);
            excel.CloseExcel();
        }
示例#16
0
        public bool MakeSaveCopyOrder(Order orderImp, string whereImp)
        {
            order = orderImp;

            if (order == null || string.IsNullOrEmpty(whereImp))
            {
                return(false);
            }
            order = orderImp;
            where = whereImp;

            service = new ExcelService(where + "\\Заявка №" + orderImp.Auction.Number.Replace("/", "_") + ".xlsx");

            SetAuctionNo();
            SetAuctionDate();
            SetInitiator();
            SetMemberCode();
            SetExchangeProvisionSize();
            SetOrderDeadline();
            SetApplicantsDeadline();
            SetExchangeProvisionDeadline();
            SetBroker();
            SetOrderDate();
            SetLots();
            SetWarrantyLetterInfo();

            Close();

            return(true);
        }
示例#17
0
        public void HasColumnTest()
        {
            var reader = new ExcelService(xlsFile);

            Assert.True(reader.HasColumns(new string[] { "Region", "Area", "UserID" }));
            Assert.False(reader.HasColumns(new string[] { "RegionNo", "AreaNo", "UserIDNo" }));
        }
示例#18
0
        public void MapTest()
        {
            var reader  = new ExcelService(xlsFile);
            var service = new ExcelMap <SampleModel>(reader);
            var map     = service.Map();

            Assert.Collection(map,
                              x =>
            {
                Assert.Contains("MYMENSINGH", x.Region);
                Assert.Contains("MYMENSINGH", x.Area);
                Assert.Contains("13", x.UserId);
                Assert.Contains("MR.MD. SHAKHWAT HOSSAIN", x.Name);
                Assert.Contains("RSM", x.Designation);
            },
                              x =>
            {
                Assert.Contains("MYMENSINGH", x.Region);
                Assert.Contains("MYMENSINGH", x.Area);
                Assert.Contains("19", x.UserId);
                Assert.Contains("MR.REZAUL KARIM", x.Name);
                Assert.Contains("DSM", x.Designation);
            },
                              x =>
            {
                Assert.Contains("MYMENSINGH", x.Region);
                Assert.Contains("MYMENSINGH", x.Area);
                Assert.Contains("930", x.UserId);
                Assert.Contains("MR. ZINNATH ALI", x.Name);
                Assert.Contains("PSO", x.Designation);
            }

                              );
        }
        private static bool FillDocument(string fileName, List <LotsExtended> lotsExtended, string lotCode = "", decimal minimalPrice = 0, decimal startPrice = 0, bool withPDF = false)
        {
            IExcelService excel = new ExcelService(fileName);

            if (minimalPrice > 0)
            {
                decimal difference = 100 - ((startPrice - minimalPrice) / (startPrice / 100));
                foreach (var subItem in lotsExtended)
                {
                    subItem.endprice = subItem.price / 100 * difference;
                    subItem.endsum   = subItem.endprice * subItem.quantity;
                }
            }

            int iRow = 4;

            excel.SetCells(1, "A", "Техническая спецификация по лоту №" + lotCode);

            try {
                foreach (var item in lotsExtended)
                {
                    excel.SetCells(iRow, "A", item.serialnumber);
                    excel.SetCells(iRow, "B", item.name);
                    excel.SetCells(iRow, "C", item.unit);
                    excel.SetCells(iRow, "D", item.quantity);
                    excel.SetCells(iRow, "E", item.price);
                    excel.SetCells(iRow, "F", item.sum);
                    excel.SetCells(iRow, "G", item.country);
                    excel.SetCells(iRow, "H", item.techspec);
                    excel.SetCells(iRow, "I", item.terms);
                    excel.SetCells(iRow, "J", item.paymentterm);
                    excel.SetCells(iRow, "K", item.dks);
                    excel.SetCells(iRow, "L", item.contractnumber);
                    excel.SetCells(iRow, "M", item.endprice);
                    excel.SetCells(iRow, "N", item.endsum);

                    for (var i = 1; i < 15; i++)
                    {
                        excel.SetCellBorder(iRow, i);
                    }

                    iRow++;
                }
            } catch (Exception) { }

            excel.SetCells(iRow, "F", lotsExtended.Sum(l => l.sum));
            excel.SetCells(iRow, "N", lotsExtended.Sum(l => l.endsum));

            excel.SetPagesFit();

            if (withPDF)
            {
                excel.SaveAsPDF(fileName.Replace(".xlsx", ".pdf"), false);
            }

            excel.CloseWorkbook(true);
            excel.CloseExcel();

            return(true);
        }
示例#20
0
        private void LoadColumnNames(string filename, FileType fileType)
        {
            _SourceData      = new List <SourceViewModel>();
            _DestinationData = new List <TransformationViewModel>();

            IExcelService service = new ExcelService();

            service.InputFileName = filename;
            service.LoadData(UserName, fileType);

            if (fileType == FileType.Source)
            {
                foreach (string columnName in service.ColumnNames.Values)
                {
                    _SourceData.Add(new SourceViewModel {
                        ColumnName = columnName
                    });
                }
            }
            else
            {
                foreach (string columnName in service.ColumnNames.Values)
                {
                    _DestinationData.Add(new TransformationViewModel {
                        TransformationRule = "", TargetColumn = columnName
                    });
                }
            }
        }
示例#21
0
        private static void FillDocument()
        {
            // Open document
            excel = new ExcelService(fileName);

            // Fill document
            excel.SetCells(5, "A", ""); // Registral number
            excel.SetCells(5, "B", company.name);
            excel.SetCells(5, "C", company.bin);
            excel.SetCells(5, "D", ""); // RNN
            excel.SetCells(5, "E", company.govregnumber);
            excel.SetCells(5, "F", company.govregdate == null ? "Не указано" : ((DateTime)company.govregdate).ToShortDateString());
            excel.SetCells(5, "G", contract.number);
            excel.SetCells(5, "H", contract.agreementdate == null ? "" : ((DateTime)contract.agreementdate).ToShortDateString());
            excel.SetCells(5, "I", ""); // City
            excel.SetCells(5, "J", company.addressActual);
            excel.SetCells(5, "K", company.addressLegal);
            excel.SetCells(5, "L", company.directorPowers);
            excel.SetCells(5, "M", company.director);
            excel.SetCells(5, "N", ""); // City
            excel.SetCells(5, "O", company.bank);
            excel.SetCells(5, "P", company.bik);
            excel.SetCells(5, "Q", company.iik.Replace(" ", ""));

            // Save & close document
            excel.CloseWorkbook(true);
            excel.CloseExcel();
        }
示例#22
0
        private string Calculate(string sourcePath, string leaguePath)
        {
            var fasitFile        = Path.Combine(sourcePath, "Fasit.xlsx");
            var sourceDirctory   = Path.Combine(leaguePath, "Tippeforslag");
            var resultsDirectory = Path.Combine(leaguePath, "Resultat");

            var currentCulture = Thread.CurrentThread.CurrentCulture;

            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

            var correctResultsWorksheet = ExcelService.GetWorksheet(fasitFile);
            var tablePosistions         = GroupStage.GetTablePositions();

            // Fasit for sluttspill
            var results = GetResultsFromWorksheet(correctResultsWorksheet);

            // Regner ut poengsummene
            var scoresForAllUsers = new List <UserScore>();

            foreach (var participant in Directory.GetFiles(sourceDirctory, "*.xlsx*"))
            {
                AddParticipantScore(participant, correctResultsWorksheet, tablePosistions, results, sourceDirctory, scoresForAllUsers);
            }

            var json = new ResultFile().Create(scoresForAllUsers, resultsDirectory, _configuration);

            // reset old culture info
            Thread.CurrentThread.CurrentCulture = currentCulture;

            return(json);
        }
示例#23
0
        public ComputerGroupsViewModel()
        {
            OpenEditMemberOf = ReactiveCommand.CreateFromObservable(() => _dialogRequests.Handle(new DialogInfo(new EditMemberOfDialog(), _computer.Principal.SamAccountName)));

            SaveDirectGroups = ReactiveCommand.CreateFromObservable(() =>
            {
                var saveFileDialog = new SaveFileDialog {
                    Filter = ExcelService.ExcelFileFilter, FileName = _computer.CN
                };
                return(saveFileDialog.ShowDialog() ?? false ? ExcelService.SaveGroupsToExcelFile(_directGroups, saveFileDialog.FileName) : Observable.Return(Unit.Default));
            });

            FindDirectGroup = ReactiveCommand.CreateFromTask(() => NavigationService.ShowWindow <GroupWindow>(_selectedDirectGroup));

            this.WhenActivated(disposables =>
            {
                Observable.Merge(
                    this.WhenAnyValue(vm => vm.Computer).WhereNotNull(),
                    OpenEditMemberOf.Select(_ => Computer))
                .Do(_ => _directGroups.Clear())
                .SelectMany(computerObject => GetDirectGroups(computerObject, TaskPoolScheduler.Default))
                .Select(directoryEntry => directoryEntry.Properties.Get <string>("cn"))
                .ObserveOnDispatcher()
                .Subscribe(cn => _directGroups.Add(cn))
                .DisposeWith(disposables);

                Observable.Merge <(string Title, string Message)>(
                    OpenEditMemberOf.ThrownExceptions.Select(ex => (("Could not open dialog", ex.Message))),
                    SaveDirectGroups.ThrownExceptions.Select(ex => (("Could not save groups", ex.Message))),
                    FindDirectGroup.ThrownExceptions.Select(ex => (("Could not open group", ex.Message))))
                .SelectMany(dialogContent => _messages.Handle(new MessageInfo(MessageType.Error, dialogContent.Message, dialogContent.Title)))
                .Subscribe()
                .DisposeWith(disposables);
            });
        }
示例#24
0
        public static object PluralTest(Decimal LastPrice, string Code)
        {
            XlCall.Excel(XlCall.xlfVolatile, true);

            return(ExcelService.Test(LastPrice.ToString(), Code));
            //return (Code + "_" + Cotacao).ToString();
        }
示例#25
0
 /// <summary>
 ///     Run metods on viewmodel startup
 /// </summary>
 public void ExcelGeneratorStartUp()
 {
     this.ExcelLists      = ExcelService.RetrieveExcelLayoutNames();
     this.Fields          = ExcelService.RetrieveFieldValues();
     this.CustomerList    = ExcelService.RetrieveExcelCustomers();
     this.ProductTypeList = GlobalData.ProductGoups;
 }
示例#26
0
        public static object GetFinancialInstrumentData_ExactDate(string FinancialInstrumentHistoryField, string Code, double DoubleDate)
        {
            XlCall.Excel(XlCall.xlfVolatile, true);
            object Output = ExcelService.GetFinancialInstrumentData_New(FinancialInstrumentHistoryField, Code, DoubleDate, true);

            return(ConvertObjectOutput(Output));
        }
示例#27
0
        public void Update(object source, RoutedEventArgs eventArgs)
        {
            if (!ValidateUpdate())
            {
                return;
            }

            try
            {
                SetLoading(Visibility.Visible);
                var languageResources = ExcelService.Read(UpdateSelectedExcel);
                ResxService.Update(UpdateClassName, UpdateResxFolder, languageResources);

                var resxKeys  = ResxService.GetAllKeys(UpdateResxFolder);
                var excelKeys = new List <string>();
                foreach (var item in languageResources)
                {
                    excelKeys.AddRange(item.Values.Keys);
                    excelKeys = excelKeys.Distinct().ToList();
                }

                var(NotInA, NotInB) = CompareHelper.GetDifference(excelKeys, resxKeys);

                KeysNotInExcel = new ObservableCollection <string>(NotInA);
                KeysNotInResx  = new ObservableCollection <string>(NotInB);

                SetLoading(Visibility.Hidden);
            }
            catch (Exception ex)
            {
                ExceptionHandler(ex);
            }
        }
示例#28
0
        private void BtnEnviarRelatorio_Click(object sender, EventArgs e)
        {
            ExcelService exService = new ExcelService();
            EmailService emService = new EmailService();

            try
            {
                var anexo = exService.GerarPlanilha(txtCaminhoArq.Text);
                emService.SendEmail(txtEmailDestinario.Text, txtAssunto.Text,
                                    txtMensagem.Text, anexo);
            }
            catch
            {
                MessageBox.Show("Algo deu errado. T-T ");
            }

            finally
            {
                MessageBox.Show("Relatório enviado com sucesso! ^-^");
                txtMensagem.Text        = "";
                txtAssunto.Text         = "";
                txtCaminhoArq.Text      = "";
                txtEmailDestinario.Text = "";
            }
        }
示例#29
0
        public async Task Excel_File_Parses_ToDataBase_Correctly()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "Excel_File_Parses_ToDataBase_Correctly")
                          .Options;

            var openFileStream = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestTable.xlsx"));

            using (var context = new ApplicationDbContext(options))
            {
                var service = new ExcelService(context);
                await service.ImportSpreadSheetToDatabase(openFileStream);
            }

            // Use a separate instance of the context to verify correct data was saved to database
            using (var context = new ApplicationDbContext(options))
            {
                Assert.AreEqual(2, context.FirstTestEntities.Count());
                Assert.AreEqual(2, context.SecondTestEntities.Count());
                var firstItemEntity = await context.FirstTestEntities.FirstOrDefaultAsync(c => c.ItemId == 1);

                Assert.IsNotNull(firstItemEntity);
                Assert.AreEqual("Sheet1Col16Id1", firstItemEntity.Col16Item);
                var secondSheetSecondEntity = await context.SecondTestEntities.FirstOrDefaultAsync(c => c.ItemId == 22);

                Assert.IsNotNull(secondSheetSecondEntity);
                Assert.AreEqual("Sheet2Col11Id2", secondSheetSecondEntity.Col11Item);
            }
        }
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            this.ProgressText = "Searching for Item Updates...";
            List <string> itemIds = ItemService.RetrieveUpdateItemReportItemIds(ReportEndDate, ReportStartDate);

            int count = 1;

            foreach (string itemId in itemIds)
            {
                int num = count - 1;
                try
                {
                    this.Items.Add(ItemService.RetrieveItem(itemId, count));
                    this.ProgressText = "Retrieving item data for " + count + " of " + itemIds.Count.ToString();
                }
                catch (Exception ex)
                {
                    ErrorLog.LogError("Failed to Retrieve data for Item " + this.Items[num].ItemId + ".", ex.ToString());
                    break;
                }
                count++;
            }
            this.ProgressText = "Writing to excel sheet...";
            ExcelService.CreateItemWorkbook("**Item", this.Items, this.FilePath);
            this.ProgressText = "Report Complete";

            this.BackgroundWorkerState = "";
            this.BackgroundWorker      = new BackgroundWorker();
        }