private void btnGenerar_Click(object sender, EventArgs e)
        {
            //Variables generales.
            string _Path    = Configuration.Path;
            int    x        = 0;
            double r        = 0;
            int    progress = 0;

            oComprobacion[] _Comprobaciones = Assembler.LoadJson <oComprobacion[]>($"{_Path}\\jsons\\Comprobaciones.json");
            //Libro Actual de Excel.
            Excel.Worksheet xlSht;
            Excel.Workbook  wb = Globals.ThisAddIn.Application.ActiveWorkbook;
            string          _DestinationPath = "";
            string          _newTemplate     = "";

            //_Name = _aName[2].ToString();
            //_IdTipo = _Name.Split('_')[1].ToString();
            Generales.Proteccion(false);//desprotejo
            //Cuándo es para transferir, pide la ruta en donde guardar el archivo a transferir.
            if (!_formulas)
            {
                for (int y = 0; y < 1;)
                {
                    fbdTemplate.ShowDialog();
                    _DestinationPath = fbdTemplate.SelectedPath;
                    y = 1;
                    if (_DestinationPath == "")
                    {
                        MessageBox.Show("Debe especificar un ruta", "Ruta Invalida", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        y = 0;
                    }
                }

                Cursor.Current = Cursors.WaitCursor;
                // el nombre de una Key debe incluir un root valido.
                const string userRoot  = "HKEY_CURRENT_USER";
                const string subkey    = "Software\\Microsoft\\Office\\Excel\\Addins\\SAT.Dictamenes.SIPRED.Client";
                const string keyName   = userRoot + "\\" + subkey;
                object       addInName = "SAT.Dictamenes.SIPRED.Client";

                Registry.SetValue(keyName, "LoadBehavior", 3);
                Globals.ThisAddIn.Application.COMAddIns.Item(ref addInName).Connect = true;
                string _sOpen = wb.Worksheets.Item[wb.Worksheets.Count].Name;

                _newTemplate = $"{_DestinationPath}\\Transferencia-{Globals.ThisAddIn.Application.ActiveWorkbook.Name}";

                for (int _wCount = 1; _wCount <= wb.Worksheets.Count; _wCount++)
                {
                    if (wb.Worksheets.Item[_wCount].Name == "SIPRED")
                    {
                        wb.Worksheets.Item[_wCount].Delete();
                    }
                }

                string _NameFile = wb.Name;
                wb.SaveCopyAs(_newTemplate);
                wb.Save();
                wb.Close();

                Globals.ThisAddIn.Application.Visible = true;
                Globals.ThisAddIn.Application.Workbooks.Open(_newTemplate);

                wb = Globals.ThisAddIn.Application.ActiveWorkbook;
                x  = 0;
                foreach (oComprobacion _Comprobacion in _Comprobaciones.Where(o => o.IdTipoPlantilla == Convert.ToInt32(1)).ToArray())
                {
                    _Comprobacion.setFormulaExcel();
                    xlSht = (Excel.Worksheet)wb.Worksheets.get_Item(_Comprobacion.Destino.Anexo);

                    if (_Comprobacion.EsValida() && _Comprobacion.EsFormula())
                    {
                        for (int a = 1; a < 1000; a++)
                        {
                            Excel.Range _Celda = (Excel.Range)xlSht.get_Range("A" + a.ToString());
                            if (Convert.ToString(_Celda.Value) == Convert.ToString(_Comprobacion.Destino.Indice))
                            {
                                try
                                {
                                    string _Rango    = Generales.ColumnAdress(Convert.ToInt32(_Comprobacion.Destino.Columna)) + a.ToString();
                                    Int32  _iColumna = _Comprobacion.Destino.Columna;

                                    _Celda = (Excel.Range)xlSht.get_Range(_Rango);
                                    _Celda.NumberFormat = "0";
                                    object _Value = _Celda.Value;
                                    _Celda.Formula = "";
                                    _Celda.Value   = _Value;
                                }
                                catch (Exception ex)
                                { }
                                a = 1001;
                            }
                        }
                    }
                }

                Excel.Range _Range;
                Excel.Range _RangeP;
                string      _sValor;
                Int64       _Valor;
                int         _Hijo;

                for (int _wCount = 1; _wCount <= wb.Worksheets.Count; _wCount++)
                {
                    string _sAnexo = wb.Worksheets.Item[_wCount].Name;
                    if (_sAnexo.IndexOf("NEXO") > 0)
                    {
                        xlSht = (Excel.Worksheet)wb.Worksheets.get_Item(_sAnexo);
                        for (int a = 1; a < 1000; a++)
                        {
                            _Range = (Excel.Range)xlSht.get_Range("A" + a.ToString());

                            if (Int64.TryParse(_Range.Value, out _Valor))
                            {
                                _Valor  = Convert.ToInt64(_Range.Value);
                                _sValor = Convert.ToString(_Range.Value);
                                _Hijo   = Convert.ToInt32(_sValor.Substring(_sValor.Length - 4, 4));

                                if (_Hijo == 100)
                                {
                                    for (int c = 3; c < 53; c++)
                                    {
                                        _RangeP = (Excel.Range)xlSht.get_Range($"{Generales.ColumnAdress(c)}{(a - 1).ToString()}");
                                        _RangeP.NumberFormat = "0";
                                        object _Value = _RangeP.Value;
                                        _RangeP.Formula = "";
                                        _RangeP.Value   = _Value;
                                    }
                                    a = 1001;
                                }
                            }
                        }
                    }
                }

                wb.Save();
                Cursor.Current = Cursors.Default;
            }
            //Asigna valores vacios a las celdas de las formulas y de tipo "General".
            if (_formulas)
            {
                x = 0;
                foreach (oComprobacion _Comprobacion in _Comprobaciones.Where(o => o.IdTipoPlantilla == Convert.ToInt32(1)).ToArray())
                {
                    _Comprobacion.setFormulaExcel();
                    xlSht = (Excel.Worksheet)wb.Worksheets.get_Item(_Comprobacion.Destino.Anexo);

                    string   _fExcel  = _Comprobacion.FormulaExcel.Replace("SUM", "").Replace("(", "").Replace(")", "").Replace("+0", "").Replace("*", "+").Replace("/", "+").Replace("IF", "").Replace("<0", "").Replace(">0", "+").Replace(",0)", "").Replace(",", "+").Replace("-", "+").Replace(">", "+").Replace("<", "+").Replace("=", "+");
                    string[] _sfExcel = _fExcel.Split('+');

                    for (int z = 0; z < _sfExcel.Length; z++)
                    {
                        if (_sfExcel[z] != "")
                        {
                            decimal temp = 0;
                            if (!decimal.TryParse(_sfExcel[z], out temp))
                            {
                                Excel.Range _Celda = (Excel.Range)xlSht.get_Range(_sfExcel[z]);
                                _Celda.NumberFormat = "0.00";
                                if (!_Open)
                                {
                                    _Celda.Value = "";
                                }
                            }
                        }
                    }
                    //Barra de Progreso.
                    x++;
                    r = x % 16;
                    if (r == 0.00)
                    {
                        progress += 10;
                        if (progress < 100)
                        {
                            fnProgressBar(progress);
                        }
                    }
                }
                x = 0;
                foreach (oComprobacion _Comprobacion in _Comprobaciones.Where(o => o.IdTipoPlantilla == Convert.ToInt32(1)).ToArray())
                {
                    _Comprobacion.setFormulaExcel();
                    xlSht = (Excel.Worksheet)wb.Worksheets.get_Item(_Comprobacion.Destino.Anexo);
                    xlSht.Unprotect(ExcelAddIn.Access.Configuration.PwsExcel);
                }
                //Asigna las formulas a las celdas al crear un nuevo archivo
                //De lo contrario si es transferir quita las formulas y asigna el valor del resultado de la formula.
                //Se agina el progreso del ProgessBar según la cantidad de celdas divididas entre 16.
                foreach (oComprobacion _Comprobacion in _Comprobaciones.Where(o => o.IdTipoPlantilla == Convert.ToInt32(1)).ToArray())
                {
                    _Comprobacion.setFormulaExcel();
                    xlSht = (Excel.Worksheet)wb.Worksheets.get_Item(_Comprobacion.Destino.Anexo);
                    Excel.Range _Range = (Excel.Range)xlSht.get_Range(_Comprobacion.Destino.CeldaExcel);

                    if (x == 0)
                    {
                        xlSht.Activate();
                    }
                    _Range.NumberFormat = "0.00";
                    if (_Comprobacion.EsValida() && _Comprobacion.EsFormula())
                    {
                        _Range.Formula = $"={_Comprobacion.FormulaExcel}";
                    }
                    else if (_Comprobacion.EsValida() && !_Comprobacion.EsFormula())
                    {
                        _Range.Value = _Comprobacion.FormulaExcel;
                    }
                    //Barra de Progreso.
                    x++;
                    r = x % 16;
                    if (r == 0.00)
                    {
                        progress += 10;
                        if (progress < 100)
                        {
                            fnProgressBar(progress);
                        }
                    }
                }
                //Se guarda el archivo original.
                wb.Save();
            }
            if (_Form != null)
            {
                _Form.Close();
            }
            this.Close();
        }
        private void CreatePDF(oCruce[] _result, oCruce[] cruces, string path, string NombreLibro)
        {
            var fecha    = DateTime.Now;
            var name     = "Cruce_" + fecha.Year.ToString() + fecha.Month.ToString() + fecha.Day.ToString() + fecha.Hour.ToString() + fecha.Minute.ToString() + fecha.Second.ToString();
            var filepath = path + "\\" + name + ".pdf";
            // Creamos el documento con el tamaño de página tradicional
            Document doc = new Document(PageSize.LETTER);
            // Indicamos donde vamos a guardar el documento
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filepath, FileMode.Create));

            // Le colocamos el título y el autor
            // **Nota: Esto no será visible en el documento
            doc.AddTitle("Curces");
            doc.AddCreator("D-SAT");
            // Abrimos el archivo
            doc.Open();
            // Creamos el tipo de Font que vamos utilizar
            iTextSharp.text.Font titlefont         = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font _standardFont     = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 7, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            iTextSharp.text.Font _standardFontbold = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 7, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            // Escribimos el encabezado en el documento
            //doc.Add(new Paragraph("eISSIF XML 17"));
            //doc.Add(new Paragraph("Cruces", _standardFont));
            //doc.Add(new Paragraph("SIPRED - ESTADOS FINANCIEROS GENERAL"));

            var titulo = new Paragraph("eISSIF XML 17", titlefont);

            titulo.Alignment = Element.ALIGN_CENTER;
            doc.Add(titulo);

            titulo           = new Paragraph(NombreLibro, titlefont);
            titulo.Alignment = Element.ALIGN_CENTER;
            doc.Add(titulo);

            titulo           = new Paragraph("Informe de Cruces: Diferencias", titlefont);
            titulo.Alignment = Element.ALIGN_CENTER;
            doc.Add(titulo);

            PdfPTable tblHeader = new PdfPTable(7);

            tblHeader.WidthPercentage = 100;
            PdfPCell cellNum = new PdfPCell(new Phrase("Número", titlefont));

            cellNum.BorderWidth       = 0;
            cellNum.BorderWidthTop    = 0.75f;
            cellNum.BorderWidthBottom = 0.75f;
            cellNum.BorderColorTop    = new BaseColor(Color.Blue);
            cellNum.BorderColorBottom = new BaseColor(Color.White);

            PdfPCell cellconc = new PdfPCell(new Phrase("Concepto", titlefont));

            cellconc.BorderWidth       = 0;
            cellconc.BorderWidthTop    = 0.75f;
            cellconc.BorderWidthBottom = 0.75f;
            cellconc.BorderColorTop    = new BaseColor(Color.Blue);
            cellconc.BorderColorBottom = new BaseColor(Color.White);
            cellconc.Colspan           = 6;

            tblHeader.AddCell(cellNum);
            tblHeader.AddCell(cellconc);

            PdfPCell col1 = new PdfPCell(new Phrase("", titlefont));

            col1.BorderWidth       = 0;
            col1.BorderWidthTop    = 0.75f;
            col1.BorderWidthBottom = 0.75f;
            col1.BorderColorBottom = new BaseColor(Color.Blue);
            col1.BorderColorTop    = new BaseColor(Color.White);

            PdfPCell col2 = new PdfPCell(new Phrase("Índice", titlefont));

            col2.BorderWidth       = 0;
            col2.BorderWidthTop    = 0.75f;
            col2.BorderWidthBottom = 0.75f;
            col2.BorderColorBottom = new BaseColor(Color.Blue);
            col2.BorderColorTop    = new BaseColor(Color.White);

            PdfPCell col3 = new PdfPCell(new Phrase("Col.", titlefont));

            col3.BorderWidth       = 0;
            col3.BorderWidthTop    = 0.75f;
            col3.BorderWidthBottom = 0.75f;
            col3.BorderColorBottom = new BaseColor(Color.Blue);
            col3.BorderColorTop    = new BaseColor(Color.White);

            PdfPCell col4 = new PdfPCell(new Phrase("Concepto", titlefont));

            col4.BorderWidth       = 0;
            col4.BorderWidthTop    = 0.75f;
            col4.BorderWidthBottom = 0.75f;
            col4.BorderColorBottom = new BaseColor(Color.Blue);
            col4.BorderColorTop    = new BaseColor(Color.White);
            col4.Colspan           = 2;

            PdfPCell col6 = new PdfPCell(new Phrase("Gpo. 1", titlefont));

            col6.BorderWidth       = 0;
            col6.BorderWidthTop    = 0.75f;
            col6.BorderWidthBottom = 0.75f;
            col6.BorderColorBottom = new BaseColor(Color.Blue);
            col6.BorderColorTop    = new BaseColor(Color.White);

            PdfPCell col7 = new PdfPCell(new Phrase("Gpo. 2", titlefont));

            col7.BorderWidth       = 0;
            col7.BorderWidthTop    = 0.75f;
            col7.BorderWidthBottom = 0.75f;
            col7.BorderColorBottom = new BaseColor(Color.Blue);
            col7.BorderColorTop    = new BaseColor(Color.White);

            tblHeader.AddCell(col1);
            tblHeader.AddCell(col2);
            tblHeader.AddCell(col3);
            tblHeader.AddCell(col4);
            tblHeader.AddCell(col6);
            tblHeader.AddCell(col7);
            doc.Add(Chunk.NEWLINE);

            foreach (var item in _result)
            {
                PdfPCell cellid = new PdfPCell(new Phrase(item.IdCruce.ToString(), titlefont));
                cellid.BorderWidth     = 0;
                cellid.BorderWidthTop  = 1;
                cellid.BorderColorTop  = new BaseColor(Color.White);
                cellid.BackgroundColor = new BaseColor(Color.Gray);

                var      strConcepto  = cruces.Where(c => c.IdCruce == item.IdCruce).FirstOrDefault();
                PdfPCell cellconcepto = new PdfPCell(new Phrase(strConcepto.Concepto, titlefont));
                cellconcepto.BorderWidth     = 0;
                cellconcepto.BorderWidthTop  = 1;
                cellconcepto.BorderColorTop  = new BaseColor(Color.White);
                cellconcepto.Colspan         = 6;
                cellconcepto.BackgroundColor = new BaseColor(Color.Gray);

                tblHeader.AddCell(cellid);
                tblHeader.AddCell(cellconcepto);

                PdfPCell cellformula = new PdfPCell(new Phrase(item.Formula, _standardFont));
                cellformula.BorderWidth = 0;
                cellformula.Colspan     = 7;
                tblHeader.AddCell(cellformula);

                if (item.Condicion != null || item.Condicion.Length > 0)
                {
                    PdfPCell cellcondicion = new PdfPCell(new Phrase(item.Condicion, _standardFont));
                    cellcondicion.BorderWidth = 0;
                    cellcondicion.Colspan     = 7;
                    tblHeader.AddCell(cellcondicion);
                }

                var formula1 = item.Formula.Split('=')[0];
                var formula2 = item.Formula.Split('=')[1];

                var valor = 1;
                foreach (var detail in item.CeldasFormula)
                {
                    var color = Color.LightGray;

                    if ((valor % 2) == 0)
                    {
                        color = Color.White;
                    }

                    PdfPCell cellanexo = new PdfPCell(new Phrase(detail.Anexo, _standardFont));
                    cellanexo.BorderWidth     = 0;
                    cellanexo.BackgroundColor = new BaseColor(color);
                    PdfPCell cellindice = new PdfPCell(new Phrase(detail.Indice, _standardFont));
                    cellindice.BorderWidth     = 0;
                    cellindice.BackgroundColor = new BaseColor(color);
                    PdfPCell cellcolumna = new PdfPCell(new Phrase(Generales.ColumnAdress(detail.Columna), _standardFont));
                    cellcolumna.BorderWidth     = 0;
                    cellcolumna.BackgroundColor = new BaseColor(color);
                    PdfPCell cellconceptodet = new PdfPCell(new Phrase(detail.Concepto, _standardFont));
                    cellconceptodet.BorderWidth     = 0;
                    cellconceptodet.BackgroundColor = new BaseColor(color);
                    cellconceptodet.Colspan         = 2;

                    var strgpo1 = string.Empty;
                    var strgpo2 = string.Empty;

                    if (detail.Original != "")
                    {
                        if (formula1.Contains(detail.Original))
                        {
                            strgpo1 = detail.Valor == "0" ? "" : detail.Valor;
                        }

                        if (formula2.Contains(detail.Original))
                        {
                            strgpo2 = detail.Valor == "0" ? "" : detail.Valor;
                        }
                    }
                    else
                    {
                        if (detail.Grupo == 0)
                        {
                            strgpo1 = detail.Valor == "0" ? "" : detail.Valor;
                        }
                        else
                        if (detail.Grupo == 1)
                        {
                            strgpo2 = detail.Valor == "0" ? "" : detail.Valor;
                        }
                    }
                    PdfPCell cellgpo1 = new PdfPCell(new Phrase(strgpo1, _standardFont));
                    cellgpo1.BorderWidth         = 0;
                    cellgpo1.BackgroundColor     = new BaseColor(color);
                    cellgpo1.HorizontalAlignment = Element.ALIGN_RIGHT;

                    PdfPCell cellgpo2 = new PdfPCell(new Phrase(strgpo2, _standardFont));
                    cellgpo2.BorderWidth         = 0;
                    cellgpo2.BackgroundColor     = new BaseColor(color);
                    cellgpo2.HorizontalAlignment = Element.ALIGN_RIGHT;

                    tblHeader.AddCell(cellanexo);
                    tblHeader.AddCell(cellindice);
                    tblHeader.AddCell(cellcolumna);
                    tblHeader.AddCell(cellconceptodet);
                    tblHeader.AddCell(cellgpo1);
                    tblHeader.AddCell(cellgpo2);

                    valor++;
                }

                PdfPCell cellcalc = new PdfPCell(new Phrase("Cálculos", _standardFontbold));
                cellcalc.BorderWidth         = 0;
                cellcalc.HorizontalAlignment = Element.ALIGN_RIGHT;
                cellcalc.Colspan             = 5;

                PdfPCell cellgpot1 = new PdfPCell(new Phrase(item.Grupo1, _standardFont));
                cellgpot1.BorderWidth         = 0;
                cellgpot1.HorizontalAlignment = Element.ALIGN_RIGHT;

                PdfPCell cellgpot2 = new PdfPCell(new Phrase(item.Grupo2, _standardFont));
                cellgpot2.BorderWidth         = 0;
                cellgpot2.HorizontalAlignment = Element.ALIGN_RIGHT;

                tblHeader.AddCell(cellcalc);
                tblHeader.AddCell(cellgpot1);
                tblHeader.AddCell(cellgpot2);

                PdfPCell celldifempty = new PdfPCell(new Phrase(" ", _standardFont));
                celldifempty.BorderWidth = 1;
                celldifempty.BorderColor = new BaseColor(Color.White);
                celldifempty.Colspan     = 5;

                PdfPCell celldifText = new PdfPCell(new Phrase("Diferencia", _standardFontbold));
                celldifText.BorderWidth     = 1;
                celldifText.BorderColor     = new BaseColor(Color.White);
                celldifText.BackgroundColor = new BaseColor(Color.LightGray);

                PdfPCell celldif = new PdfPCell(new Phrase(item.Diferencia, _standardFontbold));
                celldif.BorderWidth         = 1;
                celldif.BorderColor         = new BaseColor(Color.White);
                celldif.HorizontalAlignment = Element.ALIGN_RIGHT;
                celldifText.BackgroundColor = new BaseColor(Color.LightGray);

                tblHeader.AddCell(celldifempty);
                tblHeader.AddCell(celldifText);
                tblHeader.AddCell(celldif);
            }

            doc.Add(tblHeader);

            doc.Close();
            writer.Close();

            Process.Start(filepath);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Carga el Grid 2-Formulas y la descripción de la misma segun el click que haga el usuario en el Grid  1- Cruces
        /// </summary>
        /// <param name="Row"></param>
        private void CrucesCLick(int Row)
        {
            try
            {
                if (Row >= 0)
                {
                    int IDCruce = Convert.ToInt32(DtCruces.Rows[Row].Cells[0].Value.ToString());
                    int IdTp    = Convert.ToInt32(cmbTipo.SelectedValue);

                    Workbook  wb          = Globals.ThisAddIn.Application.ActiveWorkbook;
                    Worksheet xlSht       = null;
                    Range     currentCell = null;
                    Range     currentFind = null;
                    oCruce    _Cruce      = _Cruces.Where(o => o.IdCruce == IDCruce).FirstOrDefault();

                    _Cruce.setCeldas();
                    List <oCelda> CeldaNws = new List <oCelda>();
                    foreach (oCelda _Celda in _Cruce.CeldasFormula)
                    {
                        xlSht = (Worksheet)wb.Worksheets.get_Item(_Celda.Anexo);
                        int _maxValue = xlSht.UsedRange.SpecialCells(XlCellType.xlCellTypeLastCell).Row;

                        currentCell = (Range)xlSht.get_Range("A1", "A" + (_maxValue).ToString());
                        currentFind = currentCell.Find(_Celda.Indice, Type.Missing, XlFindLookIn.xlValues, XlLookAt.xlPart,
                                                       XlSearchOrder.xlByRows, XlSearchDirection.xlNext, false,
                                                       Type.Missing, Type.Missing);

                        _Celda.Fila = currentFind.Row;

                        currentCell = (Range)xlSht.Cells[_Celda.Fila, 2];
                        if (currentCell.get_Value(Type.Missing) != null)
                        {
                            _Celda.Concepto = currentCell.get_Value(Type.Missing).ToString();
                        }
                        else
                        {
                            _Celda.Concepto = "";
                        }

                        CeldaNws.Add(_Celda);
                    }

                    var _FormulaI = (from x in CeldaNws
                                     select new
                    {
                        Anexo = x.Anexo,
                        Indice = x.Indice,
                        x.Concepto,
                        Col = Generales.ColumnAdress(x.Columna),
                        CodSAT = ""
                    }).ToList();

                    DtFormula.DataSource = ToDataTable(_FormulaI);
                    txtDetalle.Text      = "Cruce: " + _Cruce.Formula + System.Environment.NewLine + "Condición: " + _Cruce.Condicion;
                }
                else
                {
                    DtFormula.DataSource = null;
                    txtDetalle.Text      = "";
                }
            }
            catch
            {
                this.Hide();
                MessageBox.Show("Archivo no válido, favor de generar el archivo mediante el AddIn D.SAT", "Información Incorrecta", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 4
0
        private void btnEliminar_Click(object sender, EventArgs e)
        {
            bool   _Connection = new lSerializados().CheckConnection(Configuration.UrlConnection);
            string _Message    = "No existe conexión con el servidor de datos... Contacte a un Administrador de Red para ver las opciones de conexión.";
            string _Title      = "Conexión de Red";

            if (_Connection)
            {
                int           Row           = DtComprobaciones.CurrentCell.RowIndex;
                int           IDcompro      = Convert.ToInt32(DtComprobaciones.Rows[Row].Cells[0].Value.ToString());
                oComprobacion _Comprobacion = _Comprobaciones.Where(o => o.IdComprobacion == IDcompro).FirstOrDefault();
                DialogResult  dialogo       = MessageBox.Show("Desea eliminar fórmula número " + IDcompro.ToString() + "?",
                                                              "Confirme", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (dialogo == DialogResult.Yes)
                {
                    _Message = ((cmbTipo.SelectedIndex == 0) ? "- Debe seleccionar un tipo de plantilla" : "");
                    if (_Message.Length > 0)
                    {
                        MessageBox.Show(_Message, "Información Faltante", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    if (_Comprobacion.AdmiteCambios == 0)
                    {
                        MessageBox.Show("La fórmula no puede ser eliminada ya que es un cálculo de " + cmbTipo.Text, "Eliminar", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    DialogResult _response = DialogResult.None;

                    oComprobacion _Template = new oComprobacion()
                    {
                        IdComprobacion  = IDcompro,
                        IdTipoPlantilla = cmbTipo.SelectedIndex,
                        Concepto        = "",
                        Formula         = "",
                        Condicion       = "",
                        Nota            = ""
                    };
                    KeyValuePair <bool, string[]> _result = new lComprobacionesAdmin(_Template, "E").Delete();
                    string _Messages = "";
                    foreach (string _Msg in _result.Value)
                    {
                        _Messages += ((_Messages.Length > 0) ? "\r\n" : "") + _Msg;
                    }
                    if (_result.Key && _response != DialogResult.Yes)
                    {
                        _Messages = "Fórmula eliminada con éxito";
                    }
                    MessageBox.Show(_Messages, (_result.Key) ? "Proceso Existoso" : "Información Faltante", MessageBoxButtons.OK, (_result.Key) ? MessageBoxIcon.Information : MessageBoxIcon.Exclamation);

                    if (_result.Key)
                    {
                        string       _Path      = Configuration.Path;
                        oPlantilla[] _Templates = Assembler.LoadJson <oPlantilla[]>($"{_Path}\\jsons\\Plantillas.json");
                        oPlantilla   _Temp      = _Templates.FirstOrDefault(o => o.IdTipoPlantilla == _Template.IdTipoPlantilla && o.Anio == (int)cmbAnio.SelectedValue);

                        //Libro Actual de Excel.
                        Excel.Worksheet xlSht;
                        Excel.Workbook  wb         = Globals.ThisAddIn.Application.ActiveWorkbook;
                        string[]        Formula    = _Comprobacion.Formula.Split('=');
                        string[]        _celdaBase = Formula[0].Replace("[", "").Replace("]", "").Split(',');
                        string[]        _celdaFin  = Formula[1].Replace("[", "").Replace("]", "").Split(',');
                        Excel.Range     _RangeO;
                        Excel.Range     _RangeR;

                        xlSht = (Excel.Worksheet)wb.Worksheets.get_Item(_celdaBase[0]);
                        for (int a = 1; a < 1000; a++)
                        {
                            _RangeO = (Excel.Range)xlSht.get_Range($"A" + a.ToString());

                            if (_RangeO != null)
                            {
                                if (_RangeO.Value.ToString() == _celdaBase[1])
                                {
                                    _RangeR              = (Excel.Range)xlSht.get_Range($"{Generales.ColumnAdress(Int32.Parse(_celdaBase[2]))}" + a.ToString());
                                    _RangeR.Formula      = "";
                                    _RangeR.Value        = "";
                                    _RangeR.NumberFormat = "@";
                                    _RangeR.Value2       = "";

                                    a = 1001;
                                }
                            }
                        }
                        FileJson(_Temp, cmbTipo.SelectedIndex.ToString());
                        this.Hide();
                    }
                }
            }
            else
            {
                MessageBox.Show(_Message, _Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 5
0
        /// <summary>Función para Insertar el Indice.
        /// <para>Inserta el Indice en el archivo de Excel. Referencia: <see cref="InsertIndice(Excel.Worksheet, int, Excel.Range, bool, int)"/> se agrega la referencia ExcelAddIn.Generales para invocarla.</para>
        /// <seealso cref="InsertIndice(Excel.Worksheet, int, Excel.Range, bool, int)"/>
        /// </summary>
        public static void InsertIndice(Excel.Worksheet xlSht, int CantReg, Excel.Range currentCell, bool ConFormula, int NroPrincipal)
        {
            Worksheet sheet = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet);

            Excel.Workbook wb         = Globals.ThisAddIn.Application.ActiveWorkbook;
            string         _NameFile  = wb.Name;
            string         _AnexoFile = sheet.Name;
            FileInfo       _Excel     = new FileInfo(Globals.ThisAddIn.Application.ActiveWorkbook.FullName);

            Excel.Range currentFind     = null;
            Excel.Range currentFindExpl = null;

            Excel.Range RangeLocked   = null;
            int         NroRow        = currentCell.Row;
            int         NroColumn     = currentCell.Column;
            string      IndicePrevio  = "";
            long        IndiceInicial = 0;

            int  iTotalColumns = 0;
            int  k             = 1;
            int  i             = 1;
            long indiceNvo     = 0;
            int  CantExpl      = 0;

            currentCell     = (Excel.Range)xlSht.Cells[NroRow, 1];
            IndicePrevio    = currentCell.get_Value(Type.Missing).ToString();
            currentFindExpl = (Excel.Range)xlSht.Cells[NroRow + 1, 1];

            if (currentFindExpl.get_Value(Type.Missing) != null)
            {
                if (currentFindExpl.get_Value(Type.Missing).ToString().ToUpper().Trim() == "EXPLICACION")
                {
                    NroRow++;
                }
            }

            IndiceInicial = Convert.ToInt64(IndicePrevio) + 100;
            int        rowexpl = 0;
            List <int> FilasExplicacion = new List <int>();
            int        CantRango = 0; long IndiceInicialx = IndiceInicial;

            foreach (Excel.Name cname in Globals.ThisAddIn.Application.Names)
            {
                if (cname.Name == "IA_0" + Convert.ToString(IndiceInicialx))
                {
                    CantRango++;
                    IndiceInicialx  = IndiceInicialx + 100;
                    rowexpl         = cname.RefersToRange.Cells.Row + 1;
                    currentFindExpl = (Excel.Range)xlSht.Cells[rowexpl, 1];

                    if (currentFindExpl.get_Value(Type.Missing) != null)
                    {
                        if (currentFindExpl.get_Value(Type.Missing).ToString().ToUpper().Trim() == "EXPLICACION")
                        {
                            CantExpl++;
                            if (!FilasExplicacion.Contains(rowexpl + CantReg))//los indices que tienen explicacion la fila actual + los registros que ingresó nvos
                            {
                                FilasExplicacion.Add(rowexpl + CantReg);
                            }
                        }
                    }
                }
            }

            currentFind = currentCell.Find(IndiceInicial, Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
                                           Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false,
                                           Type.Missing, Type.Missing);

            int NroRowx = 0;

            CantRango = CantRango + CantExpl;
            int NroPrincipalAux = DameRangoPrincipal(NroPrincipal, xlSht);

            while (i <= CantReg)
            {
                indiceNvo = Convert.ToInt64(IndicePrevio) + 100;
                Excel.Range rangej = xlSht.get_Range(string.Format("{0}:{0}", NroRow + i, Type.Missing));
                rangej.Select();
                rangej.Insert(Excel.XlInsertShiftDirection.xlShiftDown, Excel.XlInsertFormatOrigin.xlFormatFromLeftOrAbove);

                var rangeall   = xlSht.get_Range(string.Format("{0}:{0}", NroPrincipalAux - 1, Type.Missing));
                var rangeaCopy = xlSht.get_Range(string.Format("{0}:{0}", NroRow + i, Type.Missing));
                iTotalColumns = xlSht.UsedRange.Columns.Count;
                rangeall.Copy();
                rangeaCopy.PasteSpecial(Excel.XlPasteType.xlPasteFormulas, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
                rangeaCopy.Locked = false;

                k = 1;

                while (k <= iTotalColumns)
                {
                    if (!(rangeaCopy.Cells[k].HasFormula))
                    {
                        rangeaCopy.Cells[k].Value = "";
                    }

                    k = k + 1;
                }

                xlSht.Cells[NroRow + i, 1] = "0" + Convert.ToString(indiceNvo);
                sheet.Controls.Remove("IA_0" + indiceNvo);
                AddNamedRange(NroRow + i, 1, "IA_0" + Convert.ToString(indiceNvo));
                currentCell  = (Excel.Range)xlSht.Cells[NroRow + i, 1];
                IndicePrevio = currentCell.get_Value(Type.Missing).ToString();
                //currentCell = xlSht.Range[xlSht.Cells[NroRow + i, 1], xlSht.Cells[NroRow + i, 3]];
                //currentCell.Font.Color = System.Drawing.Color.FromArgb(0, 0, 255);

                ((Excel.Range)xlSht.Cells[NroRow + 1, 2]).NumberFormat = "General"; // le doy formato text al concepto
                ((Excel.Range)xlSht.Cells[NroRow + 1, 2]).WrapText     = true;
                RangeLocked        = (Excel.Range)xlSht.Cells[NroRow + i, 1];
                RangeLocked.Locked = true; // con esto bloqueo solo la primera columna

                i++;
            }

            if (currentFind != null)
            {
                NroRowx      = NroRow + CantReg;
                currentCell  = (Excel.Range)xlSht.Cells[NroRowx, 1];
                IndicePrevio = currentCell.get_Value(Type.Missing).ToString();

                int j = 1;

                while (j <= CantRango)
                {
                    if (!FilasExplicacion.Contains(NroRowx + j))
                    {
                        indiceNvo = Convert.ToInt64(IndicePrevio) + 100;
                        xlSht.Cells[NroRowx + j, 1] = "0" + Convert.ToString(indiceNvo);
                        sheet.Controls.Remove("IA_0" + indiceNvo);
                        AddNamedRange(NroRowx + j, 1, "IA_0" + Convert.ToString(indiceNvo));
                        currentCell  = (Excel.Range)xlSht.Cells[NroRowx + j, 1];
                        IndicePrevio = currentCell.get_Value(Type.Missing).ToString();
                    }

                    j++;
                }
            }

            string           NombreHoja = xlSht.Name.ToUpper().Replace(" ", "");
            List <oSubtotal> ColumnasST = DameColumnasST((NombreHoja));

            Excel.Range Sum_Range = null;
            int         NroFinal  = NroRow + CantReg + CantRango;

            int    _Rango = 0;
            string _Renglon;
            string _Columna;
            string _rCelda = "";

            foreach (oSubtotal ST in ColumnasST)
            {
                Sum_Range         = xlSht.get_Range(ST.Columna + (NroPrincipalAux).ToString(), ST.Columna + (NroPrincipalAux).ToString());
                Sum_Range.Formula = "=sum(" + ST.Columna + (NroPrincipalAux + 1).ToString() + ":" + ST.Columna + (NroFinal).ToString() + ")";
                _Rango            = NroFinal - NroPrincipalAux; // nroprincipalaux siempre tiene el numero de la fila padre al restar te da la cantidad de rows insertadas
                _Renglon          = (Sum_Range.Row).ToString();
                _Columna          = Generales.ColumnAdress(Sum_Range.Column);
                _rCelda           = _Columna + "" + _Renglon;
                InsertarReferencia(_NameFile, _AnexoFile, _rCelda, _Rango, _Columna, _Renglon, CantReg);
            }

            Sum_Range = xlSht.get_Range("B" + (NroPrincipal).ToString(), "B" + (NroPrincipal).ToString());
            Sum_Range.Select();
        }
        private void btguardar_Click(object sender, EventArgs e)
        {
            bool   _Connection = new lSerializados().CheckConnection(Configuration.UrlConnection);
            string _Message    = "No existe conexión con el servidor de datos... Contacte a un Administrador de Red para ver las opciones de conexión.";
            string _Title      = "Conexión de Red";

            if (_Connection)
            {
                _Message  = (txtConcepto.Text.Trim() == "") ? "- Debe indicar concepto." : "";
                _Message += (txtcelda.Text.Trim() == "") ? ((_Message.Length > 0) ? "\r\n" : "") + "- Debe indicar celda." : "";
                _Message += (txtformula.Text.Trim() == "") ? ((_Message.Length > 0) ? "\r\n" : "") + "- Debe indicar fórmula." : "";
                _Message += (chkCondicionar.Checked && txtCondicion.Text.Trim() == "") ? ((_Message.Length > 0) ? "\r\n" : "") + "- Debe indicar condición." : "";

                if (_Message.Length > 0)
                {
                    MessageBox.Show(_Message, "Información Faltante", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                DialogResult _response = DialogResult.None;
                string       Formulax  = (txtcelda.Text + "=" + txtformula.Text);
                string       condicion = "";

                if (chkCondicionar.Checked)
                {
                    condicion = txtCondicion.Text;
                }


                oComprobacion _Template = new oComprobacion()
                {
                    IdComprobacion  = Convert.ToInt32(txtNro.Text),
                    IdTipoPlantilla = TpPlantilla,//buscar
                    Concepto        = txtConcepto.Text,
                    Formula         = Formulax,
                    Condicion       = condicion,
                    Nota            = txtNota.Text,
                };

                if (accion == "A")
                {
                    KeyValuePair <bool, string[]> _result = new lComprobacionesAdmin(_Template, accion).Add();

                    string _Messages = "";
                    foreach (string _Msg in _result.Value)
                    {
                        _Messages += ((_Messages.Length > 0) ? "\r\n" : "") + _Msg;
                    }
                    if (_result.Key && _response != DialogResult.Yes)
                    {
                        _Messages = "Comprobación agregada con éxito";
                    }
                    MessageBox.Show(_Messages, (_result.Key) ? "Proceso Existoso" : "Información Faltante", MessageBoxButtons.OK, (_result.Key) ? MessageBoxIcon.Information : MessageBoxIcon.Exclamation);
                    //if (_result.Key) this.Hide();
                }
                else
                if (accion == "M")
                {
                    KeyValuePair <bool, string[]> _result = new lComprobacionesAdmin(_Template, accion).Update();

                    string _Messages = "";
                    foreach (string _Msg in _result.Value)
                    {
                        _Messages += ((_Messages.Length > 0) ? "\r\n" : "") + _Msg;
                    }
                    if (_result.Key && _response != DialogResult.Yes)
                    {
                        _Messages = "Comprobación modificada con éxito";
                    }
                    MessageBox.Show(_Messages, (_result.Key) ? "Proceso Existoso" : "Información Faltante", MessageBoxButtons.OK, (_result.Key) ? MessageBoxIcon.Information : MessageBoxIcon.Exclamation);
                    //if (_result.Key) this.Hide();
                }

                string       _Path      = Configuration.Path;
                oPlantilla[] _Templates = Assembler.LoadJson <oPlantilla[]>($"{_Path}\\jsons\\Plantillas.json");
                oPlantilla   _Temp      = _Templates.FirstOrDefault(o => o.IdTipoPlantilla == _Template.IdTipoPlantilla && o.Anio == _iYear);

                if (_oComprobacion != null)
                {
                    //Libro Actual de Excel.
                    Excel.Worksheet xlSht;
                    Excel.Workbook  wb         = Globals.ThisAddIn.Application.ActiveWorkbook;
                    string[]        Formula    = _oComprobacion.Formula.Split('=');
                    string[]        _celdaBase = Formula[0].Replace("[", "").Replace("]", "").Split(',');
                    string[]        _celdaFin  = Formula[1].Replace("[", "").Replace("]", "").Split(',');
                    Excel.Range     _RangeO;
                    Excel.Range     _RangeR;

                    xlSht = (Excel.Worksheet)wb.Worksheets.get_Item(_celdaBase[0]);
                    for (int a = 1; a < 1000; a++)
                    {
                        _RangeO = (Excel.Range)xlSht.get_Range($"A" + a.ToString());

                        if (_RangeO != null)
                        {
                            if (_RangeO.Value.ToString() == _celdaBase[1])
                            {
                                _RangeR              = (Excel.Range)xlSht.get_Range($"{Generales.ColumnAdress(Int32.Parse(_celdaBase[2]))}" + a.ToString());
                                _RangeR.Formula      = "";
                                _RangeR.Value        = "";
                                _RangeR.NumberFormat = "@";
                                _RangeR.Value2       = "";

                                a = 1001;
                            }
                        }
                    }
                }

                _Form.Close();
                FileJson(_Temp, TpPlantilla.ToString());
                _Form.Show();
            }
            else
            {
                MessageBox.Show(_Message, _Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }