public String ObtienePestañaEmpresa(ExcelWorkBook wb, string nombreEmpresa, int numeroHojas, string cuc) { string nombreSheet; int rowIndex; object[] row; rowIndex = 13;//13 for (int i = 1; i <= numeroHojas; i++) { //ot6891 inicio ExcelWorkSheet sheet = wb.GetSheet(i + 1); //ot6891 fin nombreSheet = sheet.getName(); if (nombreSheet.Equals(nombreEmpresa)) { row = sheet.GetRow(rowIndex++, 'B', 'O'); while (row[0] != null) { if (row[0].ToString().Trim().Equals(cuc)) { return(row[7].ToString().Trim()); } row = sheet.GetRow(rowIndex++, 'B', 'O'); } } } return(""); }
public void Procesar() { StringBuilder sbLinea; sbLinea = new StringBuilder(""); CargaSegurosSuraDA da = new CargaSegurosSuraDA(); SqlConnection cn = GetConnection(); cn.Open(); SqlTransaction trans = cn.BeginTransaction(IsolationLevel.ReadUncommitted); string path = sourcePath; 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 { // traer la cantidad de empresas atraves del campo codigo 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); CargaSegurosSuraDA cargaSegurosSuraDA = new CargaSegurosSuraDA(); 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 = ""; int grabo_registro = 0; int numeroHojas = 0; string parametro = ""; string constanteCP = "CP_"; 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); // ExcelWorkSheet sheet = null; nombreEmpresa = sheet.getName(); parametro = nombreEmpresa.Substring(0, 3); StreamWriter sw = null; //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', 'O'); int cont = 0; while (row[0] != null & parametro != constanteCP) { try { ConvenioTD.ConvenioRow drConvenio = new ConvenioTD().Convenio.NewConvenioRow(); drConvenio.CUC = row[0].ToString(); drConvenio.MATRICULA = row[1] == null ? "" : row[1].ToString(); drConvenio.NOMBRE = row[2] == null ? "" : row[2].ToString(); drConvenio.NOMBRES = row[3].ToString(); drConvenio.APELLIDOS = row[4].ToString(); drConvenio.MONTO = Convert.ToDouble(row[5]); drConvenio.FONDO = row[6].ToString(); drConvenio.ESTADO = row[7].ToString(); drConvenio.PARTICIPANTE = Convert.ToDouble(row[8]); drConvenio.EMPLEADOR = Convert.ToDouble(row[9]); drConvenio.ANTIGUEDAD = Convert.ToDouble(row[10]); drConvenio.SALARIO_PROM = Convert.ToDouble(row[11]); drConvenio.EDAD = Convert.ToDouble(row[12]); drConvenio.BONO_ANUAL = Convert.ToDouble(row[13]); cargaSegurosSuraDA.CargaRegistroConvenio(drConvenio, cn, trans); row = sheet.GetRow(rowIndex++, 'B', 'O'); cont = cont + 1; grabo_registro = grabo_registro + 1; } catch (Exception ex) { throw new Exception(string.Format("Error en la línea {0}. Detalle " + ex.Message, rowIndex - 1)); } // trans.Commit(); } if (cont > 0) { if (sw != null) { sw.Close(); } } existenRegistrosHoja = true; } if (grabo_registro > 0) { trans.Commit(); } } } catch (Exception ex) { trans.Rollback(); throw ex; } finally { wb.Close(); System.Threading.Thread.CurrentThread.CurrentCulture = oldCI; excelApplication.Close(); } }
/// <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; } }
//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; } }
//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; } }
public void PrepararPlantilla(string sourcePath, string savePath, string codigoUsuario) { ExcelApplication excelApplication = new ExcelApplication(); ExcelWorkBook workBook = null; workBook = excelApplication.OpenWorkBook(sourcePath, ExcelMode.Full); ExcelWorkSheet sheet = workBook.GetSheet(2); ExcelWorkSheet sheetCucs = workBook.GetSheet(3); //Obtiene los prospectos vacios CargaContratoDA cargaContratoDA = new CargaContratoDA(); DataTable dtProspectos = cargaContratoDA.ObtenerListaProspectosVacios(); sheetCucs.EscribirDatatable("B", 2, dtProspectos); DataTable dtDISTRITO = cargaContratoDA.ObtenerListaDistritos(); int indis = 2; foreach (DataRow dr in dtDISTRITO.Rows) { sheet.SetValue(string.Format("W{0}", indis), dr["NOMBRE"]); sheet.SetValue(string.Format("X{0}", indis), dr["ID"]); sheet.SetValue(string.Format("Y{0}", indis++), dr["CIUDAD"]); } FondoDA fondoDA = new FondoDA(); DataTable dtTiposDocumentos = fondoDA.ObtenerLista("TPDOCS"); int index = 2; foreach (DataRow dr in dtTiposDocumentos.Rows) { sheet.SetValue(string.Format("K{0}", index), dr["DESCRIPCION_LARGA"]); sheet.SetValue(string.Format("L{0}", index++), dr["LLAVE_TABLA"]); } index = 2; DataTable dtAgenciasOrigen = fondoDA.ObtenerLista("AGEORI"); foreach (DataRow dr in dtAgenciasOrigen.Rows) { sheet.SetValue(string.Format("H{0}", index), dr["DESCRIPCION_LARGA"]); sheet.SetValue(string.Format("I{0}", index++), dr["LLAVE_TABLA"]); } index = 2; DataTable dtFondos = cargaContratoDA.ObtenerListaFondos(); DataRow[] drFondos = dtFondos.Select("1=1", "NOMBRE"); foreach (DataRow dr in drFondos) { sheet.SetValue(string.Format("E{0}", index), dr["NOMBRE"]); sheet.SetValue(string.Format("F{0}", index++), dr["ID"]); } sheet.Hide(); excelApplication.GetWorkBook(1).SaveAs(savePath); workBook.Close(); excelApplication.Close(); workBook = excelApplication.OpenWorkBook(savePath, ExcelMode.Full); excelApplication.Show(); }