C# Read Excel Spreadsheet

Asked

Viewed 903 times

4

Hello, I have 1 problem reading an excel spreadsheet,

ListaNomes.Add(new Entidades() { GrupoFornecParceiro = rd["Grupo do Fornec./Parceiro+"].ToString() });

when it goes to Add the value of the column "Supplied Group./Partner+" it goes to the catch, I made the manual modification in the spreadsheet and removed the POINT"." and it worked, but I am automating a process, I do not want to open the spreadsheet and change the name to remove this point, there is some way to fix this problem?

I’ve tried to create a var a = @"Grupo do Fornec./Parceiro+" being like this

ListaNomes.Add(new Entidades() { GrupoFornecParceiro = rd["Grupo do Fornec./Parceiro+"].ToString() });

But to no avail.

try
{
    conexao.Open();
    OleDbDataReader rd = comando.ExecuteReader();

    while (rd.Read())
    {
        ListaNomes.Add(new Entidades() {ACN = rd["ACN"].ToString() });
        ListaNomes.Add(new Entidades() {CEP = rd["CEP"].ToString() });
        ListaNomes.Add(new Entidades() {CepContatoDireto = rd["CEP do Contato Direto"].ToString() });
        ListaNomes.Add(new Entidades() {Causa = rd["Causa"].ToString() });
        ListaNomes.Add(new Entidades() {CentroCusto = rd["Centro de Custo"].ToString() });
        ListaNomes.Add(new Entidades() {Cidade = rd["Cidade"].ToString() });
        ListaNomes.Add(new Entidades() {CidadeContatoDireto = rd["Cidade do Contato Direto"].ToString() });
        ListaNomes.Add(new Entidades() {Correio = rd["Correio"].ToString() });
        ListaNomes.Add(new Entidades() {CorreioContatoDireto = rd["Correio do Contato Direto"].ToString()});
        ListaNomes.Add(new Entidades() {CreateImpactedAreafromCustomer = rd["Create Impacted Area from Customer's Location*"].ToString()});
        ListaNomes.Add(new Entidades() {CriadoTemplate = rd["Criado do Template"].ToString()});
        ListaNomes.Add(new Entidades() {CriadoEm = rd["Criado em"].ToString()});
        ListaNomes.Add(new Entidades() {CriadoPor = rd["Criado por*"].ToString()});
        ListaNomes.Add(new Entidades() {CriarSolicitacao = rd["Criar Solicitação"].ToString()});
        ListaNomes.Add(new Entidades() {CodigoPaisContato = rd["Código de País do Contato Direto"].ToString()});
        ListaNomes.Add(new Entidades() {CodigoAreaContato = rd["Código de Área do Contato Direto"].ToString()});
        ListaNomes.Add(new Entidades() {DataAlvo = rd["Data Alvo"].ToString()});
        ListaNomes.Add(new Entidades() {DataInformada = rd["Data Informada+"].ToString() });
        ListaNomes.Add(new Entidades() {DataUltimaResolucao = rd["Data da Última Resolução"].ToString() });
        ListaNomes.Add(new Entidades() {DataFechamento = rd["Data de Fechamento"].ToString() });
        ListaNomes.Add(new Entidades() {DataResposta = rd["Data de Resposta+"].ToString() });
        ListaNomes.Add(new Entidades() {DateTimeResolucao = rd["DateTime de Resolução Requerida"].ToString() });
        ListaNomes.Add(new Entidades() {DepartamentoContato = rd["Departamento do Contato Direto"].ToString() });
        ListaNomes.Add(new Entidades() {Designado = rd["Designado+"].ToString() });
        ListaNomes.Add(new Entidades() {DetalhesAdicionais = rd["Detalhes Adicionais de Localização"].ToString() });
        ListaNomes.Add(new Entidades() {DetalhesLocalizacao = rd["Detalhes da Localização do Contato Direto"].ToString() });
        ListaNomes.Add(new Entidades() {EmailContato = rd["E-mail do Contato Direto"].ToString() });
        ListaNomes.Add(new Entidades() {Empresa = rd["Empresa"].ToString() });
        ListaNomes.Add(new Entidades() {EmpresaContato = rd["Empresa do Contato Direto"].ToString() });
        ListaNomes.Add(new Entidades() {Empresas = rd["Empresa*+"].ToString() });
        ListaNomes.Add(new Entidades() {EsforcoExpresso = rd["Esforço Expresso em Minutos"].ToString() });
        ListaNomes.Add(new Entidades() {EstadoProvincia = rd["Estado Província"].ToString() });
        ListaNomes.Add(new Entidades() {EstadoContato = rd["Estado do Contato Direto"].ToString() });
        ListaNomes.Add(new Entidades() {EventMessage = rd["Event Message"].ToString() });
        ListaNomes.Add(new Entidades() {Externo = rd["Externo:"].ToString() });
        ListaNomes.Add(new Entidades() {Fabricante = rd["Fabricante"].ToString() });
        ListaNomes.Add(new Entidades() {FabricanteR = rd["Fabricante (R)"].ToString() });
        ListaNomes.Add(new Entidades() {FlagBroadcast = rd["Flag de Broadcast Enviado"].ToString() });
        ListaNomes.Add(new Entidades() {FusoHorario = rd["Fuso Horário"].ToString() });
        ListaNomes.Add(new Entidades() {FusoHorarioContato = rd["Fuso Horário do Contato Direto"].ToString() });
        ListaNomes.Add(new Entidades() {GenericCatego = rd["Generic Categorization Tier 2"].ToString() });
        ListaNomes.Add(new Entidades() {GenericCatego2 = rd["Generic Categorization Tier 3"].ToString() });
        ListaNomes.Add(new Entidades() {GrupoDesignado = rd["Grupo Designado*+"].ToString() });
        ListaNomes.Add(new Entidades() {GrupoProprietario = rd["Grupo Proprietário+"].ToString() });
        ListaNomes.Add(new Entidades() { GrupoFornecParceiro = rd["Grupo do Fornec./Parceiro+"].ToString() });
        ListaNomes.Add(new Entidades() {GrupoSite = rd["Grupo do Site"].ToString() });    
        ListaNomes.Add(new Entidades() {GrupoSiteContato = rd["Grupo do Site do Contato Direto"].ToString() });    
        ListaNomes.Add(new Entidades() {HostName = rd["Host Name"].ToString() });    
        ListaNomes.Add(new Entidades() {IC = rd["IC+"].ToString() });    
        ListaNomes.Add(new Entidades() {IDAlerts = rd["ID Alerts 7,3,1"].ToString() });    
        ListaNomes.Add(new Entidades() {IDCorporativo = rd["ID Corporativo do Contato Direto"].ToString()  });    
        ListaNomes.Add(new Entidades() {IDPessoaContato = rd["ID da Pessoa de Contato Direto"].ToString()  });    
        ListaNomes.Add(new Entidades() {IDSolicitacao = rd["ID da Solicitação de Serviço"].ToString()  });    
        ListaNomes.Add(new Entidades() {IDIncidente = rd["ID do Incidente*+"].ToString()  });    
        ListaNomes.Add(new Entidades() {IDRegistro = rd["ID do Registro"].ToString()  });    
        ListaNomes.Add(new Entidades() {IDSiteContato = rd["ID do Site do Contato Direto"].ToString()  });    
        ListaNomes.Add(new Entidades() {ITComponent = rd["IT Component"].ToString()  });    
        ListaNomes.Add(new Entidades() {Impacto = rd["Impacto*"].ToString()  });    
        ListaNomes.Add(new Entidades() {InicialNome = rd["Inicial do Nome do Meio do Contato Direto"].ToString()  });    
        ListaNomes.Add(new Entidades() {Interno = rd["Interno:"].ToString()  });    
        ListaNomes.Add(new Entidades() {KickBackCount = rd["Kickback_Count"].ToString() });    
        ListaNomes.Add(new Entidades() {LastKickbackDate = rd["Last_Kickback_Date"].ToString()  });    
        ListaNomes.Add(new Entidades() {LocalizacaoMesa = rd["Localização da Mesa"].ToString()  });    
        ListaNomes.Add(new Entidades() {LocalizacaoMesaContato = rd["Localização da Mesa do Contato Direto"].ToString()  });    
        ListaNomes.Add(new Entidades() {ModeloVersao = rd["Modelo/Versão"].ToString() });    
        ListaNomes.Add(new Entidades() {ModeloVersaoR = rd["Modelo/Versão (R)"].ToString()  });    
        ListaNomes.Add(new Entidades() {ModificadoEM = rd["Modificado em"].ToString()  });    
        ListaNomes.Add(new Entidades() {ModificadoPor = rd["Modificado por"].ToString() });
        ListaNomes.Add(new Entidades() {MetodoResolucao = rd["Método de Resolução"].ToString()});
        ListaNomes.Add(new Entidades() {NomeContatoDireto = rd["Nome do Contato Direto"].ToString()});
        ListaNomes.Add(new Entidades() {NomeFornecedor = rd["Nome do Fornecedor"].ToString()});
        ListaNomes.Add(new Entidades() {NomeMeio = rd["Nome do Meio"].ToString()});
        ListaNomes.Add(new Entidades() {NomeProdutoR = rd["Nome do Produto (R)+"].ToString()});
        ListaNomes.Add(new Entidades() {NomeProduto = rd["Nome do Produto+"].ToString()});
        ListaNomes.Add(new Entidades() {Nome = rd["Nome+"].ToString()});
        ListaNomes.Add(new Entidades() {Notas = rd["Notas"].ToString()});
        ListaNomes.Add(new Entidades() {NTicketFornecedor = rd["N° do Ticket do Fornecedor"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoOP1 = rd["Nível de Categorização Operacional 1+"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoOP2 = rd["Nível de Categorização Operacional 2"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoOP3 = rd["Nível de Categorização Operacional 3"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoProdutoReso1 = rd["Nível de Categorização de Produto da Resolução 1"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoProdutoReso2 = rd["Nível de Categorização de Produto da Resolução 2"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoProdutoReso3 = rd["Nível de Categorização de Produto da Resolução 3"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoReso1 = rd["Nível de Categorização de Resolução 1"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoReso2 = rd["Nível de Categorização de Resolução 2"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoReso3 = rd["Nível de Categorização de Resolução 3"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoProduto1 = rd["Nível de Categorização do Produto 1"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoProduto2 = rd["Nível de Categorização do Produto 2"].ToString()});
        ListaNomes.Add(new Entidades() {NivelCategorizacaoProduto3 = rd["Nível de Categorização do Produto 3"].ToString()});
        ListaNomes.Add(new Entidades() {NumeroLocalContatoDireto = rd["Número Local do Contato Direto"].ToString()});
        ListaNomes.Add(new Entidades() {OlaemEspera = rd["OLA em Espera"].ToString()});
        ListaNomes.Add(new Entidades() {OrganizacaoContatoDireto = rd["Organização do Contato Direto"].ToString()});  
        ListaNomes.Add(new Entidades() {OrigemInformada = rd["Origem Informada"].ToString()});  
        ListaNomes.Add(new Entidades() {OrigemFechamento = rd["Origem do Fechamento"].ToString()});  
        ListaNomes.Add(new Entidades() {PapelGrupo = rd["Papel do Grupo de Suporte"].ToString()});  
        ListaNomes.Add(new Entidades() {Pais = rd["País"].ToString()});  
        ListaNomes.Add(new Entidades() {PaisContatoDireto = rd["País do Contato Direto"].ToString()});  
        ListaNomes.Add(new Entidades() {PrioridadeSLM = rd["Prioridade do SLM"].ToString()});  
        ListaNomes.Add(new Entidades() {Prioridade = rd["Prioridade*"].ToString()});  
        ListaNomes.Add(new Entidades() {Proprietario = rd["Proprietário"].ToString()});  
        ListaNomes.Add(new Entidades() {ProximaDataObjetivo = rd["Próxima Data Objetivo"].ToString()});  
        ListaNomes.Add(new Entidades() {RamalContato = rd["Ramal do Contato Direto"].ToString()});  
        ListaNomes.Add(new Entidades() {Regiao = rd["Região"].ToString()});  
        ListaNomes.Add(new Entidades() {RegiaoContato = rd["Região do Contato Direto"].ToString()});  
        ListaNomes.Add(new Entidades() {RequerAprovacao = rd["Requer Aprovação"].ToString()});  
        ListaNomes.Add(new Entidades() {RequestID = rd["Request ID"].ToString()});  
        ListaNomes.Add(new Entidades() {RequestID0 = rd["Request ID(0)"].ToString(), });  
        ListaNomes.Add(new Entidades() {ResolucaoJustificativa = rd["Resolução/Justificativa"].ToString()});  
        ListaNomes.Add(new Entidades() {Resposta = rd["Resposta"].ToString() });  
        ListaNomes.Add(new Entidades() {Rua = rd["Rua"].ToString() });
        ListaNomes.Add(new Entidades() {RuaContatoDireto = rd["Rua do Contato Direto"].ToString() });
        ListaNomes.Add(new Entidades() {SLAEspera = rd["SLA em Espera"].ToString() });    
        ListaNomes.Add(new Entidades() {SLMTag = rd["SLM Tag"].ToString() });    
        ListaNomes.Add(new Entidades() {ServerSerial = rd["ServerSerial"].ToString() });    
        ListaNomes.Add(new Entidades() {Servico = rd["Serviço*+"].ToString() });    
        ListaNomes.Add(new Entidades() {SetResolve = rd["Set_Resolve"].ToString() });    
        ListaNomes.Add(new Entidades() {SiteCliente = rd["Site do Cliente"].ToString() });    
        ListaNomes.Add(new Entidades() {SiteContato = rd["Site do Contato"].ToString() });    
        ListaNomes.Add(new Entidades() {SobrenomeContato = rd["Sobrenome do Contato Direto"].ToString() });    
        ListaNomes.Add(new Entidades() {Sobrenome = rd["Sobrenome+"].ToString() });    
        ListaNomes.Add(new Entidades() {Source = rd["Source"].ToString() });    
        ListaNomes.Add(new Entidades() {StatusTempoReal = rd["Status em Tempo Real do SLM"].ToString() });    
        ListaNomes.Add(new Entidades() {Status = rd["Status*"].ToString() });    
        ListaNomes.Add(new Entidades() {StatusPPL = rd["Status-PPL"].ToString()});    
        ListaNomes.Add(new Entidades() {StatusReasonHidden = rd["Status_Reason_Hidden"].ToString()});
        ListaNomes.Add(new Entidades() {Sumario = rd["Sumário*"].ToString()});
        ListaNomes.Add(new Entidades() {TelefoneCliente = rd["Telefone do Cliente*+"].ToString()});   
        ListaNomes.Add(new Entidades() {TelefoneContato = rd["Telefone do Contato+"].ToString()});   
        ListaNomes.Add(new Entidades() {TipoAssociacaoIncidente = rd["Tipo de Associação de Incidente"].ToString()});   
        ListaNomes.Add(new Entidades() {TipoCliente = rd["Tipo de Cliente"].ToString()});   
        ListaNomes.Add(new Entidades() {TipoClienteContatoDireto = rd["Tipo de Cliente(Contact Client Type)"].ToString()});   
        ListaNomes.Add(new Entidades() {TipoIncidente = rd["Tipo de Incidente*"].ToString()});   
        ListaNomes.Add(new Entidades() {TipoTicket = rd["Tipo de Ticket"].ToString()});   
        ListaNomes.Add(new Entidades() {UnknownUser = rd["UnknownUser"].ToString()});   
        ListaNomes.Add(new Entidades() {Urgencia = rd["Urgência*"].ToString()});   
        ListaNomes.Add(new Entidades() {IndiceSatisfacao = rd["Índice de Satisfação"].ToString()});   
        ListaNomes.Add(new Entidades() {UltimaDataConhecida = rd["Última Data Conhecida"].ToString()});   
    }
    if (ListaNomes.Count() > 0)
    {
        return ListaNomes;
    }
    else
    {
        return null;
    }
}
catch
{
    Console.WriteLine("Não Foi Possivel");
        return null;
}
  • I edited and this is the code

  • :P It didn’t have to be all the code, you can’t get around with the *

  • you say put "*" in place of "." ?

  • I just tried, unsuccessfully, it reaches the line and to, goes straight to the catch, returning me only Count = 44, has to return me more than 100

  • Get it, explain better exactly what you’re trying to do?

  • I have an excel spreadsheet, I remove data from it and send it to Database, it stores the data in a class called Entities that contains a string for each column, so that ends the while it will send to database, but my problem is in this code range 'List Names.Add(new Entities() { Grouplink = Rd["Group Supply./Partner+"].Tostring() });' , if I go in the spreadsheet manually and remove this POINT being only "Group Supply/Partner+, it takes value from this column

  • 2

    If you know the position of the columns, it would be easier to work with the index instead of the name... you could even create an Enum or configuration file with this mapping for when the model is changed in the future, also take a look at this post here https://stackoverflow.com/questions/41363492/Retrieve-data-from-excel-contains-a-special-char-using-oledb-c-Sharp

  • @Guilhermepalange, try to replace the . by #

  • @Georgewurthmann It worked! exactly as I wanted, thank you!

  • Who good @Guilhermepalange! Once I have some time I’ll put the answer here explaining the reason. I just wanted to make sure before that it would work. :)

Show 5 more comments

1 answer

2


In lines of Excel which are headers the dot (.) may cause some problems and it is replaced by the character of cowling (#).

To fix you can replace the character . for #:

GrupoFornecParceiro = rd["Grupo do Fornec#/Parceiro+"].ToString()

But the best way for you to fix this is to change your connection string from OLEDB. You must set HDR=No and you won’t have a problem with that. HDR that is to say Headers, then you’ll basically be defining that there are no headers.

"HDR=Yes;" indicates that the first row has column names (header), no information. "HDR=No;" indicates the opposite.

string connectionString = 
                string.Format(
                "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=1\";", 
                caminhoPlanilha);

I did some tests with special characters and the only character replaced was the point (.) same. I tried to find a reliable source to put as reference and so already list other characters where this may occur, but I did not find. Anyway I will leave at the end some references that can be useful.

Just evaluate if this is the best way to access your columns, as you have already commented in the question, maybe it is more interesting to use the column index instead of the name:

ListaNomes.Add(new Entidades() {ACN = rd[1].ToString() });
ListaNomes.Add(new Entidades() {CEP = rd[2].ToString() });
ListaNomes.Add(new Entidades() {CepContatoDireto = rd[3].ToString() });
ListaNomes.Add(new Entidades() {Causa = rd[4].ToString() });

If your model doesn’t usually change, maybe the indexes will be better in this case.

If for some reason you have to go by the column name note that whenever you fail to search for a column by name you can access its index to verify its name.

Here you can see an example on Github that accesses columns with several special characters and prints their names using the HDR=Yes. In the same example has the connection with the HDR=No that corrects the problem.

References:

  1. https://stackoverflow.com/q/20687817/5522115
  2. https://www.connectionstrings.com/excel/
  3. https://www.codeproject.com/Articles/37055/Working-with-MS-Excel-xls-xlsx-Using-MDAC-and-Oled
  • 1

    Boy, you helped me a lot, pure knowledge that just passed me, I’m very grateful for your help and your attention, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.