예제 #1
0
        public void DisplayText()
        {
            IWorksheet    worksheet    = this.workbook.Worksheets[2];
            IMigrantRange migrantRange = worksheet.MigrantRange;

            worksheet.UsedRangeIncludesFormatting = false;
            int           rowCount        = worksheet.UsedRange.LastRow;
            int           colCount        = worksheet.UsedRange.LastColumn;
            List <string> rowsList        = new List <string>();
            List <string> rowsContentList = new List <string>();

            for (int i = 8; i <= rowCount; i++)
            {
                //string rowValue = migrantRange.DisplayText.ToString();
                //rowsList.Append<string>(rowValue);
                string value = "";
                for (int j = 1; j <= colCount; j++)
                {
                    migrantRange.ResetRowColumn(i, j);
                    value = value + " - " + migrantRange.DisplayText;
                }

                Console.WriteLine(value);
            }
            //IRange[] cells = worksheet["A8:C40"].Cells;


            //give value of each cell in range

            /*foreach (IRange cell in cells)
             * {
             *  string cellValue = cell.DisplayText.ToString();
             *
             *  //Console.WriteLine(cellValue);
             * }*/

            //give value of each row in range
            //IRange[] rows = worksheet["A8:"].Rows;


            /*foreach (IRange row in rows)
             * {
             *  row.ToArray();
             *  display value of the first cell of the row
             *  string rowValue = row.DisplayText.ToString();
             *  Console.WriteLine(rowValue);
             *
             *
             * }*/

            //string displayText = worksheet.Range["C8:C10"].DisplayText;
            //getrange of cells and display a part of them
            //IRange range = worksheet.Range[1, 8, 16, 534];
            //string displayText = range[1, 9, 4, 20].Text;
            //string displayText = worksheet.GetValueRowCol(8, 3).ToString();

            worksheet.UsedRangeIncludesFormatting = false;
            Console.WriteLine(worksheet.UsedRange.AddressLocal);
            Close();
        }
예제 #2
0
        private void btnCreate_Click(object sender, System.EventArgs e)
        {
            if (!(int.TryParse(numRowCount.Text, out rowCount) && int.TryParse(numColCount.Text, out colCount)))
            {
                MessageBox.Show("Enter Numerical Value");
                return;
            }

            if (rowCount <= 0)
            {
                MessageBox.Show("Invalid row count");
                return;
            }

            if (colCount <= 0)
            {
                MessageBox.Show("Invalid column count");
                return;
            }
            if (rdbExcel97.Checked)
            {
                if (colCount > 256)
                {
                    MessageBox.Show("Column count must be less than or equal to 256 for Excel 2003 format.");
                    return;
                }
                if (rowCount > 65536)
                {
                    MessageBox.Show("Row count must be less than or equal to 65,536 for Excel 2003 format.");
                    return;
                }
            }
            if (rdbExcel2007.Checked || rdbExcel2010.Checked || rdbExcel2013.Checked)
            {
                if (rowCount > 100001)
                {
                    MessageBox.Show("Row count must be less than or equal to 100,000.");
                    return;
                }
                if (colCount > 151)
                {
                    MessageBox.Show("Column count must be less than or equal to 151.");
                    return;
                }
            }

            #region Starttime
            //Start Time

            #endregion

            #region Initialize Workbook
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;
            //Set the Default version as Excel 97to2003
            if (this.rdbExcel97.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel97to2003;
                fileName = "PerformanceChecking.xls";
            }
            //Set the Default version as Excel 2007
            else if (this.rdbExcel2007.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2007;
                fileName = "PerformanceChecking.xlsx";
            }
            //Set the Default version as Excel 2010
            else if (this.rdbExcel2010.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2010;
                fileName = "PerformanceChecking.xlsx";
            }
            //Set the Default version as Excel 2013
            else if (this.rdbExcel2013.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2013;
                fileName = "PerformanceChecking.xlsx";
            }
            //A new workbook is created.[Equivalent to creating a new workbook in MS Excel]
            //The new workbook will have 3 worksheets
            IWorkbook workbook = application.Workbooks.Create(3);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet worksheet = workbook.Worksheets[0];

            startTime = DateTime.Now;
            workbook.DetectDateTimeInValue = false;
            #endregion


            if (chbColumnStyle.Checked)
            {
                //Body Style
                IStyle bodyStyle = workbook.Styles.Add("BodyStyle");
                bodyStyle.BeginUpdate();

                //Add custom colors to the palette.
                workbook.SetPaletteColor(9, Color.FromArgb(239, 243, 247));
                bodyStyle.Color = Color.FromArgb(239, 243, 247);
                bodyStyle.Borders[ExcelBordersIndex.EdgeLeft].LineStyle  = ExcelLineStyle.Thin;
                bodyStyle.Borders[ExcelBordersIndex.EdgeRight].LineStyle = ExcelLineStyle.Thin;
                bodyStyle.EndUpdate();

                worksheet.SetDefaultColumnStyle(1, colCount, bodyStyle);
            }
            if (this.chkImportOnSave.Checked)
            {
                DataTable dataTable = new DataTable();
                for (int column = 1; column <= colCount; column++)
                {
                    dataTable.Columns.Add("Column: " + column.ToString(), typeof(int));
                }
                //Adding data into data table
                for (int row = 1; row < rowCount; row++)
                {
                    dataTable.Rows.Add();
                    for (int column = 1; column <= colCount; column++)
                    {
                        dataTable.Rows[row - 1][column - 1] = row * column;
                    }
                }
                startTime = DateTime.Now;
                worksheet.ImportDataTable(dataTable, 1, 1, true, true);
            }
            else
            {
                #region Apply Style
                //Header Style
                IStyle headerStyle = workbook.Styles.Add("HeaderStyle");

                headerStyle.BeginUpdate();
                //Add custom colors to the palette.
                workbook.SetPaletteColor(8, Color.FromArgb(255, 174, 33));
                headerStyle.Color     = Color.FromArgb(255, 174, 33);
                headerStyle.Font.Bold = true;
                headerStyle.Borders[ExcelBordersIndex.EdgeLeft].LineStyle   = ExcelLineStyle.Thin;
                headerStyle.Borders[ExcelBordersIndex.EdgeRight].LineStyle  = ExcelLineStyle.Thin;
                headerStyle.Borders[ExcelBordersIndex.EdgeTop].LineStyle    = ExcelLineStyle.Thin;
                headerStyle.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin;
                headerStyle.EndUpdate();
                #endregion
                IMigrantRange migrantRange = worksheet.MigrantRange;
                for (int column = 1; column <= colCount; column++)
                {
                    migrantRange.ResetRowColumn(1, column);
                    migrantRange.Text      = "Column: " + column.ToString();
                    migrantRange.CellStyle = headerStyle;
                }

                #region Insert Data
                //Writing Data using normal interface
                for (int row = 2; row <= rowCount; row++)
                {
                    //double columnSum = 0.0;
                    for (int column = 1; column <= colCount; column++)
                    {
                        //Writing number
                        migrantRange.ResetRowColumn(row, column);
                        migrantRange.Number = row * column;
                    }
                }
            }
            #endregion

            #region Workook Save
            workbook.SaveAs(fileName);
            #endregion

            #region Workbook Save and Dispose
            //Close the workbook
            workbook.Close();
            //Dispose the Excel Engine
            excelEngine.Dispose();
            #endregion

            #region Set EndTime and get LogDetails
            //End Time
            endTime = DateTime.Now - startTime;
            LogDetails(endTime);
            #endregion

            #region View the Workbook
            //Message box confirmation to view the created spreadsheet.
            if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo(fileName)
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                Process.Start(fileName);
#endif
            }
            #endregion
        }
예제 #3
0
        public ActionResult Performance(string SaveOption, string Import, string rowCount, string colCount)
        {
            if (SaveOption == null)
            {
                return(View());
            }

            int rows    = Convert.ToInt32(rowCount);
            int columns = Convert.ToInt32(colCount);

            if (SaveOption == "Xls")
            {
                if (columns > 256)
                {
                    Response.Write("<script LANGUAGE='JavaScript' >alert('Column count must be less than or equal to 256 for Excel 2003 format.');document.location='" + VirtualPathUtility.ToAbsolute("~/XlsIO/Performance") + "';</script>");
                    return(View());
                }
                if (rows > 65536)
                {
                    Response.Write("<script LANGUAGE='JavaScript' >alert('Row count must be less than or equal to 65,536 for Excel 2003 format.');document.location='" + VirtualPathUtility.ToAbsolute("~/XlsIO/Performance") + "';</script>");
                    return(View());
                }
            }
            if (SaveOption == "Xlsx")
            {
                if (rows > 100001)
                {
                    Response.Write("<script LANGUAGE='JavaScript' >alert('Row count must be less than or equal to 100,000.');document.location='" + VirtualPathUtility.ToAbsolute("~/XlsIO/Performance") + "';</script>");
                    return(View());
                }
                if (columns > 151)
                {
                    Response.Write("<script LANGUAGE='JavaScript' >alert('Column count must be less than or equal to 151.');document.location='" + VirtualPathUtility.ToAbsolute("~/XlsIO/Performance") + "';</script>");
                    return(View());
                }
            }
            //New instance of XlsIO is created.[Equivalent to launching Microsoft Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();

            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;
            IWorkbook    workbook;

            if (SaveOption == "Xlsx")
            {
                application.DefaultVersion = ExcelVersion.Excel2016;
            }
            else
            {
                application.DefaultVersion = ExcelVersion.Excel97to2003;
            }

            workbook = application.Workbooks.Create(1);

            IWorksheet sheet = workbook.Worksheets[0];

            if (Import == "importonsave")
            {
                workbook.Version = ExcelVersion.Excel2013;
                DataTable dataTable = new DataTable();
                for (int column = 1; column <= columns; column++)
                {
                    dataTable.Columns.Add("Column: " + column.ToString(), typeof(int));
                }
                //Adding data into data table
                for (int row = 1; row < rows; row++)
                {
                    dataTable.Rows.Add();
                    for (int column = 1; column <= columns; column++)
                    {
                        dataTable.Rows[row - 1][column - 1] = row * column;
                    }
                }
                sheet.ImportDataTable(dataTable, 1, 1, true, true);
            }
            else
            {
                IMigrantRange migrantRange = sheet.MigrantRange;

                for (int column = 1; column <= columns; column++)
                {
                    migrantRange.ResetRowColumn(1, column);
                    migrantRange.SetValue("Column: " + column.ToString());
                }

                //Writing Data using normal interface
                for (int row = 2; row <= rows; row++)
                {
                    //double columnSum = 0.0;
                    for (int column = 1; column <= columns; column++)
                    {
                        //Writing number
                        migrantRange.ResetRowColumn(row, column);
                        migrantRange.SetValue(row * column);
                    }
                }
            }
            try
            {
                if (SaveOption == "Xls")
                {
                    return(excelEngine.SaveAsActionResult(workbook, "Performance.xls", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel97));
                }
                else
                {
                    return(excelEngine.SaveAsActionResult(workbook, "Performance.xlsx", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel2016));
                }
            }
            catch (Exception)
            {
            }

            //Close the workbook.
            workbook.Close();
            excelEngine.Dispose();
            return(View());
        }
        private void Button1_Click(object sender, EventArgs e)
        {
            int rowCount = Convert.ToInt32(textBox1.Value);
            int colCount = Convert.ToInt32(textBox2.Value);
            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();

            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;
            IWorkbook    workbook;

            workbook = application.Workbooks.Create(1);
            IWorksheet sheet = workbook.Worksheets[0];

            if (chkImport.Checked)
            {
                workbook.Version = ExcelVersion.Excel2013;
                DataTable dataTable = new DataTable();
                for (int column = 1; column <= colCount; column++)
                {
                    dataTable.Columns.Add("Column: " + column.ToString(), typeof(int));
                }
                //Adding data into data table
                for (int row = 1; row < rowCount; row++)
                {
                    dataTable.Rows.Add();
                    for (int column = 1; column <= colCount; column++)
                    {
                        dataTable.Rows[row - 1][column - 1] = row * column;
                    }
                }
                sheet.ImportDataTable(dataTable, 1, 1, true, true);
            }
            else
            {
                IMigrantRange migrantRange = sheet.MigrantRange;

                for (int column = 1; column <= colCount; column++)
                {
                    migrantRange.ResetRowColumn(1, column);
                    migrantRange.SetValue("Column: " + column.ToString());
                }

                //Writing Data using normal interface
                for (int row = 2; row <= rowCount; row++)
                {
                    //double columnSum = 0.0;
                    for (int column = 1; column <= colCount; column++)
                    {
                        //Writing number
                        migrantRange.ResetRowColumn(row, column);
                        migrantRange.SetValue(row * column);
                    }
                }
            }
            workbook.Version = ExcelVersion.Excel2013;

            MemoryStream stream = new MemoryStream();

            workbook.SaveAs(stream);
            workbook.Close();
            excelEngine.Dispose();


            if (stream != null)
            {
                SaveAndroid androidSave = new SaveAndroid();
                androidSave.Save("CreateSheet.xlsx", "application/msexcel", stream, m_context);
            }
        }
예제 #5
0
        public EtlProcessedFile LoadExcelFileMontosMinimos()
        {
            var dateIni    = DateTime.Now;
            var idLoadFile = dateIni.TimeOfDay.ToString().PadRight(20).Replace(".", "").Replace(":", "");

            EtlProcessedFile processedFile = new EtlProcessedFile {
                DateIni = dateIni, FileName = MessageCenter.URL_FILE_MM
            };

            try
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                List <FondosInversionMontosMinimos> fondos = new List <FondosInversionMontosMinimos>();
                using (ExcelEngine excelEngine = new ExcelEngine())
                {
                    FileStream    inputStream = new FileStream(processedFile.FileName, FileMode.Open);
                    IWorkbook     workbook    = excelEngine.Excel.Workbooks.Open(inputStream);
                    IWorksheet    sheet       = workbook.Worksheets["montos minimos"];
                    IMigrantRange mRange      = sheet.MigrantRange;
                    int           rowCount    = sheet.UsedRange.LastRow;
                    int           colCount    = sheet.UsedRange.LastColumn;

                    for (int r = 2; r <= rowCount; r++)
                    {
                        var fondoInversion = new FondosInversionMontosMinimos();
                        for (int c = 1; c <= colCount; c++)
                        {
                            mRange.ResetRowColumn(r, c);
                            var      value      = mRange.Value?.ToString().TrimEnd().TrimStart();
                            DateTime parsedDate = new DateTime();
                            switch (c)
                            {
                            case 1: fondoInversion.Fecha = DateTime.TryParse(value, out parsedDate) == true ? parsedDate : new DateTime(); break;

                            case 2: fondoInversion.Operadora = value; break;

                            case 3: fondoInversion.Fondo = value; break;

                            case 4: fondoInversion.Serie = value; break;

                            case 6: fondoInversion.MontoMinimo = String.IsNullOrEmpty(value) == true ? -1 : Convert.ToDecimal(value.Replace(",", "").Replace("'", "").Replace("´", ""), null); break;

                            case 7: fondoInversion.MontoMinimoTipo = value.ToUpper() == "SERIE A" ? (char)'S' : StringToChar(value.ToCharArray()); break;

                            case 8: fondoInversion.Divisa = value; break;

                            case 9: fondoInversion.Activo = StringToChar(value.ToUpper().ToCharArray()); break;

                            case 11: fondoInversion.PersonaFisica = TransformStringToBoolean(value.ToUpper()); break;

                            case 12: fondoInversion.PersonaMoral = TransformStringToBoolean(value.ToUpper()); break;

                            case 13: fondoInversion.PersonaMoralNoContribuyente = TransformStringToBoolean(value.ToUpper()); break;

                            case 14: fondoInversion.SociedadesDeInversion = TransformStringToBoolean(value.ToUpper()); break;
                            }//SWITCH
                        }

                        fondoInversion.FondoSerie = fondoInversion.Fondo + fondoInversion.Serie;
                        fondoInversion.FondoKey   = fondoInversion.Fecha.ToString("MMyy") + fondoInversion.FondoSerie;
                        fondoInversion.IdLoadFile = idLoadFile;
                        fondos.Add(fondoInversion);
                    }

                    workbook.Close();      //Close the instance of IWorkbook
                    excelEngine.Dispose(); //Dispose the instance of ExcelEngine
                }//USING

                _dataContext.BulkInsert(fondos);
                stopwatch.Stop();

                processedFile.DateEnd       = DateTime.Now;
                processedFile.ElapsedTime   = (stopwatch.ElapsedMilliseconds) / 1000;
                processedFile.LoadedRecords = fondos.Count;
                processedFile.TypeLoad      = "Fondos de Inversión MM";
                processedFile.IdLoadFile    = idLoadFile;

                _dataContext.EtlProcessedFiles.Add(processedFile);
                _dataContext.SaveChanges();
            } catch (Exception e)
            { Console.WriteLine($"Finish with errors {e.ToString()} "); }

            return(processedFile);
        }//Montominimo
예제 #6
0
        private async void btnGenerateExcel_Click(object sender, RoutedEventArgs e)
        {
            #region Workbook initialization
            int           rowCount = Convert.ToInt32(cbRows.Text);
            int           colCount = Convert.ToInt32(cbColumns.Text);
            MessageDialog dialog   = null;
            if (rdbExcel2003.IsChecked.Value && colCount > 256)
            {
                dialog = new MessageDialog("Maximum number of columns allowed for Excel 2003 format is 256. Please select Excel 2007 to 2013 format if you need more than 256 columns.");
                await dialog.ShowAsync();
            }
            else if (rdbExcel2003.IsChecked.Value && rowCount > 65536)
            {
                dialog = new MessageDialog("Maximum number of rows allowed for Excel 2003 format is 65,536. Please select Excel 2007 to 2013 format if you need more than 65,536 rows.");
                await dialog.ShowAsync();
            }
            else
            {
                System.Diagnostics.Stopwatch watcher = new System.Diagnostics.Stopwatch();
                watcher.Start();
                //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
                //The instantiation process consists of two steps.

                //Step 1 : Instantiate the spreadsheet creation engine.
                ExcelEngine excelEngine = new ExcelEngine();
                //Step 2 : Instantiate the excel application object.
                IApplication application = excelEngine.Excel;

                //Set the Default Version as Excel 97to2003
                if (this.rdbExcel2003.IsChecked == true)
                {
                    application.DefaultVersion = ExcelVersion.Excel97to2003;
                }
                ////Set the Default Version as Excel 2007
                //else if (this.rdbExcel2007.IsChecked == true)
                //{
                //    application.DefaultVersion = ExcelVersion.Excel2007;
                //}
                //else if (this.rdbExcel2010.IsChecked == true)
                //{
                //    application.DefaultVersion = ExcelVersion.Excel2010;
                //}
                else if (this.rdbExcel2013.IsChecked == true)
                {
                    application.DefaultVersion = ExcelVersion.Excel2013;
                }

                //A new workbook is created.[Equivalent to creating a new workbook in MS Excel]
                //The new workbook will have 3 worksheets
                IWorkbook workbook = application.Workbooks.Create(1);
                //The first worksheet object in the worksheets collection is accessed.
                IWorksheet worksheet = workbook.Worksheets[0];
                #endregion

                #region FillData

                IMigrantRange migrantRange = worksheet.MigrantRange;


                for (int column = 1; column <= colCount; column++)
                {
                    migrantRange.ResetRowColumn(1, column);
                    migrantRange.Text = "Column: " + column.ToString();
//#if WINDOWS_PHONE_APP
                    worksheet.SetColumnWidth(column, 9);
//#endif
                }

                //Writing Data using normal interface
                for (int row = 2; row <= rowCount; row++)
                {
                    //double columnSum = 0.0;
                    for (int column = 1; column <= colCount; column++)
                    {
                        //Writing number
                        migrantRange.ResetRowColumn(row, column);
                        migrantRange.Number = row * column;
                    }
                }
                watcher.Stop();
                LogDetails(watcher.Elapsed);
                #endregion

                #region Save the Workbook
                StorageFile storageFile;
                if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
                {
                    FileSavePicker savePicker = new FileSavePicker();
                    savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                    savePicker.SuggestedFileName      = "Performance";
                    if (workbook.Version == ExcelVersion.Excel97to2003)
                    {
                        savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                        {
                            ".xls"
                        });
                    }
                    else
                    {
                        savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                        {
                            ".xlsx",
                        });
                    }
                    storageFile = await savePicker.PickSaveFileAsync();
                }
                else
                {
                    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                    if (workbook.Version == ExcelVersion.Excel97to2003)
                    {
                        storageFile = await local.CreateFileAsync("Performance.xls", CreationCollisionOption.ReplaceExisting);
                    }
                    else
                    {
                        storageFile = await local.CreateFileAsync("Performance.xlsx", CreationCollisionOption.ReplaceExisting);
                    }
                }

                //Saving the workbook to disk.
                if (storageFile != null)
                {
                    //Saving the workbook
                    await workbook.SaveAsAsync(storageFile);

                    workbook.Close();
                    excelEngine.Dispose();

                    MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

                    UICommand yesCmd = new UICommand("Yes");
                    msgDialog.Commands.Add(yesCmd);
                    UICommand noCmd = new UICommand("No");
                    msgDialog.Commands.Add(noCmd);
                    IUICommand cmd = await msgDialog.ShowAsync();

                    if (cmd == yesCmd)
                    {
                        // Launch the saved file
                        bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
                    }
                }
                else
                {
                    workbook.Close();
                    excelEngine.Dispose();
                }
                #endregion
            }
        }
예제 #7
0
        public EtlProcessedFile LoadExcelFileVectorPrecio()
        {
            var dateIni    = DateTime.Now;
            var idLoadFile = dateIni.TimeOfDay.ToString().PadRight(20).Replace(".", "").Replace(":", "");

            //EtlProcessedFile processedFile = new EtlProcessedFile { DateIni = dateIni, FileName = MessageCenter.URL_FILE_VP };
            // "vectorPrecios_20200301Data.xlsx" vectorPrecios_20200324Data.xlsx vectorPrecios_20200327Data.xlsx vectorPrecios_20200331Data.xlsx
            EtlProcessedFile processedFile = new EtlProcessedFile {
                DateIni = dateIni, FileName = "vectorPrecios_20200331Data.xlsx"
            };

            try
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                List <VectorPrecio> vectores = new List <VectorPrecio>();
                using (ExcelEngine excelEngine = new ExcelEngine())
                {
                    FileStream    inputStream = new FileStream(processedFile.FileName, FileMode.Open);
                    IWorkbook     workbook    = excelEngine.Excel.Workbooks.Open(inputStream);
                    IWorksheet    sheet       = workbook.Worksheets[0];
                    IMigrantRange mRange      = sheet.MigrantRange;
                    int           rowCount    = sheet.UsedRange.LastRow;
                    int           colCount    = sheet.UsedRange.LastColumn;

                    for (int r = 2; r <= rowCount; r++)
                    {
                        var vectorPrecio = new VectorPrecio();
                        for (int c = 1; c <= colCount; c++)
                        {
                            mRange.ResetRowColumn(r, c);
                            var      value      = mRange.Value?.ToString().TrimEnd().TrimStart();
                            DateTime parsedDate = new DateTime();
                            switch (c)
                            {
                            case 1: vectorPrecio.Fecha = DateTime.TryParse(value, out parsedDate) == true ? parsedDate : new DateTime(); break;

                            case 2: vectorPrecio.Operadora = value; break;

                            case 3: vectorPrecio.Fondo = value; break;

                            case 4: vectorPrecio.Serie = value; break;

                            case 6: vectorPrecio.Precio = String.IsNullOrEmpty(value) == true ? -1 : Convert.ToDecimal(value.Replace(",", "").Replace("'", "").Replace("´", ""), null); break;
                            }//SWITCH
                        }
                        var fondoserie = vectorPrecio.Fondo + vectorPrecio.Serie;
                        var fondo      = vectorPrecio.Fondo;
                        var serie      = vectorPrecio.Serie;
                        var operadora  = vectorPrecio.Operadora;
                        var fondokey   = vectorPrecio.Fecha.ToString("MMyy") + fondoserie;
                        //var fondoInverison = _dataContext.FondosInversionMontosMinimos.FirstOrDefault(fi => fi.FondoKey == fondokey);

                        vectorPrecio.FondoSerie     = fondoserie;
                        vectorPrecio.FondoKey       = fondokey;
                        vectorPrecio.FondoInversion = new FondosInversionMontosMinimos {
                            FondoKey = fondokey, Fondo = fondo, Serie = serie, FondoSerie = fondoserie, Operadora = operadora
                        };
                        vectorPrecio.IdLoadFile = idLoadFile;

                        /*** CUATRO_DIAS ***/
                        var r4 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.CUATRO_DIAS);
                        vectorPrecio.RendiDirCuatroDias = r4.Directo;
                        vectorPrecio.RendiAnuCuatroDias = r4.Anualizado;

                        /*** SIETE_DIAS ***/
                        var r7 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.SIETE_DIAS);
                        vectorPrecio.RendiDirSieteDias = r7.Directo;
                        vectorPrecio.RendiAnuSieteDias = r7.Anualizado;

                        /*** UN_MES ***/
                        var r30 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.UN_MES);
                        vectorPrecio.RendiDirUnMes = r30.Directo;
                        vectorPrecio.RendiAnuUnMes = r30.Anualizado;

                        /*** TRES_MESES ***/
                        var r90 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.TRES_MESES);
                        vectorPrecio.RendiDirTresMeses = r90.Directo;
                        vectorPrecio.RendiAnuTresMeses = r90.Anualizado;

                        /*** SEIS_MESES ***/
                        var r180 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.SEIS_MESES);
                        vectorPrecio.RendiDirSeisMeses = r180.Directo;
                        vectorPrecio.RendiAnuSeisMeses = r180.Anualizado;

                        /*** NUEVE_MESES ***/
                        var r270 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.NUEVE_MESES);
                        vectorPrecio.RendiDirNueveMeses = r270.Directo;
                        vectorPrecio.RendiAnuNueveMeses = r270.Anualizado;

                        /*** DOCE_MESES ***/
                        var r360 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.DOCE_MESES);
                        vectorPrecio.RendiDirDoceMeses = r360.Directo;
                        vectorPrecio.RendiAnuDoceMeses = r360.Anualizado;

                        /*** DIECIOCHO_MESES ***/
                        var r540 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.DIECIOCHO_MESES);
                        vectorPrecio.RendiDirDiesiOchoMeses = r540.Directo;
                        vectorPrecio.RendiAnuDiesiOchoMeses = r540.Anualizado;

                        /*** VEINTICUATRO_MESES ***/
                        var r720 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.VEINTICUATRO_MESES);
                        vectorPrecio.RendiDirVeintiCuatroMeses = r720.Directo;
                        vectorPrecio.RendiAnuVeintiCuatroMeses = r720.Anualizado;

                        /*** TREINTAYSEIS_MESES ***/
                        var r1080 = CalculateRendimiento(vectorPrecio.Fecha, vectorPrecio.Precio, fondoserie, MessageCenter.TREINTAYSEIS_MESES);
                        vectorPrecio.RendiDirTreintaySeisMeses = r1080.Directo;
                        vectorPrecio.RendiAnuTreintaySeisMeses = r1080.Anualizado;

                        vectores.Add(vectorPrecio);
                    }

                    workbook.Close();      //Close the instance of IWorkbook
                    excelEngine.Dispose(); //Dispose the instance of ExcelEngine
                }//USING

                _dataContext.BulkInsert(vectores);
                stopwatch.Stop();
                processedFile.DateEnd       = DateTime.Now;
                processedFile.ElapsedTime   = (stopwatch.ElapsedMilliseconds) / 1000;
                processedFile.LoadedRecords = vectores.Count;
                processedFile.TypeLoad      = "Vector de Precios";
                processedFile.IdLoadFile    = idLoadFile;

                _dataContext.EtlProcessedFiles.Add(processedFile);
                _dataContext.SaveChanges();
            } catch (Exception e)
            { Console.WriteLine($"Errors LoadExcelFileVectorPrecio: {e.ToString()} "); }

            return(processedFile);
        }//Vectorprecio
예제 #8
0
        private async void Excel()
        {
            var balanceView = BalanceView.GetInstance();

            var confirmacion = await dialogService.ShowMessageConfirmacion("Mensaje", "¿Desea exportar el balance a una planilla de cálculo?");

            if (confirmacion)
            {
                try {
                    Cargas();
                    if (ListaBalance.Count == 0)
                    {
                        await dialogService.ShowMessage("Error", "Se deben agregar elementos al balance");

                        balanceView.excelUnTapped();
                        return;
                    }
                    using (ExcelEngine excelEngine = new ExcelEngine())
                    {
                        cont = 0;
                        //Seleccionar versión de Excel 2013
                        excelEngine.Excel.DefaultVersion = ExcelVersion.Excel2013;

                        //Crear workbook con una hoja de trabajo
                        IWorkbook workbook = excelEngine.Excel.Workbooks.Create(1);

                        //Acceder a la primera hoja de trabajo desde la instancia de workbook
                        IWorksheet worksheet = workbook.Worksheets[0];

                        IMigrantRange migrantRange = worksheet.MigrantRange;

                        foreach (var elemento in ListaBalance)
                        {
                            // Writing Data.
                            //cont aumenta en 7 la posición de las filas en cada producto, las columnas dependen de los días elegidos

                            migrantRange["A1"].Text = "Fecha";
                            migrantRange["A1"].CellStyle.Font.Bold = true;

                            migrantRange["B1"].Text = "Origen";
                            migrantRange["B1"].CellStyle.Font.Bold = true;

                            migrantRange["C1"].Text = "Categoría";
                            migrantRange["C1"].CellStyle.Font.Bold = true;

                            migrantRange["D1"].Text = "Monto";
                            migrantRange["D1"].CellStyle.Font.Bold = true;

                            //Nueva celda
                            migrantRange.ResetRowColumn(cont + 2, 1);
                            migrantRange.Text = string.Format("{0}/{1}/{2}", elemento.Dia, elemento.Mes, elemento.Anio);


                            //migrantRange.CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;

                            //Nueva celda
                            migrantRange.ResetRowColumn(cont + 2, 2);
                            migrantRange.Text = elemento.Origen;
                            //Nueva celda
                            migrantRange.ResetRowColumn(cont + 2, 3);
                            migrantRange.Text = elemento.GastoIngreso;
                            //Nueva celda
                            migrantRange.ResetRowColumn(cont + 2, 4);

                            migrantRange.Number = double.Parse(elemento.Cantidad);
                            if (double.Parse(elemento.Cantidad) > 0)
                            {
                                worksheet[string.Format("D{0}", cont + 2)].CellStyle.Font.Color = ExcelKnownColors.Green;
                            }
                            else if (double.Parse(elemento.Cantidad) < 0)
                            {
                                worksheet[string.Format("D{0}", cont + 2)].CellStyle.Font.Color = ExcelKnownColors.Red;
                            }


                            cont = cont + 1;
                        }
                        ;

                        IRange range = worksheet.Range[string.Format("A{0}:C{0}", cont + 2)];
                        range.Merge();
                        range.Text = string.Format("Balance: ");
                        range.CellStyle.HorizontalAlignment = ExcelHAlign.HAlignCenter;
                        range.CellStyle.Font.Bold           = true;
                        worksheet[string.Format("D{0}", cont + 2)].Number = double.Parse(BalanceTotal);
                        worksheet[string.Format("D{0}", cont + 2)].CellStyle.Font.Bold = true;
                        if (double.Parse(BalanceTotal) > 0)
                        {
                            worksheet[string.Format("D{0}", cont + 2)].CellStyle.ColorIndex = ExcelKnownColors.Green;
                        }
                        else if (double.Parse(BalanceTotal) < 0)
                        {
                            worksheet[string.Format("D{0}", cont + 2)].CellStyle.ColorIndex = ExcelKnownColors.Red;
                        }
                        worksheet.Range[string.Format("A1:D{0}", cont + 2)].BorderInside();
                        worksheet.Range[string.Format("A1:D{0}", cont + 2)].BorderAround();
                        worksheet.UsedRange.AutofitColumns();

                        //Save the workbook to stream in xlsx format.
                        MemoryStream stream = new MemoryStream();
                        workbook.SaveAs(stream);

                        workbook.Close();

                        //Save the stream as a file in the device and invoke it for viewing
                        DependencyService.Get <ISave>().SaveAndView(string.Format("Balance Mensual de {0}-{1}", SelectedItemMes, SelectedItemAño) + ".xlsx", "application/msexcel", stream);

                        await dialogService.ShowMessage("Mensaje", string.Format("El balance se guardó como archivo de nombre '{0}' en la carpeta Balances", string.Format("Balance Mensual de {0}-{1}", SelectedItemMes, SelectedItemAño) + ".xlsx"));
                    }
                }
                catch
                {
                    await dialogService.ShowMessage("Error", "No se pudo exportar a hoja de cálculo. Intenta habilitando los permisos en ajustes.");
                }
            }
            balanceView.excelUnTapped();
        }
예제 #9
0
        public ActionResult Performance(string SaveOption, string Import, string rowCount, string colCount)
        {
            if (SaveOption == null)
            {
                return(View());
            }

            int rows    = Convert.ToInt32(rowCount);
            int columns = Convert.ToInt32(colCount);
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            // Creating new workbook
            IWorkbook  workbook = application.Workbooks.Create(1);
            IWorksheet sheet    = workbook.Worksheets[0];


            #region Generate Excel
            if (Import == "importonsave")
            {
                DataTable dataTable = new DataTable();
                for (int column = 1; column <= columns; column++)
                {
                    dataTable.Columns.Add("Column: " + column.ToString(), typeof(int));
                }
                //Adding data into data table
                for (int row = 1; row < rows; row++)
                {
                    dataTable.Rows.Add();
                    for (int column = 1; column <= columns; column++)
                    {
                        dataTable.Rows[row - 1][column - 1] = row * column;
                    }
                }
                sheet.ImportDataTable(dataTable, 1, 1, true, true);
            }
            else
            {
                IMigrantRange migrantRange = workbook.Worksheets[0].MigrantRange;
                for (int column = 1; column <= columns; column++)
                {
                    migrantRange.ResetRowColumn(1, column);
                    migrantRange.Text = "Column: " + column.ToString();
                }

                //Writing Data using normal interface
                for (int row = 2; row <= rows; row++)
                {
                    //double columnSum = 0.0;
                    for (int column = 1; column <= columns; column++)
                    {
                        //Writing number
                        migrantRange.ResetRowColumn(row, column);
                        migrantRange.Number = row * column;
                    }
                }
            }
            #endregion

            string ContentType = null;
            string fileName    = null;
            if (SaveOption == "ExcelXls")
            {
                ContentType = "Application/vnd.ms-excel";
                fileName    = "Sample.xls";
            }
            else
            {
                workbook.Version = ExcelVersion.Excel2013;
                ContentType      = "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                fileName         = "Sample.xlsx";
            }

            MemoryStream ms = new MemoryStream();
            workbook.SaveAs(ms);
            ms.Position = 0;

            return(File(ms, ContentType, fileName));
        }
예제 #10
0
        private async void Xls()
        {
            if (ProductoPrincipal.Calculo == false)
            {
                await dialogService.ShowMessage("Error", "Se debe realizar, en primera medida, el cálculo");

                return;
            }
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                cont = 0;
                //Seleccionar versión de Excel 2013
                excelEngine.Excel.DefaultVersion = ExcelVersion.Excel2013;

                //Crear workbook con una hoja de trabajo
                IWorkbook workbook = excelEngine.Excel.Workbooks.Create(1);


                foreach (var productoA in ProductoPrincipal.Productos)
                {
                    CantSemanas = productoA.Semanas.Count.ToString();


                    //Acceder a la primera hoja de trabajo desde la instancia de workbook
                    IWorksheet worksheet = workbook.Worksheets[0];

                    IMigrantRange migrantRange = worksheet.MigrantRange;
                    // Writing Data.
                    //cont aumenta en 7 la posición de las filas en cada producto, las columnas dependen de los días elegidos


                    migrantRange["A" + (cont + 1).ToString()].Text = productoA.Nombres;

                    migrantRange["A" + (2 + cont).ToString()].Text = "Requerimiento Bruto";

                    migrantRange["A" + (3 + cont).ToString()].Text = "Inventario Inicial";

                    migrantRange["A" + (4 + cont).ToString()].Text = "Requerimiento Neto";

                    migrantRange["A" + (5 + cont).ToString()].Text = "Liberación Orden";

                    migrantRange["A" + (6 + cont).ToString()].Text = "Inventario Final";

                    //Estilos de las celdas
                    migrantRange["A" + (cont + 1).ToString()].CellStyle.Font.Bold         = true;
                    migrantRange["A" + (cont + 1).ToString()].CellStyle.ColorIndex        = ExcelKnownColors.Sea_green;
                    migrantRange["A" + (cont + 1).ToString()].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                    migrantRange["A" + (2 + cont).ToString()].CellStyle.ColorIndex        = ExcelKnownColors.Aqua;
                    migrantRange["A" + (2 + cont).ToString()].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                    migrantRange["A" + (3 + cont).ToString()].CellStyle.ColorIndex        = ExcelKnownColors.Aqua;
                    migrantRange["A" + (3 + cont).ToString()].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                    migrantRange["A" + (4 + cont).ToString()].CellStyle.ColorIndex        = ExcelKnownColors.Aqua;
                    migrantRange["A" + (4 + cont).ToString()].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                    migrantRange["A" + (5 + cont).ToString()].CellStyle.ColorIndex        = ExcelKnownColors.Aqua;
                    migrantRange["A" + (5 + cont).ToString()].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                    migrantRange["A" + (6 + cont).ToString()].CellStyle.ColorIndex        = ExcelKnownColors.Aqua;
                    migrantRange["A" + (6 + cont).ToString()].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                    //Recorrido de columnas desde la columna 2 en adelante
                    for (int column = 2; column < int.Parse(CantSemanas) + 2; column++)
                    {
                        //Nueva celda
                        migrantRange.ResetRowColumn(cont + 1, column);
                        migrantRange.Text = "Día" + (column - 1).ToString() + "  " + DateSelected.Date.AddDays(column - 2).ToString().Remove(10);
                        //Estilo de la celda  migrantRange.ResetRowColumn(cont+1, column)
                        migrantRange.CellStyle.ColorIndex        = ExcelKnownColors.Pale_blue;
                        migrantRange.CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                        if (!string.IsNullOrEmpty(productoA.Semanas[column - 2].LibOrden))
                        {
                            migrantRange.CellStyle.ColorIndex = ExcelKnownColors.Bright_green;
                        }
                        //Nueva celda
                        migrantRange.ResetRowColumn(cont + 2, column);
                        migrantRange.Text = productoA.Semanas[column - 2].ReqBruto;
                        //Nueva celda
                        migrantRange.ResetRowColumn(cont + 3, column);
                        migrantRange.Text = productoA.Semanas[column - 2].InventarioInicial;
                        //Nueva celda
                        migrantRange.ResetRowColumn(cont + 4, column);
                        migrantRange.Text = productoA.Semanas[column - 2].ReqNeto;
                        //Nueva celda
                        migrantRange.ResetRowColumn(cont + 5, column);
                        migrantRange.Text = productoA.Semanas[column - 2].LibOrden;
                        //Estilo de la celda   migrantRange.ResetRowColumn(cont+5, column)
                        if (!string.IsNullOrEmpty(productoA.Semanas[column - 2].LibOrden))
                        {
                            migrantRange.CellStyle.ColorIndex = ExcelKnownColors.Bright_green;
                            migrantRange.CellStyle.Font.Bold  = true;
                        }
                        //Nueva celda
                        migrantRange.ResetRowColumn(cont + 6, column);
                        migrantRange.Text = productoA.Semanas[column - 2].InvFinal;
                    }
                    cont = cont + 7;
                    worksheet.UsedRange.AutofitColumns();
                }
                //Save the workbook to stream in xlsx format.
                MemoryStream stream = new MemoryStream();
                workbook.SaveAs(stream);

                workbook.Close();

                //Save the stream as a file in the device and invoke it for viewing
                await DependencyService.Get <ISave>().SaveAndView(ProductoPrincipal.Nombre + ".xlsx", "application/msexcel", stream);

                await dialogService.ShowMessage("Mensaje", "El Producto se guardó como hoja de Excel en la carpeta MRP");
            }
        }
예제 #11
0
        private void BtnGenerate_Clicked(object sender, EventArgs e)
        {
            int rows    = Convert.ToInt32(this.rowCount.Text);
            int columns = Convert.ToInt32(this.colCount.Text);
            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();

            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;
            IWorkbook    workbook;

            workbook         = application.Workbooks.Create(1);
            workbook.Version = ExcelVersion.Excel2013;
            IWorksheet sheet = workbook.Worksheets[0];

            if (this.Import.IsChecked.Value)
            {
                DataTable dataTable = new DataTable();
                for (int column = 1; column <= columns; column++)
                {
                    dataTable.Columns.Add("Column: " + column.ToString(), typeof(int));
                }
                //Adding data into data table
                for (int row = 1; row < rows; row++)
                {
                    dataTable.Rows.Add();
                    for (int column = 1; column <= columns; column++)
                    {
                        dataTable.Rows[row - 1][column - 1] = row * column;
                    }
                }
                sheet.ImportDataTable(dataTable, 1, 1, true, true);
            }
            else
            {
                IMigrantRange migrantRange = sheet.MigrantRange;

                for (int column = 1; column <= Convert.ToInt32(this.colCount.Text); column++)
                {
                    migrantRange.ResetRowColumn(1, column);
                    migrantRange.SetValue("Column: " + column.ToString());
                }

                //Writing Data using normal interface
                for (int row = 2; row <= rows; row++)
                {
                    //double columnSum = 0.0;
                    for (int column = 1; column <= columns; column++)
                    {
                        //Writing number
                        migrantRange.ResetRowColumn(row, column);
                        migrantRange.SetValue(row * column);
                    }
                }
            }

            MemoryStream stream = new MemoryStream();

            workbook.SaveAs(stream);
            workbook.Close();
            excelEngine.Dispose();

            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("Sample.xlsx", "application/msexcel", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("Sample.xlsx", "application/msexcel", stream);
            }
        }