/// <summary> /// Reads and returns the contents of the given file /// </summary> /// <param name="Path">Full path to file</param> /// <returns>Contents of file as an array</returns> public static object ReadFile(string Path) { if (!File.Exists(Path)) { return(Path + " does not exist"); } using (StreamReader r = new StreamReader(Path)) { ExcelList lines = new ExcelList(); string line = string.Empty; while ((line = r.ReadLine()) != null) { lines.Add(line); } r.Close(); return(lines.ToArray()); } }
private void OnButtonCommand(object obj) { var s = obj as string; if (s == "browse") { var dlg = new WPFFolderBrowser.WPFFolderBrowserDialog(); dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); var result = dlg.ShowDialog(); if (result == true) { FolderDestination = dlg.FileName; } } if (s == "export.excel") { Task.Run(() => ExportExcel()); } if (s == "reset") { DateFrom = null; DateTo = null; CreatedFrom = null; CreatedTo = null; RecordFrom = null; RecordTo = null; // ItemsList.Clear(); SelectedFile = null; Password = null; IsError = false; ErrorMessage = null; ExcelList.Clear(); } if (s == "cancel") { CancelToken.Cancel(); CancellationRequested = true; } if (s == "file") { IsError = false; ErrorMessage = null; var dlg = new OpenFileDialog(); dlg.DefaultExt = ".xlsx"; dlg.Filter = "Excel Files (.xls)|*.xlsx;*.xls;*.xlsm"; SelectedFile = dlg.ShowDialog() == true ? dlg.FileName : null; if (System.IO.File.Exists(SelectedFile)) { var result = GetExcel(SelectedFile); if (result.Item1) { ExcelList = new ObservableCollection <ClaimLine>(result.Item2); } } } }
public async Task <InsertExcelResult> Insert(IFormFile arquivo) { #region Variáveis GetAllImportsResult _GetAllImportsResult = new GetAllImportsResult(); InsertExcelResult _InsertExcelResult = new InsertExcelResult(); IMPORTACAO_EXCEL _IMPORTACAO_EXCEL = new IMPORTACAO_EXCEL(); List <EXCEL> oEXCEL = new List <EXCEL>(); #endregion try { #region Validações do Arquivo if (arquivo.Length == 0) { _InsertExcelResult.Retorno.Codigo = 1010; _InsertExcelResult.Retorno.Mensagem = "Arquivo está vazio"; return(_InsertExcelResult); } string fileExtension = Path.GetExtension(arquivo.FileName); if (fileExtension != ".xls" && fileExtension != ".xlsx") { _InsertExcelResult.Retorno.Codigo = 1020; _InsertExcelResult.Retorno.Mensagem = "Extensão do arquivo deve ser .xls/.xlsx"; return(_InsertExcelResult); } #endregion #region Importação Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); using (var stream = new MemoryStream()) { arquivo.CopyTo(stream); stream.Position = 0; using (var reader = ExcelReaderFactory.CreateReader(stream)) { long cont = 0; List <ExcelList> oExcelList = new List <ExcelList>(); while (reader.Read()) { if (cont > 0) { #region Validações dos registros //Linha com algum campo nulo if (reader.GetValue(0) == null || reader.GetValue(1) == null || reader.GetValue(2) == null || reader.GetValue(3) == null) { _InsertExcelResult.Retorno.Codigo = 1100; _InsertExcelResult.Retorno.Mensagem = $"Não foi possível importar planilha. Existem campos vazios. Linha {cont}"; return(_InsertExcelResult); } //DataEntrega DateTime.TryParse(reader.GetValue(0).ToString(), out DateTime dataEntrega); if (dataEntrega == default) { _InsertExcelResult.Retorno.Codigo = 1110; _InsertExcelResult.Retorno.Mensagem = $"Não foi possível importar planilha. Campo Data de Entrega está com formato inválido. Linha {cont}"; return(_InsertExcelResult); } if (dataEntrega <= DateTime.Now) { _InsertExcelResult.Retorno.Codigo = 1110; _InsertExcelResult.Retorno.Mensagem = $"Não foi possível importar planilha. Data de Entrega não pode ser menor que a data atual. Linha {cont}"; return(_InsertExcelResult); } //NomeProduto string nomeProduto = reader.GetValue(1).ToString(); if (nomeProduto.Length > 50) { _InsertExcelResult.Retorno.Codigo = 1120; _InsertExcelResult.Retorno.Mensagem = $"Não foi possível importar planilha. Nome do Produto excede o tamanho de 50 caracteres. Linha {cont}"; return(_InsertExcelResult); } //Quantidade int.TryParse(reader.GetValue(2).ToString(), out int quantidade); if (quantidade == 0) { _InsertExcelResult.Retorno.Codigo = 1130; _InsertExcelResult.Retorno.Mensagem = $"Não foi possível importar planilha. Quantidade não pode ser zero. Linha {cont}"; return(_InsertExcelResult); } //ValorUnitario decimal.TryParse(reader.GetValue(3).ToString(), out decimal valorUnitario); if (valorUnitario == 0) { _InsertExcelResult.Retorno.Codigo = 1130; _InsertExcelResult.Retorno.Mensagem = $"Não foi possível importar planilha. Valor Unitário não pode ser zero. Linha {cont}"; return(_InsertExcelResult); } #endregion ExcelList _ExcelList = new ExcelList(); _ExcelList.DataEntrega = dataEntrega; _ExcelList.NomeProduto = nomeProduto; _ExcelList.Quantidade = quantidade; _ExcelList.ValorUnitario = Math.Round(valorUnitario, 2); oExcelList.Add(_ExcelList); } cont++; } using (var transaction = _unitOfWork.BeginTransaction()) { try { _IMPORTACAO_EXCEL.DataImportacao = DateTime.Now; _IMPORTACAO_EXCEL.NomeArquivo = arquivo.FileName; _unitOfWork.Repository <IMPORTACAO_EXCEL>().Add(_IMPORTACAO_EXCEL); await _unitOfWork.SaveChanges(); oEXCEL = _mapper.Map <List <EXCEL> >(oExcelList); oEXCEL.Select(x => { x.Id = _IMPORTACAO_EXCEL.Id; return(x); }).ToList(); _unitOfWork.Repository <EXCEL>().AddRange(oEXCEL); await _unitOfWork.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); _InsertExcelResult.Retorno.Codigo = 1100; _InsertExcelResult.Retorno.Mensagem = $"Insert({arquivo.FileName})): {ex.Message}"; return(_InsertExcelResult); } } #region Repassa as informações para o retorno _InsertExcelResult.Id = _IMPORTACAO_EXCEL.Id; _InsertExcelResult.NomeArquivo = arquivo.FileName; _InsertExcelResult.DataImportacao = DateTime.Now; _InsertExcelResult.TotalRegistros = cont - 1; _InsertExcelResult.Retorno.Codigo = 200; _InsertExcelResult.Retorno.Mensagem = "Excel importado com sucesso"; _InsertExcelResult.Retorno.DataProcessamento = DateTime.Now; #endregion } } #endregion return(_InsertExcelResult); } catch (Exception ex) { _InsertExcelResult.Retorno.Codigo = 9999; _InsertExcelResult.Retorno.Mensagem = $"Insert({arquivo.FileName})): {ex.Message}"; return(_InsertExcelResult); } }