Пример #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile("appsetting.json", true, true)
                                    .Build();

            string str = config["File"];

            Console.WriteLine(str);
            Console.ReadKey();

            try
            {
                Application ObjExcel = new Application();
                Workbook    wb       = ObjExcel.Workbooks.Open("C:\\Andrii\\lists.xlsx",
                                                               0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
                Worksheet ws = (Worksheet)wb.Sheets[1];
                Microsoft.Office.Interop.Excel.Range usedColumn =
                    (Microsoft.Office.Interop.Excel.Range)ws.UsedRange.Columns[1];

                System.Array myvalues = (System.Array)usedColumn.Cells.Value2;
                string[]     strArray = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();
                foreach (var r in strArray)
                {
                    Console.WriteLine(r);
                }
                ObjExcel.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Пример #2
0
 protected internal StackItem Convert(object value)
 {
     return(value switch
     {
         null => StackItem.Null,
         bool b => b,
         sbyte i => i,
         byte i => (BigInteger)i,
         short i => i,
         ushort i => (BigInteger)i,
         int i => i,
         uint i => i,
         long i => i,
         ulong i => i,
         Enum e => Convert(System.Convert.ChangeType(e, e.GetTypeCode())),
         byte[] data => data,
         string s => s,
         BigInteger i => i,
         IInteroperable interoperable => interoperable.ToStackItem(ReferenceCounter),
         ISerializable i => i.ToArray(),
         StackItem item => item,
         (object a, object b) => new Struct(ReferenceCounter)
         {
             Convert(a), Convert(b)
         },
         Array array => new VMArray(ReferenceCounter, array.OfType <object>().Select(p => Convert(p))),
         _ => StackItem.FromInterface(value)
     });
Пример #3
0
        public void Load_XLS(string p)
        {
            Microsoft.Office.Interop.Excel.Application xlsApp = null;
            try
            {
                xlsApp = new Microsoft.Office.Interop.Excel.Application();
            }
            catch
            {
                MessageBox.Show("Excel не может быть запущен. Возможно Excel не установлен на данном компьютере.");
                return;
            }

            //Displays Excel so you can see what is happening
            //xlsApp.Visible = true;
            try
            {
                Workbook wb = xlsApp.Workbooks.Open(p,
                                                    0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
                Sheets    sheets = wb.Worksheets;
                Worksheet ws     = (Worksheet)sheets.get_Item(1);

                Range        firstColumn = ws.UsedRange.Columns[1];
                System.Array myvalues    = (System.Array)firstColumn.Cells.Value;
                double[]     data        = myvalues.OfType <object>().Select(o => Convert.ToDouble(o.ToString().Replace(".", ","))).ToArray();
                SetData(data);
            }
            catch
            {
                MessageBox.Show("Не получилось собрать данные. Проверьте правильность составления документа! см. Руководство");
                return;
            }
        }
    static object GetNewScriptElement()
    {
        var window = GetAddComponentWindow();

        if (window == null)
        {
            m_CurrentWindow  = null;
            m_CurrentElement = null;
            return(null);
        }
        if (window == m_CurrentWindow)
        {
            return(m_CurrentElement);
        }
        m_CurrentWindow = window;
        System.Array a    = (System.Array)m_Tree.GetValue(window);
        var          list = a.OfType <object>().ToArray();

        for (int i = 0; i < list.Length; i++)
        {
            if (list[i].GetType() == NewScriptElement)
            {
                m_CurrentElement = list[i];
                return(m_CurrentElement);
            }
        }
        return(null);
    }
    //private static Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    public static void Parse(String filename)
    {
        var _app       = new Excel.Application();
        var _workbooks = _app.Workbooks;

        _workbooks.OpenText(filename,
                            DataType: Excel.XlTextParsingType.xlDelimited,
                            TextQualifier: Excel.XlTextQualifier.xlTextQualifierNone,
                            ConsecutiveDelimiter: true,
                            Semicolon: true);
        Excel.Sheets    sheets    = _workbooks[1].Worksheets;
        Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
        List <String[]> excelData = new List <string[]>();

        for (int i = 1; i <= 6; i++)
        {
            Excel.Range  range    = worksheet.get_Range("A" + i.ToString(), "Z" + i.ToString());
            System.Array myvalues = (System.Array)range.Cells.Value;
            string[]     strArray = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();
            excelData.Add(strArray);
        }
        foreach (var item in excelData)
        {
            Console.WriteLine(String.Join("|", item));
        }
    }
Пример #6
0
        public string[] Contacts()
        {
            Excel.Application xlapp;
            Excel.Workbook    xlWorkbook;
            Excel.Worksheet   xlWorksheet;
            string            startupPath = Environment.CurrentDirectory;

            startupPath = startupPath.Replace("ZadaniePraktyczne\\ZadaniePraktyczne\\bin\\Debug", "");
            string contactsPath = startupPath + "Kontakty.xlsx";

            xlapp       = new Excel.Application();
            xlWorkbook  = xlapp.Workbooks.Open(contactsPath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);

            Range Column = xlWorksheet.UsedRange.Columns[3];

            System.Array mails      = (System.Array)Column.Cells.Value;
            string[]     mailsArray = mails.OfType <object>().Select(o => o.ToString()).ToArray();

            foreach (var email in mailsArray)
            {
                if (ISValidEmail(email) == false)
                {
                    mailsArray = mailsArray.Where(w => w != email).ToArray();
                }
            }

            return(mailsArray);
        }
Пример #7
0
		public ArrayExtension (Array elements)
		{
			if (elements == null)
				throw new ArgumentNullException ("elements");
			Type = elements.GetType ().GetElementType ();
			items = new List<object> (elements.OfType<object>());
		}
Пример #8
0
        public void Transfer(int cn)
        {
            Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
            //Открываем книгу.
            string pathToFile = @"C:\Users\1225908\Desktop\SK_Moschnost.xlsx";

            Microsoft.Office.Interop.Excel.Workbook ObjWorkBook = ObjExcel.Workbooks.Open(pathToFile, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Выбираем таблицу(лист).
            Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
            ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1];

            // Указываем номер столбца (таблицы Excel) из которого будут считываться данные.
            int numCol = cn;

            Microsoft.Office.Interop.Excel.Range usedColumn = ObjWorkSheet.UsedRange.Columns[numCol];
            System.Array myvalues = (System.Array)usedColumn.Cells.Value2;
            string[]     strArray = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();

            // Выходим из программы Excel.
            ObjExcel.Quit();
            for (int i = 1; i < strArray.Length; i++)
            {
                data[cn - 1].Add(Convert.ToDouble(strArray[i]));
            }
            Console.WriteLine("Well");
        }
Пример #9
0
        private Dictionary <int, string> Read_file(string filename)
        {
            Dictionary <int, string> result = new Dictionary <int, string>();

            //Создаём приложение.
            Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
            //Открываем книгу.
            Microsoft.Office.Interop.Excel.Workbook ObjWorkBook = ObjExcel.Workbooks.Open(openFileDialog1.FileName, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Выбираем таблицу(лист).
            Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
            ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1];
            Range firstColumn = ObjWorkSheet.UsedRange.Columns[1];

            System.Array myvalues1    = (System.Array)firstColumn.Cells.Value;
            Range        secondColumn = ObjWorkSheet.UsedRange.Columns[2];

            System.Array myvalues2 = (System.Array)secondColumn.Cells.Value;
            string[]     IDarray   = myvalues1.OfType <object>().Select(o => o.ToString()).ToArray();
            string[]     Namearray = myvalues2.OfType <object>().Select(o => o.ToString()).ToArray();
            // Переводим два массива в словарь - убрав первую строчку с названиями столбцов
            for (int i = 1; i < IDarray.Count(); i++)
            {
                result.Add(Convert.ToInt32(IDarray[i]), Namearray[i]);
            }
            ObjWorkBook.Close();
            return(result);
        }
Пример #10
0
        public float [] FirstColumnLa(string filename, int colNo)
        {
            Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlsApp == null)
            {
                Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
                // return 0;
            }

            //Displays Excel so you can see what is happening
            //xlsApp.Visible = true;

            Workbook wb = xlsApp.Workbooks.Open(filename,
                                                0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
            Sheets    sheets = wb.Worksheets;
            Worksheet ws     = (Worksheet)sheets.get_Item(1);

            Range firstColumn = ws.UsedRange.Columns[colNo];

            System.Array myvalues = (System.Array)firstColumn.Cells.Value;

            string[] strArray = myvalues.OfType <double>().Select(o => o.ToString()).ToArray();
            float [] outArray = Array.ConvertAll <string, float>(strArray, Convert.ToSingle);


            return(outArray);
        }
        /// <summary>
        /// Returns list of WebApplicationUrls
        /// </summary>
        /// <param name="range">Used range of component input file sheet</param>
        /// <param name="summaryViewColumnText"></param>
        /// <returns></returns>
        public static List <string> GetWebApplicationUrls(Excel.Range range, string summaryViewColumnText)
        {
            List <string> lstWebApplicationUrls = null;

            try
            {
                if (range.Rows.Count > 1)
                {
                    for (int i = 1; i <= range.Columns.Count; i++)
                    {
                        try
                        {
                            string str = (string)(range.Cells[1, i] as Excel.Range).Value2;
                            //Find for WebApplicationUrl column name
                            if (str.Equals(summaryViewColumnText))
                            {
                                Excel.Range ctRange2 = range.Columns[i];
                                //Get all WebApplicationUrl values into array
                                System.Array ctWebAppValue = (System.Array)ctRange2.Cells.Value;
                                //Convert array into List<string>
                                lstWebApplicationUrls = ctWebAppValue.OfType <object>().Select(o => o.ToString()).ToList();
                                //Remove header name 'WebApplicationUrl'
                                lstWebApplicationUrls.Remove(lstWebApplicationUrls.First());
                                List <string> lstNewWebAppUrls = new List <string>();
                                //Trim '/' character when WebApplication ends with '/'
                                lstNewWebAppUrls = lstWebApplicationUrls.Select(item => item.EndsWith("/") ? item.TrimEnd('/') : item).ToList();

                                return(lstNewWebAppUrls);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogErrorMessage(string.Format("[GeneratePivotReports][ComponentsSummaryView][GetWebApplicationUrls][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString()), true);
                            ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                                        "[GeneratePivotReports]: GetWebApplicationUrls", ex.GetType().ToString(), Constants.NotApplicable);
                        }
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorMessage(string.Format("[GeneratePivotReports][ComponentsSummaryView][GetWebApplicationUrls][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString()), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "[GeneratePivotReports]: GetWebApplicationUrls", ex.GetType().ToString(), Constants.NotApplicable);
            }
            finally
            {
                range = null;
            }
            return(lstWebApplicationUrls);
        }
Пример #12
0
    public static string[] GetRange(string range, Excel.Worksheet excelWorksheet)
    {
        Microsoft.Office.Interop.Excel.Range workingRangeCells =
            excelWorksheet.get_Range(range, Type.Missing);
        //workingRangeCells.Select();

        System.Array array  = (System.Array)workingRangeCells.Cells.Value2;
        string[]     arrayS = array.OfType <System.Array>().Select(o => o.ToString()).ToArray();

        return(arrayS);
    }
Пример #13
0
        //private bool _canExecute;
        public void MyAction()
        {
            try
            {
                Microsoft.Office.Interop.Excel.Application xlApp;
                Microsoft.Office.Interop.Excel.Workbook    xlWorkbook;
                Microsoft.Office.Interop.Excel.Worksheet   xlWorksheet;
                object misValue = System.Reflection.Missing.Value;


                xlApp       = new Microsoft.Office.Interop.Excel.Application();
                xlWorkbook  = xlApp.Workbooks.Open(FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);

                //int startColumn = Header.Cells.Column;
                //int startRow = header.Cells.Row + 1;
                int col = ExcelColumnNameToNumber(Column);
                Microsoft.Office.Interop.Excel.Range startCell = xlWorksheet.Cells[StartRow, col];
                //int endColumn = startColumn + 1;
                //int endRow = 65536;
                Microsoft.Office.Interop.Excel.Range endCell = xlWorksheet.Cells[EndRow, col];
                Microsoft.Office.Interop.Excel.Range myRange = xlWorksheet.Range[startCell, endCell];
                System.Array myvalues = (System.Array)myRange.Cells.Value;
                string[]     strArray = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();

                int           numARow = Convert.ToInt32(NumARow);
                StringBuilder sb      = new StringBuilder();

                List <string> tempLst = new List <string>();
                for (int i = 0; i < strArray.Count(); i++)
                {
                    tempLst.Add(strArray[i]);
                    if (i == strArray.Count() - 1)
                    {
                        sb.AppendLine(string.Join(",", tempLst.Select(word => string.Format("'{0}'", word))));
                        tempLst = new List <string>();
                    }
                    else if (i != 0 && (i + 1) % numARow == 0)
                    {
                        sb.AppendLine(string.Join(",", tempLst.Select(word => string.Format("'{0}'", word))) + ",");
                        tempLst = new List <string>();
                    }
                }
                if (tempLst.Count > 0)
                {
                    sb.AppendLine(string.Join(",", tempLst.Select(word => string.Format("'{0}'", word))));
                }
                Result = sb.ToString();
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #14
0
        private List <Dictionary <int, int> > Read_file_time(string filename)
        {
            List <Dictionary <int, int> > result = new List <Dictionary <int, int> >();

            //Создаём приложение.
            Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
            //Открываем книгу.
            Microsoft.Office.Interop.Excel.Workbook ObjWorkBook = ObjExcel.Workbooks.Open(openFileDialog1.FileName, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Выбираем таблицу(лист).
            Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
            ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1];
            Range firstColumn = ObjWorkSheet.UsedRange.Columns[1];

            System.Array myvalues1    = (System.Array)firstColumn.Cells.Value;
            Range        secondColumn = ObjWorkSheet.UsedRange.Columns[2];

            System.Array myvalues2   = (System.Array)secondColumn.Cells.Value;
            Range        thirdColumn = ObjWorkSheet.UsedRange.Columns[3];

            System.Array myvalues3 = (System.Array)thirdColumn.Cells.Value;
            string[]     IDarray   = myvalues1.OfType <object>().Select(o => o.ToString()).ToArray();
            string[]     Namearray = myvalues2.OfType <object>().Select(o => o.ToString()).ToArray();
            string[]     Timearray = myvalues3.OfType <object>().Select(o => o.ToString()).ToArray();
            //MessageBox.Show(IDarray.Count().ToString()+IDarray);
            // Переводим два массива в словарь - убрав первую строчку с названиями столбцов
            string tmp = IDarray[1];

            for (int i = 1; i < IDarray.Count(); i++)

            {
                Dictionary <int, int> tmplist = new Dictionary <int, int>();
                while (tmp == IDarray[i])
                {
                    tmplist.Add(Convert.ToInt32(Namearray[i]), Convert.ToInt32(Timearray[i]));
                    i++;
                    if (i == IDarray.Count())
                    {
                        break;
                    }
                }
                result.Add(tmplist);
                if (i == IDarray.Count())
                {
                    break;
                }
                tmp = IDarray[i];
                i--;
            }
            ObjWorkBook.Close();
            return(result);
        }
        public void assignMainParameters()
        {
            Range usedColumnX = ObjWorkSheet.UsedRange.Columns[numColX];

            System.Array myvaluesX = (System.Array)usedColumnX.Cells.Value2;
            string[]     strArrayX = myvaluesX.OfType <object>().Select(o => o.ToString()).ToArray();

            Range usedColumnZ = ObjWorkSheet.UsedRange.Columns[numColZ];

            System.Array myvaluesZ = (System.Array)usedColumnZ.Cells.Value2;
            string[]     strArrayY = myvaluesZ.OfType <object>().Select(o => o.ToString()).ToArray();

            Range usedColumnY = ObjWorkSheet.UsedRange.Columns[numColY];

            System.Array myvaluesY = (System.Array)usedColumnY.Cells.Value2;
            string[]     strArrayZ = myvaluesY.OfType <object>().Select(o => o.ToString()).ToArray();

            Range usedColumnF = ObjWorkSheet.UsedRange.Columns[numColF];

            System.Array myvaluesF = (System.Array)usedColumnF.Cells.Value2;
            string[]     strArrayF = myvaluesF.OfType <object>().Select(o => o.ToString()).ToArray();

            int countXvalues = 0;

            foreach (var item in strArrayX)
            {
                countXvalues++;
            }

            int numStart = 7;

            transDataX = new double[countXvalues - 8 + 1];

            transDataY = new double[countXvalues - 8 + 1];

            transDataZ = new double[countXvalues - 8 + 1];

            int j = 0;

            for (int i = numStart; i < countXvalues; i++)
            {
                transDataX[j] = Convert.ToDouble(strArrayX[i]);
                transDataY[j] = Convert.ToDouble(strArrayY[i]);
                transDataZ[j] = Convert.ToDouble(strArrayZ[i]);
                dataFDim.Add(Convert.ToDouble(strArrayF[i]));
                //Console.WriteLine($"{transDataX[j]}  {transDataY[j]}  {transDataZ[j]}");
                j++;
            }
        }
Пример #16
0
        public List <string> ReadExcelFile(string filePath)
        {
            Microsoft.Office.Interop.Excel.Application ObjExcel    = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook    ObjWorkBook = ObjExcel.Workbooks.Open(filePath, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Worksheet   ObjWorkSheet;
            ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1];
            int numCol     = 1;
            var usedColumn = ObjWorkSheet.UsedRange.Columns[numCol];

            System.Array  myvalues = (System.Array)usedColumn.Cells.Value2;
            List <string> list     = myvalues.OfType <object>().Select(o => o.ToString()).ToList();

            ObjExcel.Quit();
            return(list);
        }
Пример #17
0
        private static string[] ColumnFromExcel(string filename, int columnId)
        {
            Application xlsApp = new Application();

            Workbook wb = xlsApp.Workbooks.Open(filename,
                                                0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
            Sheets    sheets = wb.Worksheets;
            Worksheet ws     = (Worksheet)sheets.get_Item(1);

            Range wantedColumn = ws.UsedRange.Columns[columnId];

            System.Array myvalues = (System.Array)wantedColumn.Cells.Value;
            string[]     strArray = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();
            return(strArray);
        }
Пример #18
0
        static void Main(string[] args)
        {
            Client client = new Client("fcd04c9b", "0bfa15d2ec326dc77265fdf6f2461ff2");

            //String text = "for architecture is not mere building, but beautiful building. It began when for the first time a man or a woman thought of a dwelling in terms of appearance as well as of use. Probably this effort to give beauty or sublimity to a structure was directed first to graves rather than to homes; while the commemorative pillar developed into statuary, the tomb grew into a temple";

            //var hashtags = client.Hashtags(text: text);
            //Console.WriteLine(string.Join(", ", hashtags.HashtagsMember));
            //Console.ReadLine();
            Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlsApp == null)
            {
                Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
                return;
            }

            //Displays Excel so you can see what is happening
            //xlsApp.Visible = true;
            Workbook wb = xlsApp.Workbooks.Open("C:\\Users\\mobin\\Csharp\\aylien_textapi_csharp-master\\ConsoleApplication\\bin\\Debug\\Citations_History_OurOrientalHeritage.xlsx",
                                                ReadOnly: false);

            xlsApp.AlertBeforeOverwriting = false;
            try
            {
                Sheets    sheets = wb.Worksheets;
                Worksheet ws     = (Worksheet)sheets.get_Item(1);

                Range        firstColumn = (Range)ws.UsedRange.Columns[1];
                System.Array myvalues    = (System.Array)firstColumn.Cells.Value;
                string[]     strArray    = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();
                for (int i = 400; i < 1000; i++)
                {
                    var    hashtags = client.Hashtags(text: strArray[i]);
                    string hashtag  = String.Join(", ", hashtags.HashtagsMember);
                    if (hashtag != "" && hashtag != null)
                    {
                        ws.Cells[i + 1, 9] = hashtag;
                    }
                    wb.Save();
                    Console.WriteLine(i);
                }
            }
            finally
            {
                wb.Close();
            }
        }
Пример #19
0
        //private bool _canExecute;
        public void MyAction()
        {
            try
            {
                Microsoft.Office.Interop.Excel.Application xlApp;
                Microsoft.Office.Interop.Excel.Workbook    xlWorkbook;
                Microsoft.Office.Interop.Excel.Worksheet   xlWorksheet;
                object misValue = System.Reflection.Missing.Value;


                xlApp       = new Microsoft.Office.Interop.Excel.Application();
                xlWorkbook  = xlApp.Workbooks.Open(FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);

                //int startColumn = Header.Cells.Column;
                //int startRow = header.Cells.Row + 1;
                int col = ExcelColumnNameToNumber(Column);
                Microsoft.Office.Interop.Excel.Range startCell = xlWorksheet.Cells[StartRow, col];
                Microsoft.Office.Interop.Excel.Range endCell   = xlWorksheet.Cells[EndRow, col];
                Microsoft.Office.Interop.Excel.Range myRange   = xlWorksheet.Range[startCell, endCell];
                System.Array myvalues = (System.Array)myRange.Cells.Value;
                string[]     strArray = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();

                foreach (var ticketId in strArray)
                {
                    try
                    {
                        IConnectWiseService _connectWiseService = new ConnectWiseService(Company, BaseUrl, SiteUrl, SiteSuffix, PublicKey, PrivateKey);
                        //var res = _connectWiseService.ChangeCompany(Convert.ToInt32(ticketId), Value).Result;
                        var res = _connectWiseService.ChangeGenerically(Convert.ToInt32(ticketId), Value, Op, Path).Result;
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #20
0
        // To fetch data from the excel worksheets
        public String[] fetchKeysFromExcel(int flag)
        {
            Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlsApp == null)
            {
                Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
                //return null;
            }

            //Displays Excel so you can see what is happening

            if (flag == 1)
            {
                Workbook     wb            = xlsApp.Workbooks.Open(Program.excelFilePath, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
                Sheets       sheets        = wb.Worksheets;
                Worksheet    wsD1          = (Worksheet)sheets.get_Item(1);
                Worksheet    wsD2          = (Worksheet)sheets.get_Item(2);
                Range        firstColumnD1 = wsD1.UsedRange.Columns[1];
                Range        firstColumnD2 = wsD2.UsedRange.Columns[1];
                System.Array myvaluesD1    = (System.Array)firstColumnD1.Cells.Value;
                string[]     strArrayD1    = myvaluesD1.OfType <object>().Select(o => o.ToString()).ToArray();

                return(strArrayD1);
            }
            else
            {
                Workbook     wb            = xlsApp.Workbooks.Open(Program.excelFilePath, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
                Sheets       sheets        = wb.Worksheets;
                Worksheet    wsD1          = (Worksheet)sheets.get_Item(1);
                Worksheet    wsD2          = (Worksheet)sheets.get_Item(2);
                Range        firstColumnD1 = wsD1.UsedRange.Columns[1];
                Range        firstColumnD2 = wsD2.UsedRange.Columns[1];
                System.Array myvaluesD2    = (System.Array)firstColumnD2.Cells.Value;
                string[]     strArrayD2    = myvaluesD2.OfType <object>().Select(o => o.ToString()).ToArray();

                return(strArrayD2);
            }
        }
Пример #21
0
        private static List <string> GetAllTestCaseName()
        {
            List <string> strarr = new List <string>();

            Application xlApp         = new Application();
            Workbook    xlWorkbook    = xlApp.Workbooks.Open(excelDataSourcePath, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
            Sheets      sheets        = xlWorkbook.Worksheets;
            Worksheet   xlWorksheet   = (Worksheet)sheets.get_Item(1);
            Range       xlFirstColumn = xlWorksheet.UsedRange.Columns[1];

            System.Array myvalues = (System.Array)xlFirstColumn.Cells.Value;
            string[]     strArray = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();
            foreach (string val in strArray)
            {
                strarr.Add(val);
            }

            Marshal.ReleaseComObject(xlWorksheet);
            xlWorkbook.Close(0);
            xlApp.Quit();
            Marshal.ReleaseComObject(xlWorkbook);
            Marshal.ReleaseComObject(xlApp);
            return(strarr);
        }
Пример #22
0
        private void btn2_Click(object sender, System.EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Range Rng;
            fileExcel = @"C:\Users\hp\source\repos\WpfApp9\WpfApp9\obj\Debug\SK_Moschnost.xlsx";
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            // open workbook
            Microsoft.Office.Interop.Excel.Workbook  xlWorkBook = xlApp.Workbooks.Open(fileExcel, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Worksheet xlSheet    = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[1];
            Microsoft.Office.Interop.Excel.Chart     xlChart;
            Microsoft.Office.Interop.Excel.Series    xlSeries;
            xlApp.Visible     = true;
            xlApp.UserControl = true;
            Microsoft.Office.Interop.Excel.Range usedColumn = xlSheet.UsedRange.Columns[2];
            System.Array myvalues = (System.Array)usedColumn.Cells.Value2;
            string[]     strArray = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();

            for (int i = 1; i < strArray.Length; i++)
            {
                data.Add(Convert.ToDouble(strArray[i]));
            }

            for (double g = gamin; g < gamax; g += 1000)
            {
                for (double T = 0; T <= tf - t0; T += 0.01)
                {
                    for (double t = t0; t <= tf; t += 0.01)
                    {
                        function(t, T, g);
                    }
                }
            }
            gamma();
            minmax();
            timemax();
            taumin2();
            gmin22();
            String sMsg;

            sMsg = "Minimum of maximum |f(gamma,tau)|: ";
            sMsg = String.Concat(sMsg, minmax());
            sMsg = String.Concat(sMsg, " Вт, when minimum of gamma: ");
            sMsg = String.Concat(sMsg, gmin22());
            sMsg = String.Concat(sMsg, ", minimum of tau: ");
            sMsg = String.Concat(sMsg, taumin2());
            sMsg = String.Concat(sMsg, ", maximum of time: ");
            sMsg = String.Concat(sMsg, timemax());

            MessageBoxResult mes = MessageBox.Show(sMsg, "Caculate and draw graphic?", MessageBoxButton.YesNo);

            if (mes == MessageBoxResult.No)
            {
                Close();
            }
            else
            {
                //Add table headers going cell by cell.
                xlSheet.Cells[1, 4] = "Время [t0,tf], сек.";
                xlSheet.Cells[1, 5] = "|f(gamma,tau)|";


                //AutoFit columns A:B.
                Rng = xlSheet.get_Range("A1:G1");
                Rng.EntireColumn.AutoFit();

                // interval [t0, tf]
                Rng         = xlApp.get_Range("D2", "D1002");
                Rng.Formula = "=A101";


                StreamWriter txt = new StreamWriter("testinte2.txt");
                for (double t = t0; t < tf; t += 0.01)
                {
                    txt.WriteLine(Math.Abs(gmin22() - data[Convert.ToInt32(t * 100)] - data[Convert.ToInt32((t + taumin2()) * 100)]));
                }
                txt.Close();
                object   misvalue = System.Reflection.Missing.Value;
                string[] txtname  = System.IO.File.ReadAllLines(@"C:\Users\hp\source\repos\WpfApp9\WpfApp9\bin\Debug\testinte2.txt");
                try
                {
                    for (int i = 0; i <= txtname.Length; i++)
                    {
                        xlSheet.Cells[5][i + 2] = txtname[i];
                    }
                    Thread.Sleep(3000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception" + ex);
                }
                // add a chart for the selected data
                xlWorkBook = (Microsoft.Office.Interop.Excel.Workbook)xlSheet.Parent;
                xlChart    = (Microsoft.Office.Interop.Excel.Chart)xlWorkBook.Charts.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                // use the ChartWizard to create a new chart from the select data
                xlSeries         = (Microsoft.Office.Interop.Excel.Series)xlChart.SeriesCollection(1);
                xlSeries.XValues = xlSheet.get_Range("E2:E1002");
            }
        }
        private void btnBrowseExcel_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter           = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();

                    if (xlsApp == null)
                    {
                        MessageBox.Show("EXCEL could not be started. Check that your office installation and project references are correct.");
                    }
                    else
                    {
                        Workbook  wb     = xlsApp.Workbooks.Open(openFileDialog1.FileName, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
                        Sheets    sheets = wb.Worksheets;
                        Worksheet ws     = (Worksheet)sheets.get_Item(1);

                        Range        firstColumn  = ws.UsedRange.Columns[1];
                        System.Array myvalues     = (System.Array)firstColumn.Cells.Value;
                        string[]     excelNumbers = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();


                        if (!String.IsNullOrEmpty(txtTo.Text))
                        {
                            for (int i = 0; i < excelNumbers.Length; i++)
                            {
                                if (excelNumbers[i][0] == '0')
                                {
                                    txtTo.Text += "," + excelNumbers[i];
                                }
                                else
                                {
                                    txtTo.Text += ",0" + excelNumbers[i];
                                }
                            }
                        }
                        else
                        {
                            for (int i = 0; i < excelNumbers.Length; i++)
                            {
                                if (excelNumbers[i][0] == '0')
                                {
                                    txtTo.Text += excelNumbers[i] + ",";
                                }
                                else
                                {
                                    txtTo.Text += "0" + excelNumbers[i] + ",";
                                }
                            }
                            txtTo.Text = txtTo.Text.Remove(txtTo.TextLength - 1);
                        }
                        MessageBox.Show("Numbers imported successfully !");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }
Пример #24
0
        private void ManageButton_Click(object sender, EventArgs e)
        {
            try
            {
                Worksheet     worksheet  = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets.Cast <Worksheet>().SingleOrDefault(w => w.Name == Constants.UserPermissionTable);
                List <string> sheetNames = new List <string>();
                foreach (Worksheet ws in Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets)
                {
                    sheetNames.Add(ws.Name);
                }

                if (worksheet == null)
                {
                    Worksheet theSheet = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets.Add();
                    theSheet.Name = Constants.UserPermissionTable;
                    sheetNames.Add(Constants.UserPermissionTable);
                    int columnOffset = 5;
                    var numOfSheets  = sheetNames.Count;
                    var rng          = theSheet.Range[theSheet.Cells[1, 1], theSheet.Cells[3, numOfSheets + columnOffset]];
                    string[,] values = new string[3, numOfSheets + columnOffset];
                    values[0, 0]     = "ID";
                    values[1, 0]     = "admin";
                    values[2, 0]     = Constants.guest;

                    values[0, 1] = Constants.structure;
                    values[1, 1] = Constants.Mutable;
                    values[2, 1] = Constants.InMutable;

                    values[0, 2] = Constants.managementTab;
                    values[1, 2] = Constants.Visible;
                    values[2, 2] = Constants.Invisible;

                    values[0, 3] = Constants.buysideTab;
                    values[1, 3] = Constants.Visible;
                    values[2, 3] = Constants.Invisible;

                    values[0, 4] = Constants.sellsideTab;
                    values[1, 4] = Constants.Visible;
                    values[2, 4] = Constants.Invisible;

                    for (var i = 0; i < sheetNames.Count; i++)
                    {
                        values[0, i + columnOffset] = sheetNames[i];
                        values[1, i + columnOffset] = Constants.Writable;
                        values[2, i + columnOffset] = Constants.ReadOnly;
                    }
                    rng.Value = values;
                    theSheet.Range["B:B"].Validation.Add(XlDVType.xlValidateList, Type.Missing, XlFormatConditionOperator.xlBetween, Constants.Mutable + "," + Constants.InMutable);
                    theSheet.Range["B:B"].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSalmon);
                    theSheet.Range["C:E"].Validation.Add(XlDVType.xlValidateList, Type.Missing, XlFormatConditionOperator.xlBetween, Constants.Visible + "," + Constants.Invisible);
                    theSheet.Range["C:E"].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Wheat);
                    theSheet.Range["F:" + GetExcelColumnName(numOfSheets + columnOffset)].Validation.Add(XlDVType.xlValidateList, Type.Missing, XlFormatConditionOperator.xlBetween, Constants.PermissionOperation);
                    theSheet.Range["F:" + GetExcelColumnName(numOfSheets + columnOffset)].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightBlue);
                    theSheet.Range["1:1"].Validation.Delete();
                    //theSheet.Range["A:A"].Validation.Delete();
                }
                else
                {
                    Worksheet theSheet = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[Constants.UserPermissionTable];
                    unHideWorkSheet(theSheet);

                    theSheet.Select();
                    Range         firstRow = theSheet.UsedRange.Rows[1];
                    System.Array  myvalues = (System.Array)firstRow.Cells.Value;
                    List <string> lst      = myvalues.OfType <object>().Select(o => o.ToString()).ToList();
                    List <string> toAdd    = new List <string>();
                    foreach (string name in sheetNames)
                    {
                        if (!lst.Contains(name))
                        {
                            toAdd.Add(name);
                        }
                    }
                    //newSheetNames.AddRange(toAdd);
                    foreach (string newColumnName in toAdd)
                    {
                        Range rangeTarget = worksheet.Cells[1, theSheet.UsedRange.Columns.Count + 1];
                        rangeTarget.Value2 = newColumnName;
                    }
                    int totalColumns = sheetNames.Count + 5;
                    //MessageBox.Show(totalColumns.ToString());
                    theSheet.Range["B:" + GetExcelColumnName(totalColumns)].Validation.Delete();
                    theSheet.Range["B:B"].Validation.Add(XlDVType.xlValidateList, Type.Missing, XlFormatConditionOperator.xlBetween, Constants.Mutable + "," + Constants.InMutable);
                    theSheet.Range["B:B"].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSalmon);
                    theSheet.Range["C:E"].Validation.Add(XlDVType.xlValidateList, Type.Missing, XlFormatConditionOperator.xlBetween, Constants.Visible + "," + Constants.Invisible);
                    theSheet.Range["C:E"].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Wheat);
                    theSheet.Range["F:" + GetExcelColumnName(totalColumns)].Validation.Add(XlDVType.xlValidateList, Type.Missing, XlFormatConditionOperator.xlBetween, Constants.PermissionOperation);
                    theSheet.Range["F:" + GetExcelColumnName(totalColumns)].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightBlue);
                    theSheet.Range["1:1"].Validation.Delete();
                }
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                MessageBox.Show(Constants.PROTECTED_ERROR_MESSAGE);
            }
        }
Пример #25
0
        public void SelectFileBtn_Click(object sender, EventArgs e)
        {
            //оно работает, поэтому лучше не трогать
            if (OFD.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            // получаем выбранный файл
            string catalogFile = OFD.FileName;

            pathFileL.Text += catalogFile;
            string pathToFile = catalogFile;

            Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
            //Открываем книгу.
            Microsoft.Office.Interop.Excel.Workbook ObjWorkBook = ObjExcel.Workbooks.Open(pathToFile, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Выбираем таблицу(лист).
            Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
            ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1];

            // Указываем номер столбца (таблицы Excel) из которого будут считываться данные.
            int photoCol = 2;

            Microsoft.Office.Interop.Excel.Range photoColumn = ObjWorkSheet.UsedRange.Columns[photoCol];
            System.Array photoValues = (System.Array)photoColumn.Cells.Value2;
            //получаем массив данных
            string[] photoArray = photoValues.OfType <object>().Select(o => o.ToString()).ToArray();

            //получаем вспомогательные данные
            int columnsCount = ObjWorkSheet.UsedRange.Columns.Count;
            int rowCount     = ObjWorkSheet.UsedRange.Rows.Count;

            rowCountL.Text    += rowCount;
            columnCountL.Text += columnsCount;

            for (int i = 1; i < rowCount; i++)
            {
                photoFilesLB.Items.Add(photoArray[i]);
            }
            ;
            PhotoCountL.Text += photoFilesLB.Items.Count;


            int modelsCol = 1;

            Microsoft.Office.Interop.Excel.Range modelsColumn = ObjWorkSheet.UsedRange.Columns[modelsCol];
            System.Array modelsColumnValues = (System.Array)modelsColumn.Cells.Value2;
            string[]     modelsArray        = modelsColumnValues.OfType <object>().Select(o => o.ToString()).ToArray();

            for (int i = 1; i < rowCount; i++)
            {
                ModelsLB.Items.Add(modelsArray[i]);
            }
            ;
            ModelsCountL.Text += ModelsLB.Items.Count;


            int morePhotoCol = 3;

            Microsoft.Office.Interop.Excel.Range morePhottoColumn = ObjWorkSheet.UsedRange.Columns[morePhotoCol];
            Array morePhotoValues = (Array)morePhottoColumn.Cells.Value2;

            string[] morePhotoArray = morePhotoValues.OfType <object>().Select(o => o.ToString()).ToArray();

            ObjExcel.Quit();

            MorePhotoArraySplit(morePhotoArray, rowCount);

            MorePhotoCountL.Text += morePhotoFilesLB.Items.Count;

            string catalogPath      = @"j:/katalog";
            string tempPath         = @"d:/photo_for_site";
            int    removeFilesCount = 0;

            DirectoryInfo dirInfo = new DirectoryInfo(tempPath);

            if (!dirInfo.Exists)
            {
                dirInfo.Create();
            }
            else
            {
                MessageBox.Show("Ошибка создания каталога", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            var timer = Stopwatch.StartNew();

            CreateMorePhotoPathList(GetMorePhotoSplitCount(), GetSplitMorePhotoArray(), catalogPath, tempPath);

            //ConcatPathArrays(GetMorePhotoPathCount(), GetMorePhotoPathArray());

            RefreshFileCountLabel(0, rowCount);

            for (int i = 1; i < rowCount; i++)
            {
                string curFilePath;
                //string curFilePath = String.Concat(catalogPath, "/", modelsArray[i], "/", photoArray[i]);
                if (photoArray[i].IndexOf('_') >= 1)
                {
                    curFilePath = String.Concat(catalogPath, "/", photoArray[i].Substring(0, photoArray[i].Length - 4), "/", photoArray[i]);
                }
                else
                {
                    curFilePath = String.Concat(catalogPath, "/", photoArray[i]);
                }
                // string curFilePath = String.Concat(catalogPath, "/", photoArray[i].Substring(0, photoArray[i].Length - 4), "/", photoArray[i]);
                string curCatalogPath = String.Concat(tempPath, "/", photoArray[i]);
                TempLB.Items.Add(curFilePath);

                //RemoveFileCountL.Text += removeFilesCount.ToString() + "/" + rowCount.ToString();
                System.IO.File.Copy(curFilePath, curCatalogPath, true);
                removeFilesCount++;
                RefreshFileCountLabel(i, rowCount - 1);
                if (i == rowCount - 1)
                {
                    timer.Stop();
                    int    seconds = System.Int32.Parse(((timer.ElapsedMilliseconds / 1000) % 60).ToString());
                    int    minutes = System.Int32.Parse(((timer.ElapsedMilliseconds / 1000) / 60).ToString());
                    string message = "Копирвоание окончено, количество перемещенных моделей: " + removeFilesCount.ToString() + " + \rВремя выполнения: " + minutes + ":" + seconds;
                    MessageBox.Show(message, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); //+ timer.ElapsedMilliseconds/1000 + " сек");
                }
            }
            ;
            TempCountL.Text += TempLB.Items.Count;
        }
 /// <summary>
 /// Adds an array of values to the current collection.
 /// </summary>
 /// <param name="values">an array of BigQueryParameter objects.</param>
 public override void AddRange(Array values)
 {
     innerList.AddRange(values.OfType<BigQueryParameter>().ToArray());
 }
Пример #27
0
 public override void CopyTo(Array array, int index)
 {
     _list.CopyTo(array.OfType<ODataParameter>().ToArray(), index);
 }
Пример #28
0
 public override void AddRange(Array values)
 {
     _list.AddRange(values.OfType<ODataParameter>());
 }
Пример #29
0
        static void Main(string[] args)
        {
            Excel.Application ex = new Microsoft.Office.Interop.Excel.Application();

            ex.Workbooks.Open(@"*****.xls",
                              Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                              false, Type.Missing, Type.Missing, Type.Missing,
                              Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                              Type.Missing, Type.Missing);

            Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
            ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ex.Sheets[1];

            // Указываем номер столбца
            int numCol = 2;

            Excel.Range  usedColumn = ObjWorkSheet.UsedRange.Columns[numCol];
            System.Array myvalues   = (System.Array)usedColumn.Cells.Value2;

            var j = 0;

            string[] strArray = myvalues.OfType <object>().Select(o => o.ToString()).ToArray();
            Console.WriteLine(strArray.Length);

            foreach (var i in strArray)
            {
                var str = strArray[j];

                var url = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/findById/party";

                //генерация запроса
                HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
                req.Method  = "POST";
                req.Timeout = 10000;
                req.Headers.Add("Authorization", "Token *******");
                req.ContentType = "application/json";
                req.Accept      = "application/json";

                //данные для отправки
                var sentData = Encoding.UTF8.GetBytes("{ \"query\": \"" + strArray[j] + "\" }");
                req.ContentLength = sentData.Length;
                Stream sendStream = req.GetRequestStream();
                sendStream.Write(sentData, 0, sentData.Length);

                //получение ответа
                var res       = req.GetResponse() as HttpWebResponse;
                var resStream = res.GetResponseStream();
                var sr        = new StreamReader(resStream, Encoding.UTF8);

                var response = sr.ReadToEnd();

                ApiResponse apiResponse = JsonConvert.DeserializeObject <ApiResponse>(response);
                var         x           = 0;

                foreach (var z in apiResponse.Suggestions)
                {
                    // ОПФ
                    if (apiResponse.Suggestions[x].data.opf != null)
                    {
                        ObjWorkSheet.Cells[1, "Q"]     = "ОПФ";
                        ObjWorkSheet.Cells[j + 1, "Q"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.opf.@short) ? "" : apiResponse.Suggestions[x].data.opf.@short;
                    }

                    //Полное Наименование
                    if (apiResponse.Suggestions[x].data.name != null)
                    {
                        ObjWorkSheet.Cells[1, "S"]     = "Полное Наименование";
                        ObjWorkSheet.Cells[j + 1, "S"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.name.full_with_opf) ? "" : apiResponse.Suggestions[x].data.name.full_with_opf;
                    }

                    if (apiResponse.Suggestions[x].data != null)
                    {
                        ObjWorkSheet.Cells[1, "R"]     = "КПП";
                        ObjWorkSheet.Cells[j + 1, "R"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.kpp) ? "" : apiResponse.Suggestions[x].data.kpp;
                    }

                    if (apiResponse.Suggestions[x].data.address.data != null)
                    {
                        ObjWorkSheet.Cells[1, "T"]     = "Регион";
                        ObjWorkSheet.Cells[j + 1, "T"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.address.data.region_with_type) ? "" : apiResponse.Suggestions[x].data.address.data.region_with_type;

                        ObjWorkSheet.Cells[1, "U"]     = "Район";
                        ObjWorkSheet.Cells[j + 1, "U"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.address.data.city_district_with_type) ? "" : apiResponse.Suggestions[x].data.address.data.city_district_with_type;

                        ObjWorkSheet.Cells[1, "V"]     = "Город";
                        ObjWorkSheet.Cells[j + 1, "V"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.address.data.city_with_type) ? "" : apiResponse.Suggestions[x].data.address.data.city_with_type;

                        ObjWorkSheet.Cells[1, "W"]     = "Улица";
                        ObjWorkSheet.Cells[j + 1, "W"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.address.data.street_with_type) ? "" : apiResponse.Suggestions[x].data.address.data.street_with_type;

                        ObjWorkSheet.Cells[1, "X"]     = "Дом";
                        ObjWorkSheet.Cells[j + 1, "X"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.address.data.house) ? "" : apiResponse.Suggestions[x].data.address.data.house;

                        ObjWorkSheet.Cells[1, "Y"]     = "Корпус";
                        ObjWorkSheet.Cells[j + 1, "Y"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.address.data.block) ? "" : apiResponse.Suggestions[x].data.address.data.block;

                        ObjWorkSheet.Cells[1, "Z"]     = "Квартира";
                        ObjWorkSheet.Cells[j + 1, "Z"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.address.data.flat) ? "" : apiResponse.Suggestions[x].data.address.data.flat;

                        ObjWorkSheet.Cells[1, "AA"]     = "Индекс";
                        ObjWorkSheet.Cells[j + 1, "AA"] = String.IsNullOrEmpty(apiResponse.Suggestions[x].data.address.data.postal_code) ? "" : apiResponse.Suggestions[x].data.address.data.postal_code;
                    }
                    x++;
                }
                j++;
            }

            ex.Visible = true;        //Отобразить Excel

            ex.DisplayAlerts = false; //Отключить отображение окон с сообщениями
            ex.Application.ActiveWorkbook.SaveAs("*****.xls", Type.Missing,
                                                 Type.Missing, Type.Missing, Type.Missing, false, Excel.XlSaveAsAccessMode.xlNoChange,
                                                 Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            ex.Quit();
        }
        private static void EncodeContactSourceNumbers(List<KeyValuePair<string, string>> result, Array array, string elementName)
        {
            var arrayValue = string.Join(" ",
                array.OfType<ContactSourceNumbers>().Select(e => string.Join(" ", e.Text)).ToArray());
            result.Add(new KeyValuePair<string, string>(string.Format("{0}", elementName), HttpUtility.UrlEncode(arrayValue)));

            var arrayData = string.Join(" ", array.OfType<ContactSourceNumbers>().Select(e => e.fieldName).ToArray());
            result.Add(new KeyValuePair<string, string>(string.Format("{0}[fieldName]", elementName),
                HttpUtility.UrlEncode(arrayData)));
        }
        private static void EncodeToNumber(List<KeyValuePair<string, string>> result, Array array)
        {
            var arrayValue = string.Join(" ", array.OfType<ToNumber>().Select(e => e.Value).ToArray());
            result.Add(new KeyValuePair<string, string>("To", HttpUtility.UrlEncode(arrayValue)));

            var arrayData = string.Join(" ", array.OfType<ToNumber>().Select(e => e.ClientData).ToArray());
            result.Add(new KeyValuePair<string, string>("ToNumber[ClientData]", HttpUtility.UrlEncode(arrayData)));
        }
Пример #32
0
 public bool AreKeysDown(Array arr)
 {
     return AreKeysDown(arr.OfType<Key>());
 }
Пример #33
0
        static void Main(string[] args)
        {
            Excel.Application xlApp = new Excel.Application();

            Excel.Workbook   movieWorkbook = xlApp.Workbooks.Open(@"C:\Users\Class2018\source\repos\movieData\movieData\Movie Data.xlsx");
            Excel._Worksheet xlWorksheet   = movieWorkbook.Sheets[1];

            Excel.Range titleCol     = xlWorksheet.Columns[1];
            Excel.Range yearCol      = xlWorksheet.Columns[2];
            Excel.Range genreCol     = xlWorksheet.Columns[3];
            Excel.Range dirCol       = xlWorksheet.Columns[4];
            Excel.Range runCol       = xlWorksheet.Columns[5];
            Excel.Range grossCol     = xlWorksheet.Columns[6];
            Excel.Range ratingCol    = xlWorksheet.Columns[7];
            Excel.Range franchiseCol = xlWorksheet.Columns[8];
            Excel.Range studioCol    = xlWorksheet.Columns[9];

            System.Array listVals  = (System.Array)titleCol.Cells.Value;
            string[]     allTitles = listVals.OfType <object>().Select(o => o.ToString()).ToArray();

            System.Array listVals1 = (System.Array)yearCol.Cells.Value;
            string[]     allYears  = listVals1.OfType <object>().Select(o => o.ToString()).ToArray();

            System.Array listVals2 = (System.Array)genreCol.Cells.Value;
            string[]     allGenre  = listVals2.OfType <object>().Select(o => o.ToString()).ToArray();

            System.Array listVals3 = (System.Array)dirCol.Cells.Value;
            string[]     allDir    = listVals3.OfType <object>().Select(o => o.ToString()).ToArray();

            System.Array listVals4 = (System.Array)runCol.Cells.Value;
            string[]     allRun    = listVals4.OfType <object>().Select(o => o.ToString()).ToArray();

            System.Array listVals5 = (System.Array)grossCol.Cells.Value;
            string[]     allGross  = listVals5.OfType <object>().Select(o => o.ToString()).ToArray();

            System.Array listVals6 = (System.Array)ratingCol.Cells.Value;
            string[]     allRating = listVals6.OfType <object>().Select(o => o.ToString()).ToArray();

            System.Array listVals7 = (System.Array)franchiseCol.Cells.Value;
            string[]     allFran   = listVals7.OfType <object>().Select(o => o.ToString()).ToArray();

            System.Array listVals8 = (System.Array)studioCol.Cells.Value;
            string[]     allStudio = listVals8.OfType <object>().Select(o => o.ToString()).ToArray();

            Stats s = new Stats();

            Dictionary <string, int> DictYears  = s.AddYears(allYears);
            Dictionary <string, int> DictGenres = s.AddGenres(allGenre);
            Dictionary <string, int> DictDirs   = s.AddDirectors(allDir);
            Dictionary <string, int> DictRating = s.AddGenres(allRating);
            Dictionary <string, int> DictFran   = s.AddGenres(allFran);
            Dictionary <string, int> DictStudio = s.AddGenres(allStudio);

            s.SetGrossStats(allGross, allTitles);
            s.SetRunStats(allRun, allTitles);

            Console.WriteLine("Time Average: {0} min", s.GetRunAvg());
            Console.WriteLine("Shortest: {0} at {1} min", s.GetShortestFilm(), s.GetMinRun());
            Console.WriteLine("Longest: {0} at {1} min", s.GetLongestFilm(), s.GetMaxRun());

            Console.WriteLine("Gross Average: ${0}", s.GetGrossAvg());
            Console.WriteLine("Lowest: {0} at ${1}", s.GetLowestFilm(), s.GetMinGross());
            Console.WriteLine("Highest: {0} at ${1}", s.GetHighestFilm(), s.GetMaxGross());

            //write to excel sheets
            Excel._Worksheet xlWorksheet2 = movieWorkbook.Sheets[2];
            xlWorksheet2.Cells[1, 1] = "Directors";
            xlWorksheet2.Cells[1, 2] = "Count";

            int a = 1;

            foreach (var directors in DictDirs)
            {
                a++;
                xlWorksheet2.Cells[a, 1] = directors.Key;
                xlWorksheet2.Cells[a, 2] = directors.Value;
            }

            Excel._Worksheet xlWorksheet3 = movieWorkbook.Sheets[3];
            xlWorksheet3.Cells[1, 1] = "Years";
            xlWorksheet3.Cells[1, 2] = "Count";

            int b = 1;

            foreach (var years in DictYears)
            {
                b++;
                xlWorksheet3.Cells[b, 1] = years.Key;
                xlWorksheet3.Cells[b, 2] = years.Value;
            }

            Excel._Worksheet xlWorksheet4 = movieWorkbook.Sheets[4];
            xlWorksheet4.Cells[1, 1] = "Genre";
            xlWorksheet4.Cells[1, 2] = "Count";

            int c = 1;

            foreach (var genres in DictGenres)
            {
                c++;
                xlWorksheet4.Cells[c, 1] = genres.Key;
                xlWorksheet4.Cells[c, 2] = genres.Value;
            }

            Excel._Worksheet xlWorksheet5 = movieWorkbook.Sheets[5];
            xlWorksheet5.Cells[1, 1] = "Rating";
            xlWorksheet5.Cells[1, 2] = "Count";

            int d = 1;

            foreach (var ratings in DictRating)
            {
                d++;
                xlWorksheet5.Cells[d, 1] = ratings.Key;
                xlWorksheet5.Cells[d, 2] = ratings.Value;
            }

            Excel._Worksheet xlWorksheet6 = movieWorkbook.Sheets[6];
            xlWorksheet6.Cells[1, 1] = "Franchise";
            xlWorksheet6.Cells[1, 2] = "Count";

            int e = 1;

            foreach (var franchises in DictFran)
            {
                e++;
                xlWorksheet6.Cells[e, 1] = franchises.Key;
                xlWorksheet6.Cells[e, 2] = franchises.Value;
            }

            Excel._Worksheet xlWorksheet7 = movieWorkbook.Sheets[7];
            xlWorksheet7.Cells[1, 1] = "Studio";
            xlWorksheet7.Cells[1, 2] = "Count";

            int x = 1;

            foreach (var studio in DictStudio)
            {
                x++;
                xlWorksheet7.Cells[x, 1] = studio.Key;
                xlWorksheet7.Cells[x, 2] = studio.Value;
            }

            Console.WriteLine("Done!");

            Marshal.ReleaseComObject(yearCol);
            Marshal.ReleaseComObject(genreCol);
            Marshal.ReleaseComObject(dirCol);
            Marshal.ReleaseComObject(runCol);
            Marshal.ReleaseComObject(grossCol);
            Marshal.ReleaseComObject(ratingCol);
            Marshal.ReleaseComObject(franchiseCol);
            Marshal.ReleaseComObject(studioCol);
            Marshal.ReleaseComObject(xlWorksheet);
            Marshal.ReleaseComObject(xlWorksheet2);
            Marshal.ReleaseComObject(xlWorksheet3);
            Marshal.ReleaseComObject(xlWorksheet4);
            Marshal.ReleaseComObject(xlWorksheet5);
            Marshal.ReleaseComObject(xlWorksheet6);
            Marshal.ReleaseComObject(xlWorksheet7);

            movieWorkbook.Save();

            movieWorkbook.Close(0);
            Marshal.ReleaseComObject(movieWorkbook);

            xlApp.Quit();
            Marshal.ReleaseComObject(xlApp);
        }