Example #1
0
        /// <summary>
        /// Obtiene los registros de asientos tipo VT de ingresos a partir de un archivo Excel.
        /// </summary>
        /// <param name="dtAsientos">Tabla en la que se volcará la información de los asientos a generar.</param>
        /// <param name="archivo">Ruta y nombre del archivo Excel que contiene la información del reporte de ingresos para obtener los asientos.</param>
        public void ObtenerAsientosVTIngresos(Procesos.TD.Asiento.LISTA_ASIENTODataTable dtAsientos, string archivo)
        {
            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("es-PE");
            CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;

            try
            {
                Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
                ExcelApplication app   = new ExcelApplication();
                ExcelWorkBook    wb    = app.OpenWorkBook(archivo, ExcelMode.Full);
                ExcelWorkSheet   sheet = wb.GetSheet(1);

                String    fechaAsiento = sheet.GetString("G3"); //convertir a fecha
                DataTable dt           = sheet.LeerTabla("B", "I", 5, sheet.ObtenerUltimaFilaTabla("B", 6), true);

                /*String factura = sheet.GetString("G2");
                 * string[] partesFactura = ObtenerPartesFactura(factura);
                 * string numeros = partesFactura[0];
                 * string letras = partesFactura[1];
                 */
                ParametrosDA parametrosDA       = new ParametrosDA();
                DataTable    dtParametroRUC     = parametrosDA.ObtenerValoresParametros(ConstantesING.TABLA_TIPO_DOCUMENTO, ConstantesING.TIPO_DOCUMENTO_RUC);
                String       tipoDocumentoSunat = dtParametroRUC.Rows[0]["CAMPO1"].ToString();

                //int correlativoFactura = Convert.ToInt32(numeros);

                wb.Close();
                app.Close();
                Hashtable ht = new Hashtable();
                foreach (DataRow dr in dt.Rows)
                {
                    string fondo = dr["Fondo"].ToString().Trim();
                    if (!ht.ContainsKey(fondo))
                    {
                        Asiento.LISTA_ASIENTORow row = dtAsientos.NewLISTA_ASIENTORow();

                        //string numeroFactura = letras + correlativoFactura.ToString().PadLeft(numeros.Length, '0');
                        //correlativoFactura++;
                        object total = dt.Compute("SUM(Ingresos)", "Fondo = '" + fondo + "'");
                        //object totalImpuesto = dt.Compute("SUM(IGV)", "Fondo = '" + fondo + "'");
                        object totalPN = dt.Compute("SUM(Ingresos)", "Fondo = '" + fondo + "' and TipoPersona = 'PN'");
                        //object impuestoPN = dt.Compute("SUM(IGV)", "Fondo = '" + fondo + "' and TipoPersona = 'PN'");
                        object totalPJ = dt.Compute("SUM(Ingresos)", "Fondo = '" + fondo + "' and TipoPersona = 'PJ'");
                        //object impuestoPJ = dt.Compute("SUM(IGV)", "Fondo = '" + fondo + "' and TipoPersona = 'PJ'");
                        //object subtotal = Convert.ToDecimal(total) - Convert.ToDecimal(totalImpuesto);
                        object igv = dt.Compute("SUM(IGV)", "Fondo = '" + fondo + "'");
                        row.TIPO_ASIENTO  = "VT_ING";
                        row.UUID          = "";
                        row.ESTADO        = "";
                        row.FONDO         = fondo;
                        row.FECHA_PROCESO = DateTime.ParseExact(fechaAsiento, "dd/MM/yyyy", CultureInfo.InvariantCulture).Date;
                        row.ID_OPERACION  = "";
                        row.MONEDA        = dr["Moneda"].ToString() == "SOL" ? "PEN" : "USD";
                        row.TOTAL         = total == null || total == DBNull.Value ? 0 : Decimal.Round(Convert.ToDecimal(total), 2);
                        row.MONTO1        = total == null || total == DBNull.Value ? 0 : Decimal.Round(Convert.ToDecimal(total), 2);


                        //row.MONTO2 = totalImpuesto == null || totalImpuesto == DBNull.Value ? 0 : Convert.ToDecimal(totalImpuesto);
                        //row.MONTO3 = totalPN == null || totalPN == DBNull.Value ? 0 : Convert.ToDecimal(totalPN);
                        //row.MONTO4 = totalPJ == null || totalPJ == DBNull.Value ? 0 : Convert.ToDecimal(totalPJ);
                        row.MONTO2 = totalPN == null || totalPN == DBNull.Value ? 0 : Decimal.Round(Convert.ToDecimal(totalPN), 2);
                        row.MONTO3 = totalPJ == null || totalPJ == DBNull.Value ? 0 : row.MONTO1 - row.MONTO2;
                        row.MONTO4 = 0;
                        row.MONTO5 = 0;
                        //ABRIR EN CASO SE JUNTEN LOS MONTO 3 Y MONTO4
                        row.REFERENCIA  = "";// numeroFactura;
                        row.REFERENCIA1 = tipoDocumentoSunat;
                        //row.MONTO3 = subtotal == null || subtotal == DBNull.Value ? 0 : Convert.ToDecimal(subtotal);

                        row.TEXTO1 = row.FECHA_PROCESO.ToString("MM");
                        row.TEXTO2 = row.FECHA_PROCESO.ToString("yyyy");

                        DataTable dtFondo = parametrosDA.ObtenerValoresParametros(ConstantesING.FONDO, fondo);
                        row.TIPO_DOCUMENTO = ConstantesING.TIPO_DOCUMENTO_RUC;
                        row.CODIGO_CLIENTE = dtFondo.Rows[0]["CAMPO2"].ToString();
                        row.RAZON_SOCIAL   = dtFondo.Rows[0]["CAMPO3"].ToString();

                        row.DIRECCION       = ConfigurationSettings.AppSettings[ConstantesING.DIRECCION_FONDOS];
                        row.DISTRITO        = ConfigurationSettings.AppSettings[ConstantesING.DISTRITO_FONDOS];
                        row.PROVINCIA       = ConfigurationSettings.AppSettings[ConstantesING.PROVINCIA_FONDOS];
                        row.DEPARTAMENTO    = ConfigurationSettings.AppSettings[ConstantesING.DEPARTAMENTO_FONDOS];
                        row.CODIGO_PAIS     = ConstantesING.CODIGO_PERU;
                        row.CORREO          = ConfigurationSettings.AppSettings[ConstantesING.CORREO_FONDOS];
                        row.ID_PAIS         = ConfigurationSettings.AppSettings[ConstantesING.ID_PAIS_FONDOS];
                        row.ID_DEPARTAMENTO = ConfigurationSettings.AppSettings[ConstantesING.ID_DEPARTAMENTO_FONDOS];
                        row.ID_CIUDAD       = ConfigurationSettings.AppSettings[ConstantesING.ID_CIUDAD_FONDOS];
                        row.ID_DISTRITO     = ConfigurationSettings.AppSettings[ConstantesING.ID_DISTRITO_FONDOS];
                        row.UBIGEO          = ConfigurationSettings.AppSettings[ConstantesING.UBIGEO_FONDOS];

                        row.IGVF   = Decimal.ToDouble(Decimal.Round(Convert.ToDecimal(igv), 2));
                        row.TOTALF = Decimal.ToDouble(row.TOTAL);
                        row.SUBF   = row.TOTALF - row.IGVF;

                        dtAsientos.AddLISTA_ASIENTORow(row);
                        ht.Add(fondo, fondo);
                    }
                }

                da.Server   = INGFondos.Constants.Conexiones.ServidorSAP;
                da.Database = INGFondos.Constants.Conexiones.BaseDeDatosSAP;
                da.ListarControlAsiento(dtAsientos, "VT_ING", DateTime.ParseExact(fechaAsiento, "dd/MM/yyyy", CultureInfo.InvariantCulture).Date);
                da.Server   = INGFondos.Constants.Conexiones.ServidorOperaciones;
                da.Database = INGFondos.Constants.Conexiones.BaseDeDatosOperaciones;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = originalCulture;
            }
        }
Example #2
0
        //OT 8372-PSC001
        //public void generarArchivo(string rutaArchivo, string rutaArchivoDestino)
        public void generarArchivoXFondo(string rutaArchivo, string rutaArchivoDestino)
        {
            StringBuilder sbLinea;

            sbLinea = new StringBuilder("");

            //StreamWriter sw = null;

            string path = rutaArchivo;

            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            ExcelApplication excelApplication = new ExcelApplication();
            ExcelWorkBook    wb = excelApplication.OpenWorkBook(path, ExcelMode.Full);

            try
            {
                ConveniosPlanEmpleadorDA conveniosPlanEmpleadorDA = new ConveniosPlanEmpleadorDA();
                string    codigosEmpresas   = "COD_EMP_CON";
                DataTable dtCodigosEmpresas = conveniosPlanEmpleadorDA.ObtenerTablaGeneral(codigosEmpresas);
                int       numeroEmpresas    = dtCodigosEmpresas.Rows.Count;

                object[] row;
                int      rowIndex;

                string    codigoParticipacion;
                string    nombreFondo;
                DataRow[] drFondo;
                DataTable dtFondosDepositos;
                DataRow[] drFondoDeposito;
                string    idFondo;
                string    codigoTablatablaGeneralDepositos = "FONDO_EQUIV";
                string    mes  = "";
                string    anio = "";

                string    estadoFondos = "ACT";
                DataTable dtFondos     = conveniosPlanEmpleadorDA.ListarFondos(estadoFondos);

                //OT 8372 INI

                DataTable dtRegistrosHoja;//almacena el contenido de una hoja del excel

                #region Definir las columnas del DataTable dtRegistrosHoja

                dtRegistrosHoja = new DataTable();

                dtRegistrosHoja.Columns.Add("CODIGO_PARTICIPACION", typeof(string));
                dtRegistrosHoja.Columns.Add("NOMBRE_FONDO", typeof(string));
                dtRegistrosHoja.Columns.Add("MONTO_APORTE", typeof(decimal));

                #endregion

                //OT 8372 FIN

                if (numeroEmpresas == 0)
                {
                    //no hay empresas
                }
                else
                {
                    string   periodo;
                    string[] periodoElementos;
                    string   tipoMovimiento = "I";
                    string   tipoAporte     = ""; //"P"
                    double   montoAporte;
                    string   montoAporteCadena;
                    string   nombreEmpresa;
                    bool     existenRegistrosHoja = true;
                    string   codigoEmpresa        = "";
                    string   constanteCP          = "CP_";

                    // int numeroHojas = numeroEmpresas * 2 + 1;
                    int numeroHojas = 0;
                    //OT 6891 inicio
                    int cantidadHojas = wb.GetSheetCount();
                    if (cantidadHojas == 3)
                    {
                        numeroHojas = wb.GetSheetCount();
                    }
                    else
                    {
                        numeroHojas = numeroEmpresas * 2 + 1;
                    }

                    //for (int i = 1; i <= numeroEmpresas; i++)
                    for (int i = 1; i <= numeroHojas; i++)
                    {
                        //ExcelWorkSheet sheet = wb.GetSheet(i + 1);
                        //Toma a partir de la 4ta hoja porque las 3 primeras son plantillas vacías.
                        //ExcelWorkSheet sheet = wb.GetSheet(i + 1);
                        //Toma a partir de la 4ta hoja porque las 3 primeras son plantillas vacías.
                        // OT 6891
                        ExcelWorkSheet sheet = null;
                        if (cantidadHojas == 3)
                        {
                            sheet = wb.GetSheet(i);
                        }
                        else
                        {
                            sheet = wb.GetSheet(i + 1);
                        }
                        // OT 6891 fin

                        nombreEmpresa = sheet.getName();


                        if (nombreEmpresa.StartsWith(constanteCP))
                        {
                            //StreamWriter sw = new StreamWriter(rutaArchivoDestino + "\\" + "PCP_" + nombreEmpresa + "_" + anio + mes + ".txt");



                            StreamWriter sw = null;
                            String       estadoCabecera;

                            //if (i == 1)
                            //{
                            periodo          = sheet.GetString("B8").Substring(4, 10);
                            periodoElementos = periodo.Split('/');

                            anio = periodoElementos[2].Trim();
                            mes  = periodoElementos[1].Trim();
                            //}

                            codigoEmpresa = sheet.GetString("B1").Trim();
                            DataTable dtDetalleConvenio = conveniosPlanEmpleadorDA.ObtenerDetalleConvenios(codigoEmpresa, Convert.ToInt32(mes), Convert.ToInt32(anio));

                            rowIndex = 13;//13
                            //row = sheet.GetRow(rowIndex++, 'B', 'J'); //OT 6134
                            row = sheet.GetRow(rowIndex++, 'B', 'E');


                            int cont = 0;

                            while (row[0] != null)
                            {
                                //if (row[8].ToString().Trim() == "EFE")
                                //if (row[3].ToString().Trim() == "EFE")
                                estadoCabecera = ObtienePestañaEmpresa(wb, nombreEmpresa.Substring(constanteCP.Length), numeroHojas, row[0].ToString().Substring(0, 8));


                                if (estadoCabecera == "EFE")
                                {
                                    if (existenRegistrosHoja)
                                    {
                                        codigoEmpresa = sheet.GetString("B1").Trim();
                                        //OT 8372 INI
                                        //sw = new StreamWriter(rutaArchivoDestino + "\\" + "PCP_" + nombreEmpresa.Substring(3, nombreEmpresa.Length - 3) + "_" + codigoEmpresa + "_" + anio + mes + ".txt");
                                        //OT 8372 FIN
                                        existenRegistrosHoja = false;
                                    }

                                    //codigoParticipacion = row[1].ToString().Trim();
                                    codigoParticipacion = row[0].ToString().Trim();
                                    //nombreFondo = row[7].ToString().Trim();//OT 6134
                                    nombreFondo = row[1].ToString().Trim();
                                    //montoAporte = Convert.ToDouble(row[6].ToString().Trim()); //OT 6134
                                    montoAporte = Convert.ToDouble(row[2].ToString().Trim()); //OT 6134

                                    //OT 8372 INI

                                    #region Agregar un registro al DataTable dtRegistrosHoja

                                    DataRow newRegistroHoja = dtRegistrosHoja.NewRow();

                                    newRegistroHoja["CODIGO_PARTICIPACION"] = codigoParticipacion;
                                    newRegistroHoja["NOMBRE_FONDO"]         = nombreFondo;
                                    newRegistroHoja["MONTO_APORTE"]         = montoAporte;

                                    dtRegistrosHoja.Rows.Add(newRegistroHoja);

                                    #endregion

                                    #region Se comenta código: El procesamiento de los registros ahora se hará al terminar de leer los registros de toda la hoja

                                    /*
                                     *                              string filtro = "CODIGO = '" + codigoParticipacion + "' AND FONDO = '" + nombreFondo + "' AND MONTO_CONCEPTO = " + montoAporte.ToString();
                                     *                              DataRow[] dDetalleConvenio = dtDetalleConvenio.Select(filtro, "ID_CONVENIO");
                                     *                              //Decimal idConvenio =0;
                                     * Decimal idConvenioDetalle = 0;
                                     * foreach (DataRow dr in dDetalleConvenio)
                                     *                              {
                                     *                                      //if (idConvenio == 0|| idConvenio > 0 && idConvenio == Convert.ToDecimal(dr["ID_CONVENIO"]))
                                     *  if (idConvenioDetalle == 0 || idConvenioDetalle > 0 && idConvenioDetalle == Convert.ToDecimal(dr["ID_CONVENIO_DETALLE"]))
                                     *  {
                                     *      idConvenioDetalle = Convert.ToDecimal(dr["ID_CONVENIO_DETALLE"]);
                                     *
                                     *      sbLinea.Append(codigoParticipacion.Replace("-", "").Trim());
                                     *                                          drFondo = dtFondos.Select("NOMBRE = '" + nombreFondo + "'");
                                     *                                          dtFondosDepositos = conveniosPlanEmpleadorDA.ObtenerTablaGeneralDepositos(codigoTablatablaGeneralDepositos);
                                     *                                          idFondo = drFondo[0]["ID"].ToString();
                                     *                                          drFondoDeposito = dtFondosDepositos.Select("DESCRIPCION_CORTA = '" + idFondo + "'");
                                     *                                          sbLinea.Append(drFondoDeposito[0]["LLAVE_TABLA"].ToString());
                                     *
                                     *                                          sbLinea.Append(anio + mes);
                                     *                                          sbLinea.Append(tipoMovimiento);
                                     *
                                     *                                          tipoAporte = dr["CODIGO_CONCEPTO"].ToString().Trim();
                                     *                                          sbLinea.Append(tipoAporte);
                                     *
                                     *                                          montoAporte = Convert.ToDouble(dr["MONTO_CONCEPTO"]);
                                     *                                          montoAporteCadena = montoAporte.ToString("000000.00");
                                     *                                          montoAporteCadena = montoAporteCadena.Replace(".", "");
                                     *                                          sbLinea.Append(montoAporteCadena);
                                     *
                                     *                                          sw.WriteLine(sbLinea);
                                     *                                          sbLinea.Length = 0;
                                     *                                      }
                                     *                                      else
                                     *                                              break;
                                     *                              }
                                     *
                                     *                          for (int j = dtDetalleConvenio.Rows.Count - 1; j >= 0; --j)
                                     *                          {
                                     *                                  DataRow drDetalleConvenio = dtDetalleConvenio.Rows[j];
                                     *                                  if (idConvenioDetalle == Convert.ToDecimal(drDetalleConvenio["ID_CONVENIO_DETALLE"]))
                                     *                                    dtDetalleConvenio.Rows.Remove(drDetalleConvenio);
                                     *                          }
                                     */
                                    #endregion
                                    //OT 8372 FIN
                                }



                                //row = sheet.GetRow(rowIndex++, 'B', 'J');//OT 6134
                                row  = sheet.GetRow(rowIndex++, 'B', 'E');
                                cont = cont + 1;
                            }

                            //OT 8372 INI

                            #region Procesar todos los registros de la hoja almacenadas en el DataTable dtRegistrosHoja

                            //Obtener los fondos que aparecen en el DataTable dtRegistrosHoja
                            var ListaFondos = (from DataRow dRow in dtRegistrosHoja.Rows
                                               select dRow["NOMBRE_FONDO"]).Distinct();

                            if (ListaFondos != null)
                            {
                                string filtroXNombreFondo;

                                foreach (var objNombreFondo in ListaFondos)
                                {
                                    filtroXNombreFondo = "NOMBRE_FONDO = '" + objNombreFondo + "'";
                                    DataRow[] dRegistrosXFondo = dtRegistrosHoja.Select(filtroXNombreFondo, "CODIGO_PARTICIPACION");

                                    //Crear un archivo plano .txt por cada fondo

                                    //OT 8372-PSC001 INICIO

                                    /*
                                     * sw = new StreamWriter(rutaArchivoDestino + "\\" + "PCP_" + nombreEmpresa.Substring(3, nombreEmpresa.Length - 3)
                                     + "_" + codigoEmpresa + "_" + objNombreFondo + "_" + anio + mes + ".txt");
                                     */
                                    sw = new StreamWriter(rutaArchivoDestino + "\\" + "PCP_" + "F" + "_" + objNombreFondo + "._"
                                                          + nombreEmpresa.Substring(3, nombreEmpresa.Length - 3)
                                                          + "_" + codigoEmpresa + "_" + anio + mes + ".txt");

                                    //OT 8372-PSC001 FIN

                                    foreach (var dRegistroXFondo in dRegistrosXFondo)
                                    {
                                        #region procesar un registro

                                        string filtro = "CODIGO = '" + dRegistroXFondo["CODIGO_PARTICIPACION"]
                                                        + "' AND FONDO = '" + dRegistroXFondo["NOMBRE_FONDO"]
                                                        + "' AND MONTO_CONCEPTO = " + dRegistroXFondo["MONTO_APORTE"].ToString();
                                        DataRow[] dDetalleConvenio = dtDetalleConvenio.Select(filtro, "ID_CONVENIO");
                                        //Decimal idConvenio =0;
                                        Decimal idConvenioDetalle = 0;
                                        foreach (DataRow dr in dDetalleConvenio)
                                        {
                                            //if (idConvenio == 0|| idConvenio > 0 && idConvenio == Convert.ToDecimal(dr["ID_CONVENIO"]))
                                            if (idConvenioDetalle == 0 || idConvenioDetalle > 0 && idConvenioDetalle == Convert.ToDecimal(dr["ID_CONVENIO_DETALLE"]))
                                            {
                                                idConvenioDetalle = Convert.ToDecimal(dr["ID_CONVENIO_DETALLE"]);

                                                sbLinea.Append(dRegistroXFondo["CODIGO_PARTICIPACION"].ToString().Replace("-", "").Trim());
                                                drFondo           = dtFondos.Select("NOMBRE = '" + dRegistroXFondo["NOMBRE_FONDO"] + "'");
                                                dtFondosDepositos = conveniosPlanEmpleadorDA.ObtenerTablaGeneralDepositos(codigoTablatablaGeneralDepositos);
                                                idFondo           = drFondo[0]["ID"].ToString();
                                                drFondoDeposito   = dtFondosDepositos.Select("DESCRIPCION_CORTA = '" + idFondo + "'");
                                                sbLinea.Append(drFondoDeposito[0]["LLAVE_TABLA"].ToString());

                                                sbLinea.Append(anio + mes);
                                                sbLinea.Append(tipoMovimiento);

                                                tipoAporte = dr["CODIGO_CONCEPTO"].ToString().Trim();
                                                sbLinea.Append(tipoAporte);

                                                montoAporte       = Convert.ToDouble(dr["MONTO_CONCEPTO"]);
                                                montoAporteCadena = montoAporte.ToString("000000.00");
                                                montoAporteCadena = montoAporteCadena.Replace(".", "");
                                                sbLinea.Append(montoAporteCadena);

                                                sw.WriteLine(sbLinea);
                                                sbLinea.Length = 0;
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }

                                        for (int j = dtDetalleConvenio.Rows.Count - 1; j >= 0; --j)
                                        {
                                            DataRow drDetalleConvenio = dtDetalleConvenio.Rows[j];
                                            if (idConvenioDetalle == Convert.ToDecimal(drDetalleConvenio["ID_CONVENIO_DETALLE"]))
                                            {
                                                dtDetalleConvenio.Rows.Remove(drDetalleConvenio);
                                            }
                                        }

                                        #endregion
                                    }

                                    if (sw != null)
                                    {
                                        sw.Close();
                                    }
                                }

                                dtRegistrosHoja.Rows.Clear();
                            }

                            #endregion

                            //OT 8372 FIN

                            if (cont > 0)
                            {
                                if (sw != null)
                                {
                                    sw.Close();
                                }
                            }
                            existenRegistrosHoja = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                wb.Close();
                excelApplication.Close();
                System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
            }
        }
        public void Procesar()
        {
            ExcelApplication excelApplication = new ExcelApplication();
            CargaContratoDA  da = new CargaContratoDA();
            SqlConnection    cn = GetConnection();

            cn.Open();

            SqlTransaction trans         = cn.BeginTransaction(IsolationLevel.ReadUncommitted);
            int            cucanterior   = 0;
            int            idanterior    = 0;
            string         prmVidaAhorro = "";
            string         prmCUC        = "";

            try
            {
                // Abriendo el archivo que contiene la información
                excelApplication.OpenWorkBook(sourcePath, ExcelMode.Full);
                ExcelWorkSheet sheet = excelApplication.GetWorkBook(1).GetSheet(1);

                //Obtiene los prospectos vacios
                CargaContratoDA cargaContratoDA = new CargaContratoDA();
                DataTable       dtProspectos    = cargaContratoDA.ObtenerListaProspectosVacios();

                // Obteniendo la información del archivo
                int      rowIndex = 6;
                object[] row      = sheet.GetRow(rowIndex++, 'C', 'Z', 4);
                int      contador = 0;
                //OT 6891 inicio
                DataTable dtCodVida       = ObtenerCodigoEmpresas_Vida();
                string    DSC_VIDA_AHORRO = "";
                if (dtCodVida.Rows.Count > 0)
                {
                    DataRow row1 = dtCodVida.Rows[0];
                    //Obtiene nombre de la empresa Vida Ahorro
                    DSC_VIDA_AHORRO = Convert.ToString(row1["DESCRIPCION_LARGA"]);
                }


                DataTable dtPlanVidaAhorro     = ObtenerPlanVidaAhorro();
                string    DSC_PLAN_VIDA_AHORRO = "";
                if (dtPlanVidaAhorro.Rows.Count > 0)
                {
                    DataRow row2 = dtPlanVidaAhorro.Rows[0];
                    //Obtiene nombre de la empresa Vida Ahorro
                    DSC_PLAN_VIDA_AHORRO = Convert.ToString(row2["VALOR"]);
                }


                while (row[0] != null)
                {
                    try
                    {
                        int idProspecto     = Convert.ToInt32(sheet.GetString(string.Format("B{0}", rowIndex - 1))) - 44670000;
                        int codigoProspecto = Convert.ToInt32(sheet.GetString(string.Format("B{0}", rowIndex - 1)));

                        //Leer datos del Partícipe



                        ParticipeTD.ParticipeRow drParticipe = new ParticipeTD().Participe.NewParticipeRow();
                        drParticipe.IDENTIFICADOR = Convert.ToInt32(sheet.GetString(string.Format("B{0}", rowIndex - 1))) - 44670000;
                        drParticipe.CODIGO        = Convert.ToInt32(sheet.GetString(string.Format("B{0}", rowIndex - 1)));
                        // Ini - traer el CUC del Participe OT 6891
                        prmCUC = drParticipe.CODIGO.ToString();
                        // Fin  - traer el CUC del Participe OT 6891
                        drParticipe.TIPO_PERSONA     = row[71].ToString();
                        drParticipe.NOMBRE1          = row[2].ToString();
                        drParticipe.NOMBRE2          = row[3] == null ? "" : row[3].ToString();
                        drParticipe.NOMBRE3          = row[4] == null ? "" : row[4].ToString();
                        drParticipe.APELLIDO_PATERNO = row[5].ToString();
                        drParticipe.APELLIDO_MATERNO = row[6].ToString();
                        drParticipe.SEXO             = row[72].ToString();
                        drParticipe.FECHA_NACIMIENTO = Convert.ToDateTime(row[8]);

                        drParticipe.TIPO_DOCUMENTO        = row[73].ToString();
                        drParticipe.NUMERO_DOCUMENTO      = row[10].ToString();
                        drParticipe.TIPO_FIRMA            = row[74].ToString();
                        drParticipe.TIPO_PARTICIPE        = row[75].ToString();
                        drParticipe.ESTADO_CIVIL          = row[76].ToString();
                        drParticipe.CODIGO_AGENCIA_ORIGEN = row[77] == null ? "" : row[77].ToString();
                        drParticipe.TIPO_PERSONERIA       = row[78] == null ? "" : row[78].ToString();
                        drParticipe.SENAS_PARTICULARES    = row[16] == null ? "" : row[16].ToString();
                        drParticipe.FLAG_RELACION_SURA    = "N";
                        drParticipe.NACIONALIDAD          = row[80].ToString();
                        drParticipe.PROFESION             = row[18] == null ? "" : row[18].ToString();
                        drParticipe.COMPANIA                   = row[19] == null ? "" : row[19].ToString();
                        drParticipe.CARGO                      = row[20] == null ? "" : row[20].ToString();
                        drParticipe.NUMERO_HIJOS               = row[21] == null ? 0 : Convert.ToInt32(row[21]);
                        drParticipe.LUGAR_NACIMIENTO           = row[81] == null ? null : row[81].ToString();
                        drParticipe.PAIS_RESIDENCIA            = row[82].ToString();
                        drParticipe.NIVEL_CARGO                = row[83] == null ? null : row[83].ToString();
                        drParticipe.GRADO_INSTRUCCION          = row[84] == null ? null : row[84].ToString();
                        drParticipe.CAPACIDAD_LEGAL            = row[85] == null ? null : row[85].ToString();
                        drParticipe.FLAG_CORRESPONDENCIA_EMAIL = row[27] == null ? "" : row[27].ToString();
                        drParticipe.FLAG_MEDIO_CONSULTAS       = row[28] == null ? "" : row[28].ToString();
                        drParticipe.FLAG_MEDIO_OPERACIONES     = row[29] == null ? "" : row[29].ToString();
                        drParticipe.TIPO_ATRIBUCION            = row[100] == null ? null : row[100].ToString();

                        drParticipe.USUARIO = codigoUsuario;
                        //INI OT 6891
                        // Tabla telefono
                        ParticipeTD.TelefonoRow drTelefono = new ParticipeTD().Telefono.NewTelefonoRow();
                        drTelefono.NUMERO = row[31] == null ? "" : row[31].ToString();


                        //Tabla correo electronico
                        ParticipeTD.Correo_EletronicoRow drCorreo = new ParticipeTD().Correo_Eletronico.NewCorreo_EletronicoRow();
                        drCorreo.CORREO = row[30] == null ? "" : row[30].ToString();

                        ParticipeTD.BoletinesRow drboletin = new ParticipeTD().Boletines.NewBoletinesRow();
                        drboletin.BOLETIN = row[32].ToString();

                        // Tabla direccion
                        ParticipeTD.DireccionRow drDireccion = new ParticipeTD().Direccion.NewDireccionRow();
                        string pais = "";
                        pais = row[105].ToString();
                        if (row[103].Equals("") || row[103].Equals(null) || pais.Length > 5)
                        {
                            drDireccion.DEPARTAMENTO = 0;
                        }
                        else
                        {
                            drDireccion.DEPARTAMENTO = Convert.ToInt32(row[103]);
                        }
                        string ciud = "";
                        ciud = row[105].ToString();
                        if (row[104].Equals("") || row[104].Equals(null) || ciud.Length > 5)
                        {
                            drDireccion.CIUDAD = 0;
                        }
                        else
                        {
                            drDireccion.CIUDAD = Convert.ToInt32(row[104]);
                        }
                        string dist = "";
                        dist = row[105].ToString();
                        if (row[105].Equals("") || row[105].Equals(null) || dist.Length > 5)
                        {
                            drDireccion.DISTRITO = 0;
                        }
                        else
                        {
                            drDireccion.DISTRITO = Convert.ToInt32(row[105]);
                        }
                        //  drDireccion.CIUDAD = Convert.ToInt32(row[104]);
                        //****
                        // drDireccion.DISTRITO = Convert.ToInt32(row[105]);
                        drDireccion.TIPO_VIA       = row[106] == null ? "" : row[106].ToString();
                        drDireccion.NOMBRE_VIA     = row[37] == null ? "" : row[37].ToString();
                        drDireccion.NU_IND_DEP     = row[38] == null ? "" : row[38].ToString();
                        drDireccion.UBICACION      = row[40] == null ? "" : row[40].ToString();
                        drDireccion.TIPO_UBICACION = row[107] == null ? "" : row[107].ToString();


                        //fin OT 6891


                        //Leer datos del Fondo

                        ParticipeTD.FondoRow drFondo = new ParticipeTD().Fondo.NewFondoRow();
                        drFondo.ID_FONDO = Convert.ToInt32(row[87]);
                        //OT5012 INI
                        drFondo.FECHA = Convert.ToDateTime(row[43]);

                        //Leer datos del documento
                        ParticipeTD.DocumentoRow drDocumento = new ParticipeTD().Documento.NewDocumentoRow();
                        //OT5012 FIN

                        drDocumento.TIPO          = row[86].ToString();
                        drDocumento.FECHA         = Convert.ToDateTime(row[43]);
                        drDocumento.DESCRIPCION   = row[44] == null ? "" : row[44].ToString();
                        drDocumento.CODIGO_IMAGEN = row[45] == null ? "" : row[45].ToString();

                        //Inicio  OT 6891
                        // Cuenta Participacion
                        CuentaParticipacionTD.CUENTA_PARTICIPACIONRow drCuentaParticipacion = new CuentaParticipacionTD().CUENTA_PARTICIPACION.NewCUENTA_PARTICIPACIONRow();
                        drCuentaParticipacion.VIDA_AHORRO = row[109] == null ? "" : row[109].ToString();
                        drCuentaParticipacion.CODIGO      = prmCUC;
                        drCuentaParticipacion.ETIQUETA    = DSC_VIDA_AHORRO;
                        prmVidaAhorro = drCuentaParticipacion.VIDA_AHORRO;
                        drCuentaParticipacion.USUARIO_CREACION = codigoUsuario;
                        drCuentaParticipacion.CODIGO_PLAN      = DSC_PLAN_VIDA_AHORRO;
                        // Fin  OT 6891

                        ParticipeTD.ParticipeRow drParticipeAsociado = null;


                        //Leer partícipe asociado
                        if (drParticipe.TIPO_PERSONA.Equals("MAN") && cucanterior != codigoProspecto)
                        {
                            drParticipeAsociado = new ParticipeTD().Participe.NewParticipeRow();

                            drParticipeAsociado.TIPO_PERSONA = "NAT";

                            drParticipeAsociado.NOMBRE1          = row[47].ToString();
                            drParticipeAsociado.NOMBRE2          = row[48] == null ? "" : row[48].ToString();
                            drParticipeAsociado.NOMBRE3          = row[49] == null ? "" : row[49].ToString();
                            drParticipeAsociado.APELLIDO_PATERNO = row[50].ToString();
                            drParticipeAsociado.APELLIDO_MATERNO = row[51].ToString();
                            drParticipeAsociado.SEXO             = row[72].ToString();
                            drParticipeAsociado.FECHA_NACIMIENTO = Convert.ToDateTime(row[53]);
                            drParticipeAsociado.TIPO_DOCUMENTO   = row[73].ToString();
                            drParticipeAsociado.NUMERO_DOCUMENTO = row[55].ToString();
                            drParticipeAsociado.TIPO_FIRMA       = "IND";
                            drParticipeAsociado.TIPO_PARTICIPE   = row[91].ToString();

                            drParticipeAsociado.ESTADO_CIVIL          = row[92].ToString();
                            drParticipeAsociado.CODIGO_AGENCIA_ORIGEN = ""; //
                            drParticipeAsociado.TIPO_PERSONERIA       = ""; //

                            drParticipeAsociado.SENAS_PARTICULARES = "";    //
                            drParticipeAsociado.FLAG_RELACION_SURA = "N";
                            drParticipeAsociado.NACIONALIDAD       = row[94].ToString();
                            drParticipeAsociado.PROFESION          = row[61] == null ? "" : row[61].ToString();
                            drParticipeAsociado.COMPANIA           = row[62] == null ? "" : row[62].ToString();
                            drParticipeAsociado.CARGO             = row[63] == null ? "" : row[63].ToString();
                            drParticipeAsociado.NUMERO_HIJOS      = row[64] == null ? 0 : Convert.ToInt32(row[64]);
                            drParticipeAsociado.LUGAR_NACIMIENTO  = row[95].ToString();
                            drParticipeAsociado.PAIS_RESIDENCIA   = row[96].ToString();
                            drParticipeAsociado.NIVEL_CARGO       = row[96].ToString();
                            drParticipeAsociado.GRADO_INSTRUCCION = row[99].ToString();
                            drParticipeAsociado.CAPACIDAD_LEGAL   = row[99].ToString();

                            drParticipeAsociado.USUARIO = codigoUsuario;
                        }
                        //Partícipes NAT
                        if (row[71].ToString().Equals("NAT"))
                        {
                            cargaContratoDA.registrarParticipe(drParticipe, drFondo, drDocumento, drCorreo, drTelefono, drboletin, drDireccion, cn, trans);
                            // OT 6891 INICIO
                            if (prmVidaAhorro.Equals("S"))
                            {
                                cargaContratoDA.RegistrarCuentaParticipacion_x_Participe(drCuentaParticipacion, prmCUC, codigoUsuario, cn, trans);
                            }
                            // FIN OT 6891 FIN
                            DataTable dtPersona = cargaContratoDA.ObtenerPersona(drParticipe, cn, trans);

                            if (dtPersona.Rows.Count == 0)
                            {
                                cargaContratoDA.registrarPersona(drParticipe, cn, trans);
                            }
                            else
                            {
                                cargaContratoDA.ActualizarPersona(drParticipe, cn, trans, "N");
                                cargaContratoDA.ActualizarParticipeXDocumento(drParticipe, cn, trans, "N");
                            }
                        }
                        //Partícipes MAN
                        else
                        {
                            //Registra dos prospectos
                            if (codigoProspecto != cucanterior)
                            {
                                String contrasenaCifrada = "";
                                String claveEncriptada   = cargaContratoDA.ObtenerClaveEncriptada(cn, trans);

                                String areaModificacion = "OPE";
                                String flagVerOperacion = "S";
                                String flagAccesoWeb    = "S";

                                contrasenaCifrada = obtenerContrasenaCifrada(claveEncriptada);
                                cargaContratoDA.registrarProspectos(drParticipe, contrasenaCifrada, areaModificacion, flagVerOperacion, flagAccesoWeb, cn, trans); //TITULAR

                                contrasenaCifrada = obtenerContrasenaCifrada(claveEncriptada);
                                cargaContratoDA.registrarProspectos(drParticipeAsociado, contrasenaCifrada, areaModificacion, flagVerOperacion, flagAccesoWeb, cn, trans); //ASOCIADO
                                /*CARGA DE LA PERSONA DEL ASOCIADO*/
                                DataTable dtPersona = cargaContratoDA.ObtenerPersona(drParticipeAsociado, cn, trans);
                                if (dtPersona.Rows.Count == 0)
                                {
                                    cargaContratoDA.registrarPersona(drParticipeAsociado, cn, trans);
                                }
                                else
                                {
                                    cargaContratoDA.ActualizarPersona(drParticipeAsociado, cn, trans, "S");
                                    cargaContratoDA.ActualizarParticipeXDocumento(drParticipeAsociado, cn, trans, "S");
                                }
                                int idParticipe         = drParticipe.CODIGO - 44670000;
                                int idProspectoTitular  = drParticipe.IDENTIFICADOR;
                                int idProspectoAsociado = drParticipeAsociado.IDENTIFICADOR;
                                cargaContratoDA.actualizarParticipe(drParticipe, cn, trans); //REGISTRO DEL PARTICIPE MANCOMUNO
                                /*CARGA DE LA PERSONA DEL TITULAR*/
                                dtPersona = cargaContratoDA.ObtenerPersona(drParticipe, cn, trans);
                                if (dtPersona.Rows.Count == 0)
                                {
                                    cargaContratoDA.registrarPersona(drParticipe, cn, trans);
                                }
                                else
                                {
                                    cargaContratoDA.ActualizarPersona(drParticipe, cn, trans, "N");
                                    cargaContratoDA.ActualizarParticipeXDocumento(drParticipe, cn, trans, "N");
                                }
                                //REGISTRAMOS LA RELACION ENTRE EL TITULAR Y EL ASOCIADO
                                decimal porcentajeTitular  = decimal.MinValue;
                                decimal porcentajeAsociado = decimal.MinValue;

                                if (row[86] != null && row[86].ToString().Equals("DIS"))
                                {
                                    porcentajeTitular  = Convert.ToDecimal(row[101]) * 100;
                                    porcentajeAsociado = Convert.ToDecimal(row[102]) * 100;
                                    if (porcentajeTitular + porcentajeAsociado != 100)
                                    {
                                        throw new Exception("La suma de los porcentajes debe sumar 100%.");
                                    }

                                    cargaContratoDA.registrarParticipeXparticipe(idProspecto, idProspecto, codigoUsuario, porcentajeTitular, cn, trans);
                                }
                                cargaContratoDA.registrarParticipeXparticipe(idProspecto, idProspectoAsociado, codigoUsuario, porcentajeAsociado, cn, trans);
                            }
                            //OT5012 INI
                            cargaContratoDA.registrarFondos(drFondo, idProspecto, codigoUsuario, cn, trans);
                            //OT5012 FIN
                        }
                        // FIN OT 6891
                        //sheet.SetValue(string.Format("B{0}",rowIndex-1),codigoProspecto);
                        cucanterior = codigoProspecto;
                        idanterior  = idProspecto;

                        row = sheet.GetRow(rowIndex++, 'C', 'Z', 4);
                        contador++;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("Error en la línea {0}. Detalle " + ex.Message, rowIndex - 1));
                    }
                }

                trans.Commit();
                excelApplication.GetWorkBook(1).Save();
                excelApplication.Show();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                excelApplication.GetWorkBook(1).Close();
                excelApplication.Close();
                throw ex;
            }
            finally
            {
                trans.Dispose();
                cn.Close();
                excelApplication.Close();
            }
        }
Example #4
0
        //OT 8372-PSC001
        public void generarArchivoUnico(string rutaArchivo, string rutaArchivoDestino)
        {
            StringBuilder sbLinea;

            sbLinea = new StringBuilder("");

            //StreamWriter sw = null;

            string path = rutaArchivo;

            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            ExcelApplication excelApplication = new ExcelApplication();
            ExcelWorkBook    wb = excelApplication.OpenWorkBook(path, ExcelMode.Full);

            try
            {
                ConveniosPlanEmpleadorDA conveniosPlanEmpleadorDA = new ConveniosPlanEmpleadorDA();
                string    codigosEmpresas   = "COD_EMP_CON";
                DataTable dtCodigosEmpresas = conveniosPlanEmpleadorDA.ObtenerTablaGeneral(codigosEmpresas);
                int       numeroEmpresas    = dtCodigosEmpresas.Rows.Count;

                object[] row;
                int      rowIndex;

                string    codigoParticipacion;
                string    nombreFondo;
                DataRow[] drFondo;
                DataTable dtFondosDepositos;
                DataRow[] drFondoDeposito;
                string    idFondo;
                string    codigoTablatablaGeneralDepositos = "FONDO_EQUIV";
                string    mes  = "";
                string    anio = "";

                string    estadoFondos = "ACT";
                DataTable dtFondos     = conveniosPlanEmpleadorDA.ListarFondos(estadoFondos);

                if (numeroEmpresas == 0)
                {
                    //no hay empresas
                }
                else
                {
                    string   periodo;
                    string[] periodoElementos;
                    string   tipoMovimiento = "I";
                    string   tipoAporte     = ""; //"P"
                    double   montoAporte;
                    string   montoAporteCadena;
                    string   nombreEmpresa;
                    bool     existenRegistrosHoja = true;
                    string   codigoEmpresa        = "";
                    string   constanteCP          = "CP_";

                    // int numeroHojas = numeroEmpresas * 2 + 1;
                    int numeroHojas = 0;
                    //OT 6891 inicio
                    int cantidadHojas = wb.GetSheetCount();
                    if (cantidadHojas == 3)
                    {
                        numeroHojas = wb.GetSheetCount();
                    }
                    else
                    {
                        numeroHojas = numeroEmpresas * 2 + 1;
                    }

                    //for (int i = 1; i <= numeroEmpresas; i++)
                    for (int i = 1; i <= numeroHojas; i++)
                    {
                        //ExcelWorkSheet sheet = wb.GetSheet(i + 1);
                        //Toma a partir de la 4ta hoja porque las 3 primeras son plantillas vacías.
                        //ExcelWorkSheet sheet = wb.GetSheet(i + 1);
                        //Toma a partir de la 4ta hoja porque las 3 primeras son plantillas vacías.
                        // OT 6891
                        ExcelWorkSheet sheet = null;
                        if (cantidadHojas == 3)
                        {
                            sheet = wb.GetSheet(i);
                        }
                        else
                        {
                            sheet = wb.GetSheet(i + 1);
                        }
                        // OT 6891 fin

                        nombreEmpresa = sheet.getName();


                        if (nombreEmpresa.StartsWith(constanteCP))
                        {
                            //StreamWriter sw = new StreamWriter(rutaArchivoDestino + "\\" + "PCP_" + nombreEmpresa + "_" + anio + mes + ".txt");



                            StreamWriter sw = null;
                            String       estadoCabecera;

                            //if (i == 1)
                            //{
                            periodo          = sheet.GetString("B8").Substring(4, 10);
                            periodoElementos = periodo.Split('/');

                            anio = periodoElementos[2].Trim();
                            mes  = periodoElementos[1].Trim();
                            //}

                            codigoEmpresa = sheet.GetString("B1").Trim();
                            DataTable dtDetalleConvenio = conveniosPlanEmpleadorDA.ObtenerDetalleConvenios(codigoEmpresa, Convert.ToInt32(mes), Convert.ToInt32(anio));

                            rowIndex = 13;//13
                            //row = sheet.GetRow(rowIndex++, 'B', 'J'); //OT 6134
                            row = sheet.GetRow(rowIndex++, 'B', 'E');


                            int cont = 0;

                            while (row[0] != null)
                            {
                                //if (row[8].ToString().Trim() == "EFE")
                                //if (row[3].ToString().Trim() == "EFE")
                                estadoCabecera = ObtienePestañaEmpresa(wb, nombreEmpresa.Substring(constanteCP.Length), numeroHojas, row[0].ToString().Substring(0, 8));


                                if (estadoCabecera == "EFE")
                                {
                                    if (existenRegistrosHoja)
                                    {
                                        codigoEmpresa = sheet.GetString("B1").Trim();

                                        //OT 8372-PSC001 INICIO

                                        //sw = new StreamWriter(rutaArchivoDestino + "\\" + "PCP_" + nombreEmpresa.Substring(3, nombreEmpresa.Length - 3) + "_" + codigoEmpresa + "_" + anio + mes + ".txt");
                                        sw = new StreamWriter(rutaArchivoDestino + "\\" + "PCP_" + "T" + "_"
                                                              + nombreEmpresa.Substring(3, nombreEmpresa.Length - 3) + "_" + codigoEmpresa + "_" + anio + mes + ".txt");

                                        //OT 8372-PSC001 FIN

                                        existenRegistrosHoja = false;
                                    }

                                    //codigoParticipacion = row[1].ToString().Trim();
                                    codigoParticipacion = row[0].ToString().Trim();
                                    //nombreFondo = row[7].ToString().Trim();//OT 6134
                                    nombreFondo = row[1].ToString().Trim();
                                    //montoAporte = Convert.ToDouble(row[6].ToString().Trim()); //OT 6134
                                    montoAporte = Convert.ToDouble(row[2].ToString().Trim()); //OT 6134

                                    string    filtro           = "CODIGO = '" + codigoParticipacion + "' AND FONDO = '" + nombreFondo + "' AND MONTO_CONCEPTO = " + montoAporte.ToString();
                                    DataRow[] dDetalleConvenio = dtDetalleConvenio.Select(filtro, "ID_CONVENIO");
                                    //Decimal idConvenio =0;
                                    Decimal idConvenioDetalle = 0;
                                    foreach (DataRow dr in dDetalleConvenio)
                                    {
                                        //if (idConvenio == 0|| idConvenio > 0 && idConvenio == Convert.ToDecimal(dr["ID_CONVENIO"]))
                                        if (idConvenioDetalle == 0 || idConvenioDetalle > 0 && idConvenioDetalle == Convert.ToDecimal(dr["ID_CONVENIO_DETALLE"]))
                                        {
                                            idConvenioDetalle = Convert.ToDecimal(dr["ID_CONVENIO_DETALLE"]);

                                            sbLinea.Append(codigoParticipacion.Replace("-", "").Trim());
                                            drFondo           = dtFondos.Select("NOMBRE = '" + nombreFondo + "'");
                                            dtFondosDepositos = conveniosPlanEmpleadorDA.ObtenerTablaGeneralDepositos(codigoTablatablaGeneralDepositos);
                                            idFondo           = drFondo[0]["ID"].ToString();
                                            drFondoDeposito   = dtFondosDepositos.Select("DESCRIPCION_CORTA = '" + idFondo + "'");
                                            sbLinea.Append(drFondoDeposito[0]["LLAVE_TABLA"].ToString());

                                            sbLinea.Append(anio + mes);
                                            sbLinea.Append(tipoMovimiento);

                                            tipoAporte = dr["CODIGO_CONCEPTO"].ToString().Trim();
                                            sbLinea.Append(tipoAporte);

                                            montoAporte       = Convert.ToDouble(dr["MONTO_CONCEPTO"]);
                                            montoAporteCadena = montoAporte.ToString("000000.00");
                                            montoAporteCadena = montoAporteCadena.Replace(".", "");
                                            sbLinea.Append(montoAporteCadena);

                                            sw.WriteLine(sbLinea);
                                            sbLinea.Length = 0;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }

                                    for (int j = dtDetalleConvenio.Rows.Count - 1; j >= 0; --j)
                                    {
                                        DataRow drDetalleConvenio = dtDetalleConvenio.Rows[j];
                                        if (idConvenioDetalle == Convert.ToDecimal(drDetalleConvenio["ID_CONVENIO_DETALLE"]))
                                        {
                                            dtDetalleConvenio.Rows.Remove(drDetalleConvenio);
                                        }
                                    }
                                }

                                //row = sheet.GetRow(rowIndex++, 'B', 'J');//OT 6134
                                row  = sheet.GetRow(rowIndex++, 'B', 'E');
                                cont = cont + 1;
                            }

                            if (cont > 0)
                            {
                                if (sw != null)
                                {
                                    sw.Close();
                                }
                            }
                            existenRegistrosHoja = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                wb.Close();
                excelApplication.Close();
                System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
            }
        }
Example #5
0
        public void Procesar()
        {
            ExcelApplication            excelApplication = new ExcelApplication();
            CargarRetencionPagoFlujosDA da = new CargarRetencionPagoFlujosDA();
            SqlConnection cn = GetConnection();

            cn.Open();

            SqlTransaction trans       = cn.BeginTransaction(IsolationLevel.ReadUncommitted);
            DateTime       fechaActual = DateTime.Now;


            try
            {
                // Abriendo el archivo que contiene la información
                excelApplication.OpenWorkBook(sourcePath, ExcelMode.Full);
                ExcelWorkSheet sheet = excelApplication.GetWorkBook(1).GetSheet(1);

                // Obteniendo la información del archivo
                int rowIndex = 2;
                //object[] row = sheet.GetRow(rowIndex++, 'A', 'C', 4);
                object[] row = sheet.GetRow(rowIndex++, 'A', 'C');

                while (row[0] != null)
                {
                    try
                    {
                        int idOperacion = Convert.ToInt32(sheet.GetString(string.Format("A{0}", rowIndex - 1)));
                        int idParticipe = Convert.ToInt32(sheet.GetString(string.Format("B{0}", rowIndex - 1)));
                        //decimal montoRetencion = Convert.ToDecimal(sheet.GetString(string.Format("C{0}", rowIndex - 1)));
                        String  montoRetencionCadena = Convert.ToDecimal(sheet.GetString(string.Format("C{0}", rowIndex - 1))).ToString("0.00000000");
                        decimal montoRetencion       = Convert.ToDecimal(montoRetencionCadena);

                        PagoFlujosTD.PagoFlujosRow drPagoFlujos = new PagoFlujosTD().PagoFlujos.NewPagoFlujosRow();
                        drPagoFlujos.ID_OPERACION     = idOperacion;
                        drPagoFlujos.ID_PARTICIPE     = idParticipe;
                        drPagoFlujos.RETENCION        = montoRetencion;
                        drPagoFlujos.FECHA            = fechaActual;
                        drPagoFlujos.USUARIO_CREACION = codigoUsuario;

                        da.registrarPagoFlujos(drPagoFlujos, cn, trans);
                        row = sheet.GetRow(rowIndex++, 'A', 'C');
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("Error en la línea {0}. Detalle " + ex.Message, rowIndex - 1));
                    }
                    //excelApplication.GetWorkBook(1).Save();
                    //excelApplication.Show();
                }
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                excelApplication.GetWorkBook(1).Close();
                excelApplication.Close();
                throw ex;
            }
            finally
            {
                trans.Dispose();
                cn.Close();
                excelApplication.Close();
            }
        }