protected override void Dispose(bool disposing)
        {
            lock (m_lock)
            {
                if (m_disposed)
                    return;

                ApplicationControllerTrace trace = new ApplicationControllerTrace();

                m_disposed = true;
                                
                try
                {
                    Quit();
                }
                catch (Exception e)
                {
                    trace.Log(e);
                    // ignore.
                }
                finally
                {
                    trace.Log("Releasing word application");

                    if (null != m_hostApplication)
                        Marshal.FinalReleaseComObject(m_hostApplication);

                    m_hostApplication = null;
                }

                base.Dispose(disposing);
            }
        }
Example #2
0
		protected internal string GetViServerStatus(_Application app)
		{
			StringBuilder message = new StringBuilder("AppStatus: ");
			try
			{				
				if(app != null)
				{
					//viServer.CheckConnection();				
					//message.Append(app.ToString());
                    message.Append("\tAppName: " + app.AppName);
                    message.Append("\tDirectory: " + app.ApplicationDirectory);
					message.Append("\tVersion: " + app.Version);
					message.Append("\tUserName: "******"\tProcessID: " + app._ProcessID);
				}
				else
				{
					message.Append("labViewApp = null");
				}
			}
			catch(Exception ex)
			{
				message.Append("Error: " + ex.Message + ex.StackTrace);
				throw(ex);
			}
			message.ToString();
			return message.ToString();
		}
		public static IAccessible GetTabByName(string tabName, _Application wordApp)
		{
			IAccessible result = null;
			var ribbon = wordApp.CommandBars["Ribbon"];
			var ribbona = ribbon as IAccessible;

			try
			{
				EnumerateChildren(ribbona, accessibles =>
					{
						for (var i = 0; i < accessibles.Length; i++)
						{
							var child = accessibles[i];
							if (!Marshal.IsComObject(child)) continue;

							if (result == null && HasName(child, tabName))
							{
								result = child;
								break;
							}
						}

						return result == null;
					});
			}
			catch
			{}
			finally
			{
				if (ribbon != null) Marshal.ReleaseComObject(ribbon);
				if (ribbona != null) Marshal.ReleaseComObject(ribbona);
			}

			return result;
		}
Example #4
0
        ///////////////////////////////////////////////////////////////////////////
        //
        //  CONSTRUCTION
        //
        ///////////////////////////////////////////////////////////////////////////
        #region CONSTRUCTION

        /// <summary>
        /// 새로운 ExcelFile 개체 인스턴스를 초기화 합니다.
        /// </summary>
        private ExcelFile()
        {
            _xlApp = new Application();

            _xlApp.Visible = false;

            // Do not disturbed by prompts and alert messages while a program is running.
            _xlApp.DisplayAlerts = false;
        }
Example #5
0
 //构造器
 public LoadPlanExtracter(string path)
 {
     _context  = new ApplicationDbContext();
     _path     = path;
     _excel    = new Application();
     _wb       = _excel.Workbooks.Open(_path);
     _ws       = _wb.Worksheets[1];
     _userName = HttpContext.Current.User.Identity.Name.Split('@')[0] == "" ? (HttpContext.Current.Request.Headers.Get("AppUser") == null ? "" : HttpContext.Current.Request.Headers.Get("AppUser")) : HttpContext.Current.User.Identity.Name.Split('@')[0];
 }
Example #6
0
 private void DemoOpenDSSUI_FormClosed( object sender, FormClosedEventArgs e )
 {
     if ( workbook != null )
     workbook.Close( false, Type.Missing, Type.Missing );
      workbook = null;
      if ( application != null )
     application.Quit();
      application = null;
 }
Example #7
0
 public Base()
 {
     App               = new Application();
     App.Visible       = true;
     App.DisplayAlerts = false;
     Books             = App.Workbooks;
     Book              = Books.Add(Missing.Value);
     Sheet             = Book.ActiveSheet;
 }
Example #8
0
 //构造器
 public LoadPlanExtracter(string path)
 {
     _context  = new ApplicationDbContext();
     _path     = path;
     _excel    = new Application();
     _wb       = _excel.Workbooks.Open(_path);
     _ws       = _wb.Worksheets[1];
     _userName = HttpContext.Current.User.Identity.Name.Split('@')[0];
 }
        private static void CloseQuitAndRelease(_Application excellApp, _Worksheet excellWorkSheet, _Workbook excellWorkBook)
        {
            object misValue = Missing.Value;

            excellWorkBook.Close(true, misValue, misValue);
            excellApp.Quit();
            ReleaseObject(excellApp);
            ReleaseObject(excellWorkBook);
            ReleaseObject(excellWorkSheet);
        }
Example #10
0
 private void ExcelClose()
 {
     wb.Close(false);
     excel.Quit();
     System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
     excel = null;
     wb    = null;
     ws    = null;
     System.GC.Collect();
 }
Example #11
0
 private void CloseWord()
 {
     if (application != null)
     {
         document.Close(ref falseObj, ref missingObj, ref missingObj);
         application.Quit(ref missingObj, ref missingObj, ref missingObj);
         document    = null;
         application = null;
     }
 }
Example #12
0
        public void Test_CWD_HideenSheet()
        {
            StartCaptureMessage(UrlHandler.Program.TITLE);
            String[] args = { $"{PREFIX}{cwd}\\test Book.xlsx#hidden!G3:I4" };
            Program.Main(args);
            _Application excel = Program.GetExcel();

            Assert.AreEqual("Sheet \"hidden\" not found", StopCaptureMessage());
            excel.ActiveWorkbook.Close();
        }
Example #13
0
 /// <summary>
 /// 处理<see cref="_Application"/>适应自动化
 /// </summary>
 public static _Application ChangeForRPA(this _Application app)
 {
     //禁止Excel进程的各种弹窗
     app.DisplayAlerts = false;
     //取消用户控制模式
     app.UserControl = false;
     //显示Excel窗口
     app.Show();
     return(app);
 }
Example #14
0
 /// <summary>
 /// 适应用户
 /// </summary>
 public static _Application ChangeForUser(this _Application app)
 {
     //启用Excel进程的各种弹窗
     app.DisplayAlerts = true;
     //开启用户控制模式
     app.UserControl = true;
     //显示Excel窗口
     app.Show();
     return(app);
 }
Example #15
0
        public ExcelWriter()
        {
            _excel = new Application
            {
                SheetsInNewWorkbook = 1,
                Visible             = true
            };

            _workbook = _excel.Workbooks.Add(Missing.Value);
        }
Example #16
0
        /// <summary>
        /// 构造函数
        /// </summary>
        public OfficeWordConvert()
        {
            appWord = new Application();
            object template    = Missing.Value;
            object newTemplate = Missing.Value;
            object docType     = Missing.Value;
            object visible     = true;

            doc = appWord.Documents.Add(ref template, ref newTemplate, ref docType, ref visible);
        }
Example #17
0
        private _Document OpenDoc(string path, string printerName)
        {
            _word = CreateWordApp();
            var s = _word.Documents.Add(path);

            //_word.ActivePrinter = printerName; //Note: This will change the Windows deafault printer
            //Therefore, we use this function to print in word without affecting the Windows default printer.
            _word.WordBasic.FilePrintSetup(Printer: printerName, DoNotSetAsSysDefault: 1);
            return(s);
        }
Example #18
0
        public void Test_CWD_Sheet_WrongName()
        {
            StartCaptureMessage(UrlHandler.Program.TITLE);
            String[] args = { $"{PREFIX}{cwd}\\test Book.xlsx#Sheet2!Noname" };
            Program.Main(args);
            _Application excel = Program.GetExcel();

            Assert.AreEqual("Range or Name \"Noname\" not found", StopCaptureMessage());
            excel.ActiveWorkbook.Close();
        }
        public void Export(ObservableCollection <List <CEGRebarInfo> > list)
        {
            _Application application = (Microsoft.Office.Interop.Excel.Application)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("00024500-0000-0000-C000-000000000046")));
            _Workbook    workbook    = application.Workbooks.Add(Type.Missing);
            int          count       = workbook.Sheets.Count;
            _Worksheet   worksheet   = (_Worksheet)workbook.Worksheets.Add((dynamic)workbook.Sheets[count], Type.Missing, Type.Missing, Type.Missing);

            worksheet.Name = "Rebar Schedule";
            dynamic val = worksheet.Range[(dynamic)worksheet.Cells[1, 1], (dynamic)worksheet.Cells[1, 14]];

            val.Font.Bold = true;
            //val.Merge();
            val           = worksheet.Range[(dynamic)worksheet.Cells[1, 1], (dynamic)worksheet.Cells[1, 14]];
            val.Font.Bold = true;
            //val.Merge();
            worksheet.Cells[1, 1]  = "Control Mark";
            worksheet.Cells[1, 2]  = "Bar Size";
            worksheet.Cells[1, 3]  = "Overall Length";
            worksheet.Cells[1, 4]  = "Type NO.";
            worksheet.Cells[1, 5]  = "Bend Dia.";
            worksheet.Cells[1, 6]  = "A";
            worksheet.Cells[1, 7]  = "B";
            worksheet.Cells[1, 8]  = "C";
            worksheet.Cells[1, 9]  = "D";
            worksheet.Cells[1, 10] = "E";
            worksheet.Cells[1, 11] = "F";
            worksheet.Cells[1, 12] = "G";
            worksheet.Cells[1, 13] = "H";
            worksheet.Cells[1, 14] = "K";
            val           = worksheet.Range[(dynamic)worksheet.Cells[1, 1], (dynamic)worksheet.Cells[1, 14]];
            val.Font.Bold = true;
            val.Style.HorizontalAlignment = HorizontalAlignmentStyle.Center;
            int num = 2;

            foreach (var item in list)
            {
                worksheet.Cells[num, 1]  = item.First().ControlMark;
                worksheet.Cells[num, 2]  = item.First().UnistImperial;
                worksheet.Cells[num, 3]  = item.First().DimLength;
                worksheet.Cells[num, 4]  = item.First().TypeNote;
                worksheet.Cells[num, 5]  = item.First().BenDia;
                worksheet.Cells[num, 6]  = item.First().BarLengthA;
                worksheet.Cells[num, 7]  = item.First().BarLengthB;
                worksheet.Cells[num, 8]  = item.First().BarLengthC;
                worksheet.Cells[num, 9]  = item.First().BarLengthD;
                worksheet.Cells[num, 10] = item.First().BarLengthE;
                worksheet.Cells[num, 11] = item.First().BarLengthF;
                worksheet.Cells[num, 12] = item.First().BarLengthG;
                worksheet.Cells[num, 13] = item.First().BarLengthH;
                worksheet.Cells[num, 14] = item.First().BarLengthK;
                num++;
            }
            application.Visible     = true;
            application.WindowState = XlWindowState.xlMaximized;
        }
Example #20
0
        public void readExcel()
        {
            int    count = 1;
            string raws  = "A" + count;

            myRange = mySheet.get_Range(raws);
            Array.Resize(ref question, 1);
            while (Convert.ToString(myRange.Value) != null)
            {
                label1.Text = Convert.ToString(question.Length);//載入題數
                raws        = "A" + count;
                myRange     = mySheet.get_Range(raws);
                //string q = Convert.ToString(myRange.Value);由於50%會變成0.5 故改用myRange.Text
                string q = myRange.Text;

                raws    = "B" + count;
                myRange = mySheet.get_Range(raws);
                //string a = Convert.ToString(myRange.Value);
                string a = myRange.Text;

                raws    = "C" + count;
                myRange = mySheet.get_Range(raws);
                //string b = Convert.ToString(myRange.Value);
                string b = myRange.Text;

                raws    = "D" + count;
                myRange = mySheet.get_Range(raws);
                //string c = Convert.ToString(myRange.Value);
                string c = myRange.Text;

                raws    = "E" + count;
                myRange = mySheet.get_Range(raws);
                //string d = Convert.ToString(myRange.Value);
                string d = myRange.Text;

                raws    = "F" + count;
                myRange = mySheet.get_Range(raws);
                //string ans = Convert.ToString(myRange.Value);
                string ans = myRange.Text;

                question[count - 1] = new MyExcelCollection(q, a, b, c, d, ans);
                Array.Resize(ref question, question.Length + 1);

                raws    = "A" + ++count;
                myRange = mySheet.get_Range(raws);
                //label5.Text = Convert.ToString(count - 1);
            }
            Array.Resize(ref question, question.Length - 1);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
            myBook  = null;
            mySheet = null;
            myRange = null;
            myExcel = null;
            GC.Collect();
        }
        //Freeing up resources allocated by Word and Doc etc..
        private void CloseCOMObject(bool quit)
        {
            if (quit)
            {
                WrdDocObj.Close(true, null, null);
                WrdAppObj.Quit();
            }

            releaseObject(WrdDocObj); WrdDocObj = null;
            releaseObject(WrdAppObj); WrdAppObj = null;
        }
Example #22
0
        // 通过模板创建新文档
        public void CreateNewDocument()
        {
            killWinWordProcess();
            wordApp = new ApplicationClass();
            wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
            wordApp.Visible       = false;
            object missing = System.Reflection.Missing.Value;

            wordDoc = wordApp.Documents.Add(
                ref missing, ref missing, ref missing, ref missing);
        }
Example #23
0
 public void openExcel(string path)
 {
     myExcel = new Microsoft.Office.Interop.Excel.Application();
     myExcel.Workbooks.Open(path);
     myExcel.DisplayAlerts = false;
     myExcel.Visible       = false;
     myBook = myExcel.Workbooks[1];
     myBook.Activate();
     mySheet = (_Worksheet)myBook.Worksheets[1];
     mySheet.Activate();
 }
Example #24
0
 internal override void Dispose(bool disposing)
 {
     if (ExcelBaseObject.ReleaseComObjectOnDispose && GetInteropVersion() != null)
     {
         ReleaseComObject(GetInteropVersion());
     }
     if (disposing && _excel != null)
     {
         _excel = null;
     }
 }
Example #25
0
        public MainController(AddinModule addinModule)
        {
            this.addinModule    = addinModule;
            wordApp             = addinModule.WordApp;
            documentControllers = new Dictionary <_Document, DocumentController>();
            styles = StyleHelper.GetStylesInfo();

            addinModule.UpdateRibbonStyles(styles);

            EnsureDocearFoldersExists();
        }
Example #26
0
        private void Dispose()
        {
            object saveChange     = 0;
            object originalFormat = Missing.Value;
            object routeDocument  = Missing.Value;

            appWord.Quit(ref saveChange, ref originalFormat, ref routeDocument);
            doc     = null;
            appWord = null;
            GC.Collect();
        }
Example #27
0
        public MainController(AddinModule addinModule)
        {
            this.addinModule = addinModule;
            wordApp = addinModule.WordApp;
            documentControllers = new Dictionary<_Document, DocumentController>();
            styles = StyleHelper.GetStylesInfo();

            addinModule.UpdateRibbonStyles(styles);

            EnsureDocearFoldersExists();
        }
Example #28
0
        public void Test_CIFS_AdminShare_URLEncoded()
        {
            string basename = cwd.Substring(3);

            String[] args = { $"{PREFIX}\\\\localhost\\c$\\{basename}\\test%20Book.xlsx#TARGET" };
            Program.Main(args);
            _Application excel = Program.GetExcel();

            AssertAddress("Sheet2", "$G$6:$I$7");
            excel.ActiveWorkbook.Close();
        }
Example #29
0
        public void Test_CWD_WrongName()
        {
            StartCaptureMessage(UrlHandler.Program.TITLE);
            String[] args = { $"{PREFIX}{cwd}\\invalid Book.xlsx#TARGET" };
            Program.Main(args);
            _Application excel = Program.GetExcel();

            Assert.IsTrue(StopCaptureMessage().StartsWith(
                              $"申し訳ございません。{cwd}\\invalid Book.xlsxが見つかりません。名前が変更されたか、移動や削除が行われた可能性があります。"));
            // excel.ActiveWorkbook.Close();
        }
Example #30
0
        public void Test_CIFS_Name_URLEncoded()
        {
            StartCIFS();
            String[] args = { $"{PREFIX}\\\\localhost\\testShare\\test%20Book.xlsx#TARGET" };
            Program.Main(args);
            _Application excel = Program.GetExcel();

            AssertAddress("Sheet2", "$G$6:$I$7");
            excel.ActiveWorkbook.Close();
            StopCIFS();
        }
        /// <summary>
        /// This constructor creates the new excel instance and calls the print method that handles the actual printing.
        /// </summary>
        /// <param name="masterList"> The master list of sales. </param>
        public Printer(List <Data> masterList)
        {
            excel           = new _Excel.Application();
            excel.Visible   = true;
            wbs             = excel.Workbooks;
            wb              = wbs.Add();
            this.ws         = wb.Worksheets[sheet];
            this.masterList = masterList;

            print();
        }
Example #32
0
 /// <summary>
 /// 初始化当前应用程序(为应用程序的前期数据做准备)
 /// </summary>
 public static void Init()
 {
     APP.GoldSoftClient = new GoldSoftClient();
     APP.Application    = new _Application();
     //为应用的准备工作流(无论何时当一个新业务开始的时候必须初始化)
     APP.WorkFlows               = new _WorkFlows();
     APP.UserPriceLibrary        = new _UserPriceLibrary();
     APP.RepairQuantityUnit      = new _RepairQuantityUnit();
     APP.InformationPriceLibrary = new _InformationPriceLibrary();
     APP.UnInformation           = new _UnInformation();
     APP.MachineNumber           = ToolKit.GetIndentify();
 }
Example #33
0
        private int fitnessUpdate = 0;                                  // Variable for number of fitness save


        // Class constructor using the excelfile path to call excel
        // application and read / write excel file
        public ExcelFile(string path)
        {
            this.path = path;                                           // Initialize workbook path
            try                                                         // try to open an excel application
            {
                excel = new Microsoft.Office.Interop.Excel.Application();
            }
            catch (Exception e)
            {
                MyConsole.displayError(e.ToString());
            }
        }
Example #34
0
        public ExcelReader(string readFilePath, int sheet, int startingRow, char separatorCh)
        {
            Guard.WhenArgument(readFilePath, "readFilePath").IsNullOrWhiteSpace().Throw();
            Guard.WhenArgument(sheet, "sheet").IsLessThan(1).Throw();
            Guard.WhenArgument(startingRow, "startingRow").IsLessThan(1).Throw();

            this.excel         = new _Excel.Application();
            this.wb            = excel.Workbooks.Open(readFilePath);
            this.ws            = (Worksheet)wb.Worksheets[sheet];
            this.startingRow   = startingRow;
            this.separatorChar = separatorCh;
        }
Example #35
0
        //打开文件
        public void OpenDocFile(string docName)
        {
            wordApp = new ApplicationClass();
            wordApp.Visible = false; //所打开的WORD程序,是否是可见的。

            object docObject = docName;  //由于COM操作中,都是使用的 object ,所以,需要做一些转变                       
            if (File.Exists(docName))   // 如果要打开的文件名存在,那就使用doc来打开 
            {
                wordDoc = wordApp.Documents.Add(ref docObject, ref missing, ref missing, ref missing);
                wordDoc.Activate();   //将当前文件设定为活动文档
            }
        }
Example #36
0
        public void DeleteAppointments()
        {
            _Application app          = null;
            _NameSpace   session      = null;
            MAPIFolder   folder       = null;
            Items        contactItems = null;

            app          = new Application();
            session      = app.Session;
            folder       = session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
            contactItems = folder.Items;

            var noItemsLeft = false;

            try
            {
                while (noItemsLeft == false)
                {
                    //++++++++++++Begin Edit Area+++++++++++++++
                    var n = 0;

                    foreach (object item in contactItems)
                    {
                        if (item != null)
                        {
                            var getType = GetOutlookTypeForComObject(item);
                            if (getType != null && getType.Name == "AppointmentItem")
                            {
                                if ((item as AppointmentItem).Location == "Engage")
                                {
                                    n++;
                                    (item as AppointmentItem).Delete();
                                }
                            }
                        }
                    }

                    if (n == 0)
                    {
                        noItemsLeft = true;
                    }
                    //++++++++++++End Edit Area+++++++++++++++
                }
            }
            catch (System.Exception ex)
            {
                if (ex.Message != "The message you specified cannot be found.") // Required because of the MSTO not deleting items completely bug.
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private static void addBookmarkToEveryPage(_Application wdApp, _Document doc)
        {
            object unitWdStory = WdUnits.wdStory;
            object oFalse = false;
            object pageBkm = "\\Page";
            object gotoWdGoToPage = WdGoToItem.wdGoToPage;
            object gotoWdGoToNext = WdGoToDirection.wdGoToNext;
            object gotoCount1 = 1;
            object oCollapseStart = WdCollapseDirection.wdCollapseStart;
            object missing = System.Reflection.Missing.Value;

            Selection sel = wdApp.Selection;
            sel.HomeKey(ref unitWdStory, ref oFalse); //Start of doc
            //Assign entire page to range
            Range rngPage = sel.Bookmarks.get_Item(ref pageBkm).Range;
            //We need a second, independent object so that we can later
            //compare the two objects
            Range rngBkm = rngPage.Duplicate;
            //Collapse the second object to a point
            //(will be bookmark location, at top of page)
            rngBkm.Collapse(ref oCollapseStart);
            int counter = 0;
            int lNumPages = (int)sel.get_Information(WdInformation.wdNumberOfPagesInDocument);
            string pageNr = null;

            //Execute at least once,
            //then as long as the last bookmark isn't on the page with the cursor
            // (when can't go to next page, not error occurs, selection stays on last page)
            while (counter == 0 || !rngBkm.InRange(rngPage))
            {
                counter++;
                rngPage.Collapse(ref oCollapseStart);
                //Extra security against an infinite loop
                if (counter > lNumPages) break;
                //Determine the page number
                pageNr = sel.get_Information(WdInformation.wdActiveEndPageNumber).ToString();
                rngBkm = rngPage.Duplicate;
                object oRngBkm = rngBkm;
                //Add a bookmark
                rngPage.Bookmarks.Add("bkmPage" + pageNr, ref oRngBkm);
                //Go to the next page
                sel.GoTo(ref gotoWdGoToPage, ref gotoWdGoToNext, ref gotoCount1, ref missing);
                //Get the full page, for the comparison at the top of the loop
                rngPage = sel.Bookmarks.get_Item(ref pageBkm).Range;
            }
        }
Example #38
0
        private static string FillAnketa(_Application app, object templateFileName, Person anketa, string resultPath)
        {
            _Document doc = null;
            var newFileName = resultPath;
            if (!newFileName.EndsWith("\\"))
                newFileName += "\\";
            newFileName += anketa.Surname+" "+anketa.Name;
            try
            {
                doc = app.Documents.Add(ref templateFileName, ref _missingObj, ref _missingObj, ref _missingObj);
                var fieldInfos = anketa.GetType().GetFields();

                foreach (var info in fieldInfos)
                {
                    var custAttibs = info.GetCustomAttributes(true);
                    foreach (var oAttr in custAttibs)
                    {
                        if (oAttr is StringAttribute)
                        {
                            FillField(doc, info, oAttr as StringAttribute, anketa);
                        }
                        else if (oAttr is EnumAttribute)
                        {
                            CheckSomeBoxes(doc, info, oAttr as EnumAttribute, anketa);
                        }
                        else if (oAttr is BoolAttribute)
                        {
                            CheckSomeBoxesFromBool(doc, info, oAttr as BoolAttribute, anketa);
                        }
                    }
                }
                object newFn = newFileName;
                doc.SaveAs(ref newFn, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj);
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Ошибка '{0}' при заполнении анкеты '{1}' для '{2} {3}'", e.Message + e.StackTrace, templateFileName, anketa.Surname, anketa.Name));
            }
            finally
            {
                if (doc != null) doc.Close(ref _falseObj);
            }
            return newFileName;
        }
Example #39
0
 //通过模板创建新文档
 public void CreateNewDocument(string filePath)
 {
     killWinWordProcess();
     wordApp = new Application();
     wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
     wordApp.Visible = true;
     object templateName = filePath;
     for (int i = 1; i <= wordApp.Documents.Count; i++)
     {
         String str = wordApp.Documents[i].FullName.ToString();
         if (str == wordApp.ToString())
         {
             return;
         }
     }
     wordDoc = wordApp.Documents.Open(ref templateName, ref missing,
       ref missing, ref missing, ref missing, ref missing, ref missing,
       ref missing, ref missing, ref missing, ref missing, ref missing,
       ref missing, ref missing, ref missing, ref missing);
 }
Example #40
0
 public bool InitKompas(out string result)
 {
     result = string.Empty;
     try
     {    	
         var t = Type.GetTypeFromProgID("KOMPAS.Application.5");
         _kompasObj = (KompasObject)Activator.CreateInstance(t);               
         _kompasApp = (_Application)_kompasObj.ksGetApplication7();                
         if (_kompasApp == null)
             return false;
     }
     catch
     {
         result = "Error: Компас не установлен";
         AddLog(result);
         return false;
     }
     result = string.Empty;
     return true;
 }
Example #41
0
		/// <summary>
		/// Connect to the local VI application,  the 'LabView' reference will detremine 
		/// what version and LabView application will be the target
		/// </summary>
		public LabViewInterface()
        {
            try
            {
#if LabVIEW_86
                lvVersion = "LabVIEW 8.6";
#endif
#if LabVIEW_82
                lvVersion = "LabVIEW 8.2.1";
#endif
                viServer = new ApplicationClass();
                appDir = viServer.ApplicationDirectory;
                viServer.AutomaticClose = false;
            }
            catch (Exception e)
            {

                Exception ex = new Exception("ERROR: Creating ApplicationClass " + lvVersion +": ", e);
                throw ex;
            }
		}
Example #42
0
 //通过模板创建新文档
 public void CreateNewDocument(string filePath)
 {
     try
     {
         KillWinWordProcess();
         _wordApp = new ApplicationClass
         {
             DisplayAlerts = WdAlertLevel.wdAlertsNone,
             Visible = false
         };
         object missing = System.Reflection.Missing.Value;
         object templateName = filePath;
         _wordDoc = _wordApp.Documents.Open(ref templateName, ref missing,
             ref missing, ref missing, ref missing, ref missing, ref missing,
             ref missing, ref missing, ref missing, ref missing, ref missing,
             ref missing, ref missing, ref missing, ref missing);
     }
     catch (Exception e)
     {
         Log.Debug("CreateNewDocument出错原因:" + e.Message);
     }
 }
Example #43
0
 public void NewWordDoc()
 {
     try
     {
         this._wordApp = new ApplicationClass();
         Object myNull = System.Reflection.Missing.Value;
         this._wordDoc = this._wordApp.Documents.Add(ref myNull, ref myNull, ref myNull, ref myNull);
     }
     catch (Exception e)
     {
         Logger.WriteLog("Create Word: " + e.Message);
     }
 }
        private void Quit(bool forceQuit)
        {
            base.Quit();

            lock (m_lock)
            {
                if (null == m_hostApplication)
                {
                    return;
                }

                ApplicationControllerTrace trace = new ApplicationControllerTrace();

                try
                {
                    if (m_hostApplication.Visible && !forceQuit)
                        return;

                    DisableMacros(true);
                    MarkTemplatesAsSaved();

                    object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
                    object originalFormat = null;
                    object routeDocument = false;

                    m_hostApplication.Options.ConfirmConversions = _confirmConversion;
                    m_hostApplication.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
                }
                catch (COMException e)
                {
                    trace.Log(e);

                    if (RPC_E_DISCONNECTED != e.ErrorCode)
                        throw e;
                }
                finally
                {
                    if (null != m_hostApplication)
                        Marshal.FinalReleaseComObject(m_hostApplication);

                    m_hostApplication = null;
                }
            }
        }
        private void initialize(bool restartOultlook = false)
        {
            if (restartOultlook)
                restartOutlookInstance();

            try
            {
                _outlookApplication = new Application();
            }
            catch (COMException e)
            {
                const string messsage =
                    @"HRESULT: 0x80080005";

                if (!e.Message.Contains(messsage))
                    throw;

                MessageBoxResult result =
                    MessageBox.Show(
                        LanguageDictionary.CurrentDictionary.Translate<string>("Messages.OutlookProblem", "Message"),
                        LanguageDictionary.CurrentDictionary.Translate<string>("Messages.OutlookProblem", "Title"),
                        MessageBoxButton.YesNo, MessageBoxImage.Warning);

                if (result == MessageBoxResult.No) return;
                initialize(true);
            }
        }
        private static int GetApplicationProcessId(_Application excelApp)
        {
            int excelPid = -1;
            //
            // Get the Excel instance's process ID...used later
            // to prevent orphaned Excel processes.
            //
            Process[] aProcesses = Process.GetProcesses();
            for (int i = 0; i <= aProcesses.GetUpperBound(0); i++)
            {
                if (aProcesses[i].MainWindowHandle.ToString() == excelApp.Hwnd.ToString(CultureInfo.InvariantCulture))
                {
                    excelPid = aProcesses[i].Id;
                    break;
                }
            }

            return excelPid;
        }
Example #47
0
        /// <summary>
        /// 转为PDF
        /// </summary>
        /// <param name="dstDir"></param>
        /// <param name="docFileName"></param>
        /// <returns></returns>
        public Boolean ConvertToPDF(String dstDir, String docFileName)
        {
            string wjm = Path.GetFileNameWithoutExtension(docFileName);
            string path = FormatPath(wjm);

            //该目录存在
            dstDir += path;

            string pdfFile = dstDir + wjm + ".pdf";
            string docFile = dstDir + docFileName;

            WdExportFormat exportFormat = WdExportFormat.wdExportFormatPDF;
            bool result;
            object paramMissing = Type.Missing;
            //ApplicationClass wordApplication = new ApplicationClass();
            this._wordApp = new ApplicationClass();

            try
            {
                object paramSourceDocPath = docFile;
                string paramExportFilePath = pdfFile;

                WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;

                _wordDoc = _wordApp.Documents.Open(
                        ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing);

                if (_wordDoc != null)
                    _wordDoc.ExportAsFixedFormat(paramExportFilePath,
                            paramExportFormat, paramOpenAfterExport,
                            paramExportOptimizeFor, paramExportRange, paramStartPage,
                            paramEndPage, paramExportItem, paramIncludeDocProps,
                            paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                            paramBitmapMissingFonts, paramUseISO19005_1,
                            ref paramMissing);
                result = true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                _wordDoc.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                _wordApp.Quit(ref paramMissing, ref paramMissing, ref paramMissing);

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
		/// <summary>
		/// Connect to the local VI application,  the 'LabView' reference will detremine 
		/// what version and LabView application will be the target
		/// </summary>
		public LabViewInterface()
		{	
			viServer = new ApplicationClass();
            appDir = viServer.ApplicationDirectory;
			viServer.AutomaticClose = false;
		}
Example #49
0
 public DocToPdf()
 {
     _wordApp = new ApplicationClass();
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="outlookApplication"></param>
 public OutlookViewProvider(_Application outlookApplication)
 {
     explorers = outlookApplication.Explorers;
     inspectors = outlookApplication.Inspectors;
 }
Example #51
0
        private static Table PutDayScheduleInWord(ScheduleRepository repo, int lessonLength, bool weeksMarksVisible,
            Dictionary<int, Dictionary<string, Dictionary<int, Tuple<string, List<Tuple<Lesson, int>>, string>>>> schedule, _Document oDoc, object oEndOfDoc, _Application oWord, Table table, int dayOfWeek)
        {
            var timeList = new List<string>();
            foreach (var group in schedule)
            {
                foreach (var time in @group.Value.Keys)
                {
                    if (!timeList.Contains(time))
                    {
                        timeList.Add(time);
                    }
                }
            }

            Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            Table oTable;

            var plainGroupsListIds = new Dictionary<int, List<int>>();
            var nGroupsListIds = new Dictionary<int, List<int>>();
            var plainNGroupIds = new Dictionary<int, Tuple<int, int>>();

            int tableRowOffset = 0;

            if (table != null)
            {
                oTable = table;
                tableRowOffset = oTable.Rows.Count;

                for (int i = 0; i < 1 + timeList.Count; i++)
                {
                    oTable.Rows.Add();
                }
            }
            else
            {

                oTable = oDoc.Tables.Add(wrdRng, 1 + timeList.Count, 1 + schedule.Count);
                oTable.Borders.Enable = 1;
                oTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
                oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                oTable.Range.Font.Size = 10;
                oTable.Range.Font.Bold = 0;

                oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f);
                float colWidth = 25.64F / schedule.Count;
                for (int i = 0; i < schedule.Count; i++)
                {
                    oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth);
                }
            }

            oTable.Cell(tableRowOffset + 1, 1).Range.Text = Constants.DowLocal[dayOfWeek];
            oTable.Cell(tableRowOffset + 1, 1).Range.ParagraphFormat.Alignment =
                WdParagraphAlignment.wdAlignParagraphCenter;

            int groupColumn = 2;

            foreach (var group in schedule)
            {
                var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                var groupName = groupObject.Name;

                oTable.Cell(tableRowOffset + 1, groupColumn).Range.Text = groupName.Replace(" (+Н)", "");
                oTable.Cell(tableRowOffset + 1, groupColumn).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                groupColumn++;

                if (groupName.Contains(" (+Н)"))
                {
                    var plainGroupName = groupName.Replace(" (+Н)", "");
                    var nGroupName = groupName.Replace(" (+", "(");

                    var plainGroupId = repo.StudentGroups.FindStudentGroup(plainGroupName).StudentGroupId;
                    var plainStudentIds = repo.StudentsInGroups.GetAllStudentsInGroups()
                        .Where(sig => sig.StudentGroup.StudentGroupId == plainGroupId)
                        .Select(stig => stig.Student.StudentId)
                        .ToList();
                    plainGroupsListIds.Add(@group.Key, repo.StudentsInGroups.GetAllStudentsInGroups()
                        .Where(sig => plainStudentIds.Contains(sig.Student.StudentId))
                        .Select(stig => stig.StudentGroup.StudentGroupId)
                        .Distinct()
                        .ToList());

                    var nGroupId = repo.StudentGroups.FindStudentGroup(nGroupName).StudentGroupId;
                    var nStudentIds = repo.StudentsInGroups.GetAllStudentsInGroups()
                        .Where(sig => sig.StudentGroup.StudentGroupId == nGroupId)
                        .Select(stig => stig.Student.StudentId)
                        .ToList();
                    nGroupsListIds.Add(@group.Key, repo.StudentsInGroups.GetAllStudentsInGroups()
                        .Where(sig => nStudentIds.Contains(sig.Student.StudentId))
                        .Select(stig => stig.StudentGroup.StudentGroupId)
                        .Distinct()
                        .ToList());

                    plainNGroupIds.Add(groupObject.StudentGroupId, new Tuple<int, int>(plainGroupId, nGroupId));
                }
            }

            var timeRowIndexList = new List<int>();

            var timeRowIndex = 2;
            foreach (var time in timeList.OrderBy(t => int.Parse(t.Split(':')[0]) * 60 + int.Parse(t.Split(':')[1])))
            {
                var hour = int.Parse(time.Substring(0, 2));
                var minute = int.Parse(time.Substring(3, 2));

                minute += lessonLength;

                while (minute >= 60)
                {
                    hour++;
                    minute -= 60;
                }

                timeRowIndexList.Add(timeRowIndex);
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.Text = time + " - " +
                                                          hour.ToString("D2") + ":" + minute.ToString("D2");
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Cell(tableRowOffset + timeRowIndex, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                var columnGroupIndex = 2;
                foreach (var group in schedule)
                {
                    if (@group.Value.ContainsKey(time))
                    {
                        oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex).VerticalAlignment =
                            WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                        var timeTable = oDoc.Tables.Add(oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex).Range, 1, 1);
                        for (int i = 0; i < @group.Value[time].Count - 1; i++)
                        {
                            timeTable.Rows.Add();
                        }
                        for (int i = 0; i < @group.Value[time].Count - 1; i++)
                        {
                            timeTable.Cell(i + 1, 1).Borders[WdBorderType.wdBorderBottom].Visible = true;
                        }
                        timeTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
                        timeTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                        timeTable.Range.Font.Size = 10;
                        timeTable.Range.Font.Bold = 0;

                        var tfdIndex = 0;
                        foreach (
                            var tfdData in
                                @group.Value[time].OrderBy(
                                    tfd => tfd.Value.Item2.Select(l => repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date)).Min()))
                        {
                            var cellText = "";
                            // Discipline name
                            cellText += tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.Name;

                            // N + Group modifiers
                            var groupId = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId;
                            if (plainGroupsListIds.ContainsKey(@group.Key))
                            {
                                if (plainGroupsListIds[@group.Key].Contains(groupId) &&
                                    nGroupsListIds[@group.Key].Contains(groupId))
                                {
                                    cellText += " (+Н)";
                                }
                                if (!plainGroupsListIds[@group.Key].Contains(groupId) &&
                                    nGroupsListIds[@group.Key].Contains(groupId))
                                {
                                    cellText += " (Н)";
                                }
                            }

                            var tfdGroupId = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId;
                            if ((tfdGroupId != @group.Key))
                            {
                                if ((!plainNGroupIds.ContainsKey(@group.Key)) ||
                                    ((tfdGroupId != plainNGroupIds[@group.Key].Item1) &&
                                     (tfdGroupId != plainNGroupIds[@group.Key].Item2)))
                                {
                                    cellText += " (" + tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.Name +
                                                ")";
                                }
                            }

                            cellText += Environment.NewLine;
                            // Teacher FIO
                            cellText += tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Teacher.FIO + Environment.NewLine;

                            // Total weeks
                            if (weeksMarksVisible)
                            {
                                cellText += "(" + tfdData.Value.Item1 + ")" + Environment.NewLine;
                            }

                            var audWeekList = tfdData.Value.Item2.ToDictionary(l => repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date),
                                l => l.Item1.Auditorium.Name);
                            var grouped = audWeekList.GroupBy(a => a.Value);

                            var enumerable = grouped as List<IGrouping<string, KeyValuePair<int, string>>> ?? grouped.ToList();
                            var gcount = enumerable.Count();
                            if (gcount == 1)
                            {
                                cellText += enumerable.ElementAt(0).Key;
                            }
                            else
                            {
                                for (int j = 0; j < gcount; j++)
                                {
                                    var jItem = enumerable.OrderBy(e => e.Select(ag => ag.Key).ToList().Min()).ElementAt(j);
                                    cellText += CommonFunctions.CombineWeeks(jItem.Select(ag => ag.Key).ToList()) + " - " +
                                                jItem.Key;

                                    if (j != gcount - 1)
                                    {
                                        cellText += Environment.NewLine;
                                    }
                                }
                            }

                            timeTable.Cell(tfdIndex + 1, 1).Range.Text = cellText;
                            timeTable.Cell(tfdIndex + 1, 1).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            tfdIndex++;
                        }
                    }

                    columnGroupIndex++;
                }

                timeRowIndex++;
            }
            return oTable;
        }
Example #52
0
        private static Table GetAndPutDowStartSchedule(ScheduleRepository repo, int lessonLength, int dayOfWeek, bool weekFiltered, int weekFilter, bool weeksMarksVisible, Faculty faculty, _Document oDoc, object oEndOfDoc, _Application oWord, CancellationToken cToken)
        {
            cToken.ThrowIfCancellationRequested();

            var schedule = repo.Lessons.GetFacultyDowSchedule(faculty.FacultyId, dayOfWeek, weekFiltered, weekFilter, false, false);

            cToken.ThrowIfCancellationRequested();

            var timeList = new List<string>();
            foreach (var group in schedule)
            {
                foreach (var time in @group.Value.Keys)
                {
                    if (!timeList.Contains(time))
                    {
                        timeList.Add(time);
                    }
                }
            }

            Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            Table oTable = oDoc.Tables.Add(wrdRng, 1 + timeList.Count, 1 + (schedule.Count * 2));
            oTable.Borders.Enable = 1;
            oTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
            oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
            oTable.Range.Font.Size = 11;
            oTable.Range.Font.Bold = 0;

            oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f);
            float colWidth = 25.64F / schedule.Count;
            for (int i = 0; i < schedule.Count * 2; i += 2)
            {
                oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth - 1.1f);
                oTable.Columns[i + 3].Width = oWord.CentimetersToPoints(1.1f);
            }

            oTable.Range.Font.Underline = WdUnderline.wdUnderlineNone;

            oTable.Cell(1, 1).Range.Text = "Время занятий";//Constants.DOWLocal[dayOfWeek];
            oTable.Cell(1, 1).Range.Font.Bold = 1;
            oTable.Cell(1, 1).Range.ParagraphFormat.Alignment =
                WdParagraphAlignment.wdAlignParagraphCenter;

            int groupColumn = 2;

            foreach (var group in schedule)
            {
                var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                var groupName = groupObject.Name;
                oTable.Cell(1, groupColumn).Range.Text = groupName;
                oTable.Cell(1, groupColumn).Range.Font.Bold = 1;
                oTable.Cell(1, groupColumn).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Cell(1, groupColumn).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                oTable.Cell(1, groupColumn + 1).Range.Text = "Ауд";
                oTable.Cell(1, groupColumn + 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                groupColumn += 2;
            }

            var timeRowIndexList = new List<int>();

            var timeRowIndex = 2;
            foreach (var time in timeList.OrderBy(t => int.Parse(t.Split(':')[0]) * 60 + int.Parse(t.Split(':')[1])))
            {
                cToken.ThrowIfCancellationRequested();

                var hour = int.Parse(time.Substring(0, 2));
                var minute = int.Parse(time.Substring(3, 2));

                minute += lessonLength;

                while (minute >= 60)
                {
                    hour++;
                    minute -= 60;
                }

                timeRowIndexList.Add(timeRowIndex);
                oTable.Cell(timeRowIndex, 1).Range.Text = time + "-" +
                                                          hour.ToString("D2") + ":" + minute.ToString("D2");
                oTable.Cell(timeRowIndex, 1).Range.Font.Bold = 1;
                oTable.Cell(timeRowIndex, 1).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Cell(timeRowIndex, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                var columnGroupIndex = 2;
                foreach (var group in schedule)
                {
                    if (@group.Value.ContainsKey(time))
                    {
                        oTable.Cell(timeRowIndex, columnGroupIndex).VerticalAlignment =
                            WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                        var groupDowTimeLessons = @group.Value[time]
                            .OrderBy(tfd => tfd.Value.Item2.Select(l =>
                                repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date)).Min())
                            .ToList();
                        var tfdIndex = 0;

                        if (groupDowTimeLessons.Count() == 2)
                        {
                            if (groupDowTimeLessons[0].Value.Item1.Contains("(чёт.") &&
                                groupDowTimeLessons[1].Value.Item1.Contains("(нечёт."))
                            {
                                var tmp = groupDowTimeLessons[0];
                                groupDowTimeLessons[0] = groupDowTimeLessons[1];
                                groupDowTimeLessons[1] = tmp;
                            }
                        }

                        if (
                            ((@group.Value[time].Count == 2) &&
                            ((groupDowTimeLessons[0].Value.Item1.Contains("нечёт.")) && (groupDowTimeLessons[1].Value.Item1.Contains("чёт."))))
                            || ((@group.Value[time].Count == 1) && (groupDowTimeLessons[0].Value.Item1.Contains("чёт."))))
                        {
                            var rng = oTable.Cell(timeRowIndex, columnGroupIndex).Range;
                            rng.Borders[WdBorderType.wdBorderDiagonalUp].LineStyle = WdLineStyle.wdLineStyleSingle;
                        }

                        var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                        var subGroupOne = repo.StudentGroups.GetFirstFiltredStudentGroups(sg => sg.Name == groupObject.Name + "1");
                        var subGroupTwo = repo.StudentGroups.GetFirstFiltredStudentGroups(sg => sg.Name == groupObject.Name + "2");

                        if (groupDowTimeLessons.Count() == 2)
                        {
                            if (((subGroupOne != null) && (subGroupTwo != null)) &&
                                ((groupDowTimeLessons[0].Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId == subGroupTwo.StudentGroupId) &&
                                 (groupDowTimeLessons[1].Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId == subGroupOne.StudentGroupId)))
                            {
                                var tmp = groupDowTimeLessons[0];
                                groupDowTimeLessons[0] = groupDowTimeLessons[1];
                                groupDowTimeLessons[1] = tmp;
                            }
                        }

                        var addSubGroupColumn = 0;

                        if ((groupDowTimeLessons.Count() == 1) &&
                            (subGroupOne != null) &&
                            (groupDowTimeLessons[0].Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId == subGroupOne.StudentGroupId))
                        {
                            addSubGroupColumn = 1;

                            var emptytfd = new KeyValuePair<int, Tuple<string, List<Tuple<Lesson, int>>, string>>(-1, null);
                            groupDowTimeLessons.Add(emptytfd);
                        }

                        if ((groupDowTimeLessons.Count() == 1) &&
                            (subGroupTwo != null) &&
                            (groupDowTimeLessons[0].Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId == subGroupTwo.StudentGroupId))
                        {
                            addSubGroupColumn = 1;

                            var emptytfd = new KeyValuePair<int, Tuple<string, List<Tuple<Lesson, int>>, string>>(-1, null);
                            groupDowTimeLessons.Add(emptytfd);

                            var tmp = groupDowTimeLessons[0];
                            groupDowTimeLessons[0] = groupDowTimeLessons[1];
                            groupDowTimeLessons[1] = tmp;
                        }

                        var timeTable = oDoc.Tables.Add(oTable.Cell(timeRowIndex, columnGroupIndex).Range, 1, @group.Value[time].Count + addSubGroupColumn);

                        if (!((groupDowTimeLessons.Count == 2) &&
                            (((groupDowTimeLessons[0].Value != null) && (groupDowTimeLessons[1].Value != null)) &&
                             ((groupDowTimeLessons[0].Value.Item1.Contains("нечёт.")) && (groupDowTimeLessons[1].Value.Item1.Contains("чёт."))))))
                        {
                            for (int i = 0; i < groupDowTimeLessons.Count - 1; i++)
                            {
                                timeTable.Cell(1, i + 1).Borders[WdBorderType.wdBorderRight].Visible = true;
                            }
                        }

                        timeTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
                        timeTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                        timeTable.Range.Font.Size = 10;
                        timeTable.Range.Font.Bold = 0;

                        foreach (var tfdData in groupDowTimeLessons)
                        {
                            var cellText = "";

                            if (tfdData.Value == null)
                            {
                                tfdIndex++;

                                continue;
                            }

                            var discName = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.Name;

                            var shorteningDictionary = new Dictionary<string, string>
                            {
                                {"Английский язык", "Англ. яз."},
                                {"Немецкий язык", "Нем. яз."},
                                {"Французский язык", "Франц. яз."}
                            };

                            if (shorteningDictionary.ContainsKey(discName))
                            {
                                discName = shorteningDictionary[discName];
                            }

                            // Discipline name
                            cellText += discName + Environment.NewLine;

                            // Teacher FIO
                            var ommitInitials = @group.Value[time].Count != 1;
                            String teacherFio = ShortenFio(tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Teacher.FIO, ommitInitials);
                            cellText += teacherFio;

                            // Total weeks
                            if (weeksMarksVisible)
                            {
                                /*
                                if (tfdData.Value.Item1.Contains("(чёт."))
                                {
                                    cellText += "(чёт.)" + Environment.NewLine;
                                }
                                if (tfdData.Value.Item1.Contains("(нечёт."))
                                {
                                    cellText += "(нечёт.)" + Environment.NewLine;
                                }
                                */
                                //cellText += "(" + tfdData.Value.Item1 + ")" + Environment.NewLine;
                            }

                            String audText = "";
                            // Auditoriums
                            var audWeekList = tfdData.Value.Item2.ToDictionary(l => repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date),
                                l => l.Item1.Auditorium.Name);
                            var grouped = audWeekList.GroupBy(a => a.Value);

                            var enumerable = grouped as List<IGrouping<string, KeyValuePair<int, string>>> ?? grouped.ToList();
                            var gcount = enumerable.Count();
                            if (gcount == 1)
                            {
                                audText += ShortenAudName(enumerable.ElementAt(0).Key);
                            }
                            else
                            {
                                for (int j = 0; j < gcount; j++)
                                {
                                    var jItem = enumerable.OrderBy(e => e.Select(ag => ag.Key).ToList().Min()).ElementAt(j);
                                    audText += CommonFunctions.CombineWeeks(jItem.Select(ag => ag.Key).ToList()) + " - " +
                                               ShortenAudName(jItem.Key);

                                    if (j != gcount - 1)
                                    {
                                        audText += Environment.NewLine;
                                    }
                                }
                            }

                            if ((groupDowTimeLessons.Count == 1) &&
                                (groupDowTimeLessons[0].Value.Item1.Contains("(чёт.")))
                            {
                                cellText = Environment.NewLine + cellText;
                            }

                            if ((groupDowTimeLessons.Count == 1) &&
                                (groupDowTimeLessons[0].Value.Item1.Contains("(нечёт.")))
                            {
                                cellText = cellText + Environment.NewLine;
                            }
                            //Auditoriums

                            timeTable.Cell(1, tfdIndex + 1).Range.Text = cellText;
                            timeTable.Cell(1, tfdIndex + 1).Range.ParagraphFormat.Alignment =
                                WdParagraphAlignment.wdAlignParagraphCenter;

                            /*
                             * FIO in one line
                            var lineSpacing = timeTable.Cell(1, tfdIndex + 1).Range.ParagraphFormat.LineSpacing;

                            var Height = timeTable.Cell(1, tfdIndex + 1).Height;

                            if (Height > lineSpacing * 2)
                            {

                            }
                             */

                            timeTable.Cell(1, tfdIndex + 1).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            var audCellText = oTable.Cell(timeRowIndex, columnGroupIndex + 1).Range.Text;
                            if (audCellText == "\r\a")
                            {
                                oTable.Cell(timeRowIndex, columnGroupIndex + 1).Range.Text = audText;
                            }
                            else
                            {
                                oTable.Cell(timeRowIndex, columnGroupIndex + 1).Range.Text = audCellText + "/ " + audText;
                            }

                            oTable.Cell(timeRowIndex, columnGroupIndex + 1).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            if ((@group.Value[time].Count == 2) &&
                                ((groupDowTimeLessons[0].Value.Item1.Contains("нечёт.")) && (groupDowTimeLessons[1].Value.Item1.Contains("чёт."))))
                            {
                                timeTable.Cell(1, tfdIndex + 1).Range.ParagraphFormat.Alignment =
                                    (tfdIndex == 0)
                                        ? WdParagraphAlignment.wdAlignParagraphLeft
                                        : WdParagraphAlignment.wdAlignParagraphRight;
                            }

                            if ((groupDowTimeLessons.Count == 1) &&
                                (groupDowTimeLessons[0].Value.Item1.Contains("(чёт.")))
                            {
                                timeTable.Cell(1, tfdIndex + 1).Range.ParagraphFormat.Alignment =
                                    WdParagraphAlignment.wdAlignParagraphRight;
                            }

                            tfdIndex++;
                        }
                    }

                    columnGroupIndex += 2;
                }

                timeRowIndex++;
            }

            return oTable;
        }
Example #53
0
        private static Table GetAndPutDowSchedule(ScheduleRepository repo, int lessonLength, int dayOfWeek, bool weekFiltered, int weekFilter, bool weeksMarksVisible, Faculty faculty, _Document oDoc, object oEndOfDoc, _Application oWord, Table tableToContinue, CancellationToken cToken)
        {
            cToken.ThrowIfCancellationRequested();

            var schedule = repo.Lessons.GetFacultyDowSchedule(faculty.FacultyId, dayOfWeek, weekFiltered, weekFilter, false, false);

            cToken.ThrowIfCancellationRequested();

            var timeList = new List<string>();
            foreach (var group in schedule)
            {
                foreach (var time in @group.Value.Keys)
                {
                    if (!timeList.Contains(time))
                    {
                        timeList.Add(time);
                    }
                }
            }

            Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            Table oTable;
            var tableRowOffset = 0;

            if (tableToContinue == null)
            {
                oTable = oDoc.Tables.Add(wrdRng, 1 + timeList.Count, 1 + schedule.Count);
                oTable.Borders.Enable = 1;
                oTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
                oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                oTable.Range.Font.Size = 10;
                oTable.Range.Font.Bold = 0;

                oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f);
                float colWidth = 25.64F / schedule.Count;
                for (int i = 0; i < schedule.Count; i++)
                {
                    oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth);
                }
            }
            else
            {
                oTable = tableToContinue;
                tableRowOffset = oTable.Rows.Count;

                for (int i = 0; i < 1 + timeList.Count; i++)
                {
                    oTable.Rows.Add();

                    for (int j = 1; j <= 1 + schedule.Count; j++)
                    {
                        oTable.Cell(tableRowOffset + i + 1, j).Borders[WdBorderType.wdBorderDiagonalUp].Visible = false;
                    }
                }
            }

            oTable.Cell(tableRowOffset + 1, 1).Range.Text = Constants.DowLocal[dayOfWeek];
            oTable.Cell(tableRowOffset + 1, 1).Range.Bold = 1;
            oTable.Cell(tableRowOffset + 1, 1).Range.ParagraphFormat.Alignment =
                WdParagraphAlignment.wdAlignParagraphCenter;

            int groupColumn = 2;

            foreach (var group in schedule)
            {
                var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                var groupName = groupObject.Name;
                oTable.Cell(tableRowOffset + 1, groupColumn).Range.Text = groupName;
                oTable.Cell(tableRowOffset + 1, groupColumn).Range.Bold = 1;
                oTable.Cell(tableRowOffset + 1, groupColumn).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                groupColumn++;
            }

            var timeRowIndexList = new List<int>();

            var timeRowIndex = 2;
            foreach (var time in timeList.OrderBy(t => int.Parse(t.Split(':')[0]) * 60 + int.Parse(t.Split(':')[1])))
            {

                cToken.ThrowIfCancellationRequested();

                var hour = int.Parse(time.Substring(0, 2));
                var minute = int.Parse(time.Substring(3, 2));

                minute += lessonLength;

                while (minute >= 60)
                {
                    hour++;
                    minute -= 60;
                }

                timeRowIndexList.Add(timeRowIndex);
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.Text = time + " - " +
                                                          hour.ToString("D2") + ":" + minute.ToString("D2");
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.Bold = 1;
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Cell(tableRowOffset + timeRowIndex, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                var columnGroupIndex = 2;
                foreach (var group in schedule)
                {
                    if (@group.Value.ContainsKey(time))
                    {
                        oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex).VerticalAlignment =
                            WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                        var groupDowTimeLessons = @group.Value[time]
                            .OrderBy(tfd => tfd.Value.Item2.Select(l =>
                                repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date)).Min())
                            .ToList();

                        var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                        var subgroupIds = new List<int>();
                        var subGroupOne = repo.StudentGroups.GetFirstFiltredStudentGroups(sg => sg.Name == groupObject.Name + "1");
                        if (subGroupOne != null) subgroupIds.Add(subGroupOne.StudentGroupId);
                        var subGroupTwo = repo.StudentGroups.GetFirstFiltredStudentGroups(sg => sg.Name == groupObject.Name + "2");
                        if (subGroupTwo != null) subgroupIds.Add(subGroupTwo.StudentGroupId);

                        var subgroups = false;

                        var groupIds =
                                groupDowTimeLessons.Select(
                                    l =>
                                        l.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup
                                            .StudentGroupId).ToList();
                        if (groupIds.Intersect(subgroupIds).Count() > 0)
                        {
                            subgroups = true;
                        }

                        Table subgroupsTable = null;
                        Table timeTable = null;

                        List<KeyValuePair<int, Tuple<string, List<Tuple<Lesson, int>>, string>>> group1Items = null;
                        if (subGroupOne != null)
                        {
                            group1Items =
                                groupDowTimeLessons.Where(
                                    l =>
                                        l.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup
                                            .StudentGroupId == subGroupOne.StudentGroupId).ToList();
                        }

                        List<KeyValuePair<int, Tuple<string, List<Tuple<Lesson, int>>, string>>> group2Items = null;
                        if (subGroupTwo != null)
                        {
                            group2Items =
                                groupDowTimeLessons.Where(
                                    l =>
                                        l.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup
                                            .StudentGroupId == subGroupTwo.StudentGroupId).ToList();
                        }

                        if (subgroups)
                        {
                            subgroupsTable =
                                oDoc.Tables.Add(oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex).Range, 1, 2);
                            subgroupsTable.Cell(1, 1).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            subgroupsTable.Cell(1, 2).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            subgroupsTable.Cell(1, 1).Borders[WdBorderType.wdBorderRight].Visible = true;

                            PutDowSchedulePutGroupOrSubGroupDowTimeItem(repo, oDoc, subgroupsTable.Cell(1, 1), group1Items, true);

                            PutDowSchedulePutGroupOrSubGroupDowTimeItem(repo, oDoc, subgroupsTable.Cell(1, 2), group2Items, true);
                        }
                        else
                        {
                            PutDowSchedulePutGroupOrSubGroupDowTimeItem(repo, oDoc, oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex), groupDowTimeLessons, false);
                        }
                    }

                    columnGroupIndex++;
                }

                timeRowIndex++;
            }

            return oTable;
        }
	    private void Dispose(bool disposing)
	    {
	        // For embedded messages there may be circumstances where the msg file is
	        // still being accessed/deleted in other code so use try/catch to ensure
	        // that we don't fail the whole send process.
	        try
	        {
	            foreach (string s in _msgFileBackingCopies)
	            {
	                DeleteFile(s);
	            }
	            _msgFileBackingCopies.Clear();
	        }
    	    catch (Exception ex)
	        {
    	        Interop.Logging.Logger.LogError(ex);
	        }

	        try
	        {
	            foreach (string sFolder in _msgFileCreatedFolders)
	            {
	                Directory.Delete(sFolder);
	            }
	            _msgFileCreatedFolders.Clear();
	        }
	        catch (Exception ex)
	        {
	            Interop.Logging.Logger.LogError(ex);
	        }

	        CleanupTempCopies();

			_localFileManager = null;
			
			if (_mapIutils != null)
			{
				_mapIutils.Cleanup();
				
                if (Marshal.IsComObject(_mapIutils))
                {
                    Marshal.ReleaseComObject(_mapIutils);
                }
				_mapIutils = null;
			}

			if (_outlookApp != null)
			{
                if (Marshal.IsComObject(_outlookApp))
                {
				    Marshal.ReleaseComObject(_outlookApp);
                }
				_outlookApp = null;
			}
		}
Example #55
0
		public virtual string QuitLabView()
		{
			StringBuilder message = new StringBuilder("QuitLabview: ");
			

			if(viServer != null)
			{
				message.Append(" Process=" +viServer._ProcessID);
			
				try
				{
					viServer.Quit();
				}
				catch(Exception e)
				{
					message.Append(" ERROR on Quit(): " + e.Message);
				}
				
				viServer = null;
			}
			return message.ToString();
		}
Example #56
0
 //通过模板创建新文档
 public void CreateNewDocument(string filePath)
 {
     killWinWordProcess();
     wordApp = new ApplicationClass();
     wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
     wordApp.Visible = false;
     object missing = System.Reflection.Missing.Value;
     object templateName = filePath;
     wordDoc = wordApp.Documents.Open(ref templateName, ref missing,
         ref missing, ref missing, ref missing, ref missing, ref missing,
         ref missing, ref missing, ref missing, ref missing, ref missing,
         ref missing, ref missing, ref missing, ref missing);
 }
Example #57
0
        public virtual string submitRemoteCommand(string actionStr, string valueStr,
            _Application appRef, VirtualInstrument viRef)
        {
            /*
             * Initialize the variables and define the strings corresponding to
             * the VI connector labels. Note the strings are case sensitive
             **/
            StringBuilder message = new StringBuilder(actionStr + ": ");
            if (valueStr != null)
                message.Append(" Data=" + valueStr);
            string dataStr = valueStr;
            VirtualInstrument actionVI =  this.getRemoteCommandVI();
            if (actionVI != null)
            {

                string[] connectors = new String[6];
                object[] data = new object[6];

                connectors[0] = "action";
                connectors[1] = "data";
                connectors[2] = "response";
                connectors[3] = "errorOut";
                connectors[4] = "appRef";
                connectors[5] = "viRef";
                

                //The wrapper function expects to be passed a object type by reference.
                //We pass the string array to the object type here
                object param1 = (object)connectors;

                //Define the variable that will pass the expression to be evaluated to 
                //LabVIEW and typecast it to type object


                data[0] = (object)actionStr;
                if (dataStr == null)
                    data[1] = (object)"";
                else
                    data[1] = (object)dataStr;
                
                if (appRef != null)
                {
                    data[4] = appRef;
                }

                if (viRef != null)
                {
                    data[5] = viRef;
                }
                object param2 = (object)data;
                //Call the VI
                actionVI.Call(ref param1, ref param2);
                //Display the result
                //Data returned
                if (((object[])param2)[2] != null)
                    message.Append(" response: " + ((object[])param2)[2].ToString());
                //Error returned
                if (((object[])param2)[3] != null)
                    message.Append(" Error: " + ((object[])param2)[3].ToString());

            }
            else
            {
                message.Append(" ERROR: RemoteCommandMgr not found");
            }
            Utilities.WriteLog(message.ToString());
            return message.ToString();

        }
Example #58
0
        //读取数据
        private void btRead_Click(object sender, EventArgs e)
        {
            int MAXLINE = 5000;
            int i = 0, j = 0, k = 0, m = 0;//m为总行数
            int fileCount = lvFile.Items.Count;
            string DataTag;
            int eCount = 0;//有效工作簿数
            int sCount = 0;//当前表中工作簿数
            Point point;
            Object missing = Type.Missing;

            int iCount = lbContent.Items.Count;
            //重点区域,范围型读取单元格区域
            RangeSelector mainRange = new RangeSelector(tbMainRange.Text);
            //预判断块读取还是固定位置读取,初始化总数组大小
            if (mainRange.getWidth() > 0)
                myArray = new String[MAXLINE, mainRange.getWidth() + iCount + 1];//最多千行
            else
                myArray = new String[MAXLINE, iCount + 1];//最多千行

            //開啟一個新的應用程式
            myExcel = new Excel.Application();
            for (i = 0; i < fileCount; i++)
            {
                //停用警告訊息
                myExcel.DisplayAlerts = false;
                //讓Excel文件可見
                myExcel.Visible = true;
                //引用第一個活頁簿
                myBook = myExcel.Workbooks.Open(lvFile.Items[i].SubItems[2].Text, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                //設定活頁簿焦點
                myBook.Activate();
                //判断所有工作簿
                sCount = myBook.Worksheets.Count;
                for (k = 1; k <= sCount; k++)
                {
                    //大表判断条件
                    if (cbSheetSelect.Text != "全部" && Int16.Parse(cbSheetSelect.Text) != k) continue;
                    //选择当前表
                    mySheet = (Worksheet)myBook.Worksheets[k];
                    //設工作表焦點
                    mySheet.Activate();
                    //特征值判断
                    if (tbSheetPos.Text != "")
                    {
                        point = pointPos(tbSheetPos.Text);
                        if (mySheet.Cells[point.Y, point.X].Value != tbSheetCont.Text) continue;
                    }
                    eCount++;
                    //备注列判断
                    if (tbDataTag.Text == "") DataTag = lvFile.Items[i].SubItems[0].Text;    //未设置备注默认使用文件名
                    else
                    {
                        Point tagpos = pointPos(tbDataTag.Text);
                        DataTag = Convert.ToString(mySheet.Cells[tagpos.Y, tagpos.X].Value);
                    }
                    string mainStart = tbMainStart.Text;
                    string mainEnd = tbMainEnd.Text;
                    //判断选择哪种模式
                    if (mainRange.Count() > 1)
                    {
                        mainRange = new RangeSelector(tbMainRange.Text);//重新恢复原区域值
                        //重点区域起始位置判断
                        Point nowPos = mainRange.getCurPos();
                        for (j = 0; j < mainRange.Count(); j++)
                        {
                            string myCell = Convert.ToString(mySheet.Cells[nowPos.Y, nowPos.X].Value);
                            if (mainStart == "") break;
                            if (myCell == mainStart) break;
                            mainRange.acc();
                        }
                        //mainRange.lineacc();    //移到关键字下一行
                        mainRange.SetStartVal(mainRange.getCurPos());
                        //读取内容
                        while (m < MAXLINE)    //最大读取行数上限估计
                        {
                            nowPos = mainRange.getCurPos();
                            string lineFirstCell = Convert.ToString(mySheet.Cells[nowPos.Y, nowPos.X].Value);
                            if (lineFirstCell == null|| lineFirstCell=="") break;   //首字为空
                            if (lineFirstCell == tbMainEnd.Text) break; //符合结束字符串
                            if (mainRange.pos > mainRange.Count()) break;//读取完了就退出
                            for (j = 0; j < mainRange.getWidth(); j++)//读取一行
                            {
                                point = mainRange.getCurPos();
                                myArray[m, j] = Convert.ToString(mySheet.Cells[point.Y, point.X].Value);    //不管什么类型都转为字符串
                                mainRange.acc();
                            }
                            myArray[m, j] = DataTag;
                            m++;
                        }
                    }
                    else
                    {
                        //准备读取单元格相关信息,固定位置读取单元格
                        if (iCount >= 1)
                        {
                            List<Array> ListOfLine = new List<Array>(); //所有的读取行集合
                            String[] myLine = new String[iCount];   //单行对象
                            RangeSelector[] rsContentA = new RangeSelector[iCount];
                            for (j = 0; j < iCount; j++)
                            {
                                rsContentA[j] = new RangeSelector(lbContent.Items[j].ToString());
                            }
                            j = 0;
                            foreach (RangeSelector cont in rsContentA)
                            {
                                cont.acc();
                                point = cont.getCurPos();
                                myArray[m, j] = Convert.ToString(mySheet.Cells[point.Y, point.X].Value);    //不管什么类型都转为字符串
                                j++;
                                if (j > iCount) break;//xxxxxxx
                            }
                            myArray[m, j - 1] = DataTag;
                            m++;
                        }
                    }
                }
                //关闭当前活页簿
                myBook.Close();
                System.Windows.Forms.Application.DoEvents();
            }
            myExcel.Quit();
        }
Example #59
0
		public static bool IsReferencesTabActive(_Application application)
		{
			var ribbon = application.CommandBars["Ribbon"];
			var accessibleRibbon = ribbon as IAccessible;
		}
Example #60
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (myArray == null)
            {
                MessageBox.Show("请先读取数据");
                return;
            }

            //開啟一個新的應用程式
            myExcel = new Excel.Application();
            //加入新的活頁簿
            myExcel.Workbooks.Add(true);
            //停用警告訊息
            myExcel.DisplayAlerts = true;
            //讓Excel文件可見
            myExcel.Visible = true;
            //引用第一個活頁簿
            myBook = myExcel.Workbooks[1];
            //設定活頁簿焦點
            myBook.Activate();
            //加入新的工作表在第1張工作表之後
            myBook.Sheets.Add(Type.Missing, myBook.Worksheets[1], 1, Type.Missing);
            //引用第一個工作表
            mySheet = (Worksheet)myBook.Worksheets[1];
            //命名工作表的名稱為 "Array"
            mySheet.Name = "Array";
            //設工作表焦點
            mySheet.Activate();
            int UpBound1 = myArray.GetUpperBound(0);//二維陣列數上限
            int UpBound2 = myArray.GetUpperBound(1);//二維陣列數上限
            //寫入報表名稱
            myExcel.Cells[1, 4] = "全自动生成報表";
            //設定範圍
            myRange = (Range)mySheet.Range[mySheet.Cells[2, 1], mySheet.Cells[UpBound1 + 2, UpBound2 + 1]];
            myRange.Select();
            //用陣列一次寫入資料
            myRange.Value2 = myArray;
            //設定儲存路徑
            string PathFile = Directory.GetCurrentDirectory() + @"\我的报表.xlsx";
            //另存活頁簿
            myBook.SaveAs(PathFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                , XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            //關閉活頁簿
            //myBook.Close(false, Type.Missing, Type.Missing);
            ////關閉Excel
            //myExcel.Quit();
            ////釋放Excel資源
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
            myBook = null;
            mySheet = null;
            myRange = null;
            myExcel = null;

            GC.Collect();
        }