C #: How to identify worksheet title

2

Hi, I'm working on an excel-to-txt converter and I've been trying to make an algorithm where it detects the column title and returns an error if the column had the same title, to identify only the title?

In this algorithm it only compares the column and row and returns the column error and equal row.

for (int i = 0; i < dsPlan1.Tables[0].Columns.Count; i++) //todo: dispara a contagem da quantidade de tabelas
            {
                try
                {
                    if (!TestaCampos(dsPlan1.Tables[0].Rows[0][i].ToString()))
                    {
                        try
                        {
                            if (dsPlan1.Tables[0].Rows[0][i].ToString() != "" )
                            {
                                cmps.Add(dsPlan1.Tables[0].Rows[0][i].ToString());
                            }
                            else
                            {
                                //erro.SetErro(38);
                                throw new Exception();
                            }
                        }
                        catch (Exception)
                        {

                            string txt = null;
                            i++; //Moacir 28062017 - soma 1 no contador para igualar a coluna do excel para visualização do usuário
                            txt += "Coluna " + dsPlan1.Tables[0].Columns.IndexOf(dsPlan.Tables[0].Columns[i].ColumnName);
                            txt += " com nome vazio no arquivo! Favor verificar!";
                            MessageBox.Show(txt, "", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }

                    }
                    else
                    {
                        throw new Exception();
                    }
                }
                catch
                {
                    string txt = null;
                    txt += "Coluna " + dgvMostrar.Rows[0].Cells[i].Value.ToString();
                    txt += " em duplicidade no arquivo! Favor verificar!";
                    MessageBox.Show(txt, "", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
    
asked by anonymous 03.07.2017 / 17:34

1 answer

1

I've decided to re-write your algorithm. From the moment you can get the name of the columns you can check for duplicate columns as follows

var nomeDasColunas = dsPlan1.Tables[0].Rows[0].Select(r => r.ToString());
var haColunaSemNome = nomeDasColunas.Any(n => string.IsNullOrEmpty(n));
if(haColunaSemNome){
    //erro.SetErro(38);
    throw new Exception();
}
var colunaDuplicada = nomeDasColunas.GroupBy(n => n)
    .FirstOrDefault(g => g.Count() > 1)?.Key;
if(colunaDuplicada != null){
    var txt = "Coluna " + colunaDuplicada
        + " em duplicidade no arquivo! Favor verificar!";
    MessageBox.Show(txt, "", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
    
07.07.2017 / 00:44