简体   繁体   中英

Efficiency. DataTable or Worksheet? Using interop C#

I am working on a project and I am looking for efficiency , I have a DataTable that I convert in a excel file and I can treat using Interop . What I am looking for in this project is to add all the values that a father has. For example, the father of the values in red blood cells are " COSC-1218-SIT41SCH ". I have to do this with thousands of rows ...

在此处输入图片说明

So, when I try to do it iterating over DataTable or Worksheet , I have to wait like 10-25 minutes and that's a lot for me. Is there another way to get these values ? Any recommendation? If you want to see the code, I can publish it.

This is my code

for (int j = 1; j <= usedRange.Rows.Count; j++)
            {
                for (int i = 1; i <= usedRange.Columns.Count; i++)
                {

                    if (Convert.ToString(usedRange.Cells[j, i].Value) == "Peso Total")
                    {
                        colPT = i;
                    }
                    if (Convert.ToString(usedRange.Cells[j, i].Value) == "Peso Unitario")
                    {
                        colPU = i;
                        filaPU = j;
                    }
                    if (Convert.ToString(usedRange.Cells[j, i].Value) == "Cantidad Total")
                    {
                        colCantidadTotal = i;
                    }
                    if (j > 1)
                    {
                        System.Diagnostics.Debug.WriteLine(" Obteniendo nivel actual ... ");
                        //almaceno en lact el nivel de la celda actual
                        lact = Convert.ToInt32(usedRange.Cells[j,posNivel2].Value());
                        System.Diagnostics.Debug.WriteLine(" Nivel actual obtenido, es: " + lact);
                    }
                    //almaceno el valor de la celda actual en valCel
                    valCel = Convert.ToString(usedRange.Cells[j, i].Value);

                    //Obtengo la dirección de la celda actual, por ejemplo Q7
                    dirCelda = CellAddress(Worksheet, j, i);

                    System.Diagnostics.Debug.WriteLine("******* Exportando a Excel, el valor actual de la celda es: | info pruebas ValCell contiene -> " + valCel + " y la dirección es: " + rng.Address + " la j fila es: " + j + " y la i columna es: " + i + " -------- " + dirCelda + " el límite de columnas es : " + usedRange.Columns.Count + " y de filas es: " + usedRange.Rows.Count);

                    xz = Convert.ToString(usedRange.Cells[j+1,posNivel2].Value);
                    System.Diagnostics.Debug.WriteLine(" Probaaaaaaaaando, posnivel es: " + posNivel2 + " y xz contiene: " + xz);

                    //bucle Peso Total, j diferente a 1 para no acceder a la cabecera y no sobrepasar las filas con j+1
                    if (j!=1 && j + 1 < usedRange.Rows.Count)
                    {
                        System.Diagnostics.Debug.WriteLine(" === CheckPnt 0: ");
                        if (Convert.ToInt32(usedRange.Cells[j + 1,posNivel2].Value) < usedRange.Rows.Count)
                        {
                            //Obtengo el nivel de la siguiente fila
                            levelmas = Convert.ToInt32(usedRange.Cells[j + 1,posNivel2].Value);
                            System.Diagnostics.Debug.WriteLine(" === CheckPnt 1, levelactual es: " + lact + " levelmas:" + levelmas + " J es:" + j + " y RowCounts es " + usedRange.Rows.Count);
                        }
                        //si el nivel actual más 1 es igual al nivel de la fila siguiente y no se supera el límite de filas
                        if ((lact + 1) == levelmas && j + 1 < usedRange.Rows.Count)
                        {
                            System.Diagnostics.Debug.WriteLine(" === CheckPnt 2: ");
                            dirCelda = CellAddress(Worksheet, j, i);
                            formulaPadre = "=(";
                            int iterador = j + 1;
                            bool encontr = false;
                            //se crea iterador y se recorren las filas hasta que se encuentre una del mismo nivel
                            while (iterador < usedRange.Rows.Count && !encontr)
                            {
                                System.Diagnostics.Debug.WriteLine(" === Bucle While");
                                //si la siguiente fila tiene un nivel más que el padre se añade la celda
                                if ((lact + 1) == Convert.ToInt32(usedRange.Cells[iterador,posNivel2].Value))
                                {
                                    System.Diagnostics.Debug.WriteLine(" === CheckPnt 3: ");
                                    //si quiero quitar el primer + evaluar si es el primero
                                    formulaPadre = formulaPadre + "+" + CellAddress(Worksheet, iterador, colPT); // getCellNamev2(iterador, colPT);
                                }
                                //si se encuentra una fila con el mismo nivel se para y se añade el paréntesis final
                                if ((lact + 1) > Convert.ToInt32(usedRange.Cells[iterador,posNivel2].Value) || iterador + 1 == RowsCount)
                                {
                                    formulaPadre = formulaPadre + ")";
                                    encontr = true;
                                    //si encontrado encontes almaceno la fórmula en la columna peso total y reinicio fórmula
                                    //colPT es columna Peso Total
                                    System.Diagnostics.Debug.WriteLine(" Fin hijos se añade el último paréntesis y la fórmula es: " + formulaPadre);
                                    usedRange.Cells[j, colPT] = formulaPadre;
                                    System.Diagnostics.Debug.WriteLine("Cells de Fórmula Padre contine: " + Cells[j,colPT].ToString());
                                    formulaPadre = "";

                                }
                                iterador++;
                            }

                        }
                        else
                        {
                            //Si no es padre se múltiplica cantidad x Peso Unitario
                            System.Diagnostics.Debug.WriteLine(" NO es padre, aplico la otra fórmula");
                            //celdaPesoTotal = getCellNamev2(j, i);
                            celdaCantidad = CellAddress(Worksheet, j, colCantidadTotal); //getCellNamev2(j, colCantidadTotal);

                            celdaPesoUnitario = CellAddress(Worksheet, j, colPU); //getCellNamev2(filaPU, colPU);
                            formulaHijo = "=" + celdaCantidad + "*" + celdaPesoUnitario;
                            System.Diagnostics.Debug.WriteLine(" -__--__-----> La fórmula del Peso Total para el level 2 es: " + formulaHijo);
                            usedRange.Cells[j, colPT] = formulaHijo;
                        }
                    }
                }
            }

You could simply create a List<> for each column and iterate trough the list and simply check if your list element x with the values of nivel2 you want to select has your desired value at the same index.

You can convert your DataTable to a list with something like

List<string> list = dtusers.AsEnumerable()
                           .Select(r=> r.Field<string>("ColumnName"))
                           .ToList();

But there are also a lot of other possibilities to convert the DataTable to a list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM