예제 #1
0
        public void PastTest()
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.ApplicationClass();
            app.Visible = false;
            Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(@"C:\Users\Administrator\Desktop\WorkFiles\Letter Automation\Template\NewTemplate\(chi) Cancellation of PW1.doc", false);

            doc.Activate();

            doc.Tables[2].Cell(2, 2).Range.FormFields[1].Result = "44444444";
            int count = doc.FormFields.Count;

            doc.Tables[1].ConvertToText(WdTableFieldSeparator.wdSeparateByParagraphs, false);
            doc.Tables[2].Cell(1, 3).Range.Text = "33";
            doc.Tables[3].Rows.Add();
            object unite = WdUnits.wdStory;

            app.Selection.EndKey(ref unite, Type.Missing); //将光标移动到文档末尾
            doc.Tables[3].Rows[1].Cells[1].Range.Paste();
            doc.Tables[3].Rows.Add();

            doc.Protect(WdProtectionType.wdAllowOnlyFormFields, true, Type.Missing, Type.Missing, true);
            doc.Save();
            doc.Save();
            doc.Close();
            app.Quit();
        }
        public void CreateEntry()
        {
            try
            {
                Word.Application application = new Word.Application();
                application.Visible = false;
                Word.Document doc   = application.Documents.Open(FeatureContext.Current["ReportsFolderPath"].ToString() + FeatureContext.Current["OELog"].ToString() + ".docx");
                Word.Table    table = doc.Tables[1];

                int lastRowIndex = table.Rows.Count;
                table.Cell(lastRowIndex, 1).Range.Text = "Step " + FeatureContext.Current["StepNumber"];
                table.Cell(lastRowIndex, 2).Range.Text = GetScenarioTag("ReqID");
                table.Cell(lastRowIndex, 3).Range.Text = ScenarioContext.Current["Actions"].ToString();
                table.Cell(lastRowIndex, 4).Range.Text = ScenarioContext.Current["ExpResults"].ToString();
                table.Cell(lastRowIndex, 5).Range.Text = ScenarioContext.Current["ActResult"].ToString();
                table.Cell(lastRowIndex, 6).Range.Text = ScenarioContext.Current["Comments"].ToString();

                table.Rows[lastRowIndex].Range.Bold      = 0;
                table.Rows[lastRowIndex].Range.Font.Size = 11;
                table.Rows[lastRowIndex].Range.Font.Name = "Times New Roman";

                ScenarioContext.Current.Remove("Actions");
                ScenarioContext.Current.Remove("ExpResults");
                ScenarioContext.Current.Remove("ActResult");
                ScenarioContext.Current.Remove("Comments");

                doc.Save();
                doc.Close();
                application.Quit();
            }
            catch (Exception e)
            {
            }
        }
예제 #3
0
        public void processWord(string saved_path, bool newSmry)
        {
            word_app = createWordApp();
            this.insertBookmark(saved_doc_list);
            object strFileName = saved_path;
            Object Nothing     = System.Reflection.Missing.Value;
            object readOnly    = false;
            object isVisible   = false;

            word_wrt = word_app.Documents.Open(ref strFileName, ref Nothing, ref readOnly,
                                               ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                                               ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing,
                                               ref Nothing, ref Nothing, ref Nothing);
            word_wrt.Activate();
            //word_wrt.Paragraphs.Last.Range.Text = "test text" + "\n";//加个结束符(增加一段),否则再次插入的时候就成了替换.
            this.writeSammary();
            //保存
            word_wrt.Save();

            // test code
            this.buildTOC(saved_path, newSmry);
            // test code

            try
            {
                word_show.Quit(ref Nothing, ref Nothing, ref Nothing);
                word_app.Quit(ref Nothing, ref Nothing, ref Nothing);
            }
            catch (Exception)
            {
            }

            word_app  = null;
            word_show = null;
        }
예제 #4
0
 public static void SaveFile(Word.Document doc, string fileName = "")
 {
     if (string.IsNullOrEmpty(fileName))
     {
         try
         {
             doc.Save();
         }
         catch (Exception e)
         {
             throw new Exception("Can't save file", e);
         }
     }
     else
     {
         try
         {
             doc.SaveAs(fileName);
         }
         catch (Exception e)
         {
             throw new Exception("Can't save file in " + fileName, e);
         }
     }
 }
예제 #5
0
 protected override void OnButtonAction(XRibbonButton xRibbonButton, RibbonEventArgs e)
 {
     //Commands.DocumentAdmin.Execute(SceneContext.Instance);
     OfficeWord.Application app = SceneContext.Instance.WordAppAdmin.Application;
     OfficeWord.Document    doc = app.ActiveDocument;
     if (doc != null)
     {
         if (SceneContext.Instance.SecretDataAdmin.Get(doc) == null)
         {
             MessageBox.Show("该文档不是通过文档工具打开的文档,无法使用此功能!");
         }
         else
         {
             SceneContext.Instance.SecretDataAdmin.Remove(doc);
             doc.Save();
             string filename     = doc.FullName;
             string tempFileName = Path.Combine(Logger.TemporaryDirectory, doc.Name);
             File.Copy(filename, tempFileName);
             if (SceneContext.Instance.FileServer.Upload(tempFileName, doc.Name))
             {
                 MessageBox.Show("文件保存成功!");
             }
             // 缺省参数
             object unknown = Type.Missing;
             doc.Close(ref unknown, ref unknown, ref unknown);
             File.Delete(tempFileName);
             File.Delete(filename);
         }
     }
 }
예제 #6
0
        private async Task CreateWord(string filePath)
        {
            var xmlString = System.IO.File.ReadAllText(filePath);

            Word.Application app = new Word.Application();
            Word.Document    doc = app.Documents.Add();
            try
            {
                doc.Content.Font.Size = 12;
                try
                {
                    doc.Content.Text = xmlString;

                    doc.Save();
                    doc.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to convert file");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Marshal.ReleaseComObject(app);
            }
        }
예제 #7
0
        private void FormatHeaders(string DocToFormat)
        {
            var application = new Word.Application();

            Word.Document document = application.Documents.Open(DocToFormat);

            string imgHeader1 = @"C:\hmz\Stanlib_Logo_Board_Reports.png";
            string HeaderLine = @"C:\hmz\Stanlib_HeaderLine.png";

            foreach (Word.Section section in document.Sections)
            {
                section.PageSetup.DifferentFirstPageHeaderFooter = -1;
                Word.HeaderFooter header = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
                lblProcessing.Text = "Processing Headers...";
                //wdHeaderFooterFirstPage would be for first page..

                header.Shapes.AddPicture(imgHeader1, 0, 1, -15, -15, 137, 51);
                header.Shapes.AddPicture(HeaderLine, 0, 1, -15, 50, 520, 1);
                //header.Shapes.AddLine(28, 90, 558, 90);
            }

            document.Save();
            document.Close();
            application.Quit();
        }
예제 #8
0
        private void WordMailMergeLink(string fileNameTemplate, string projectid)
        {
            MSWord.Application winword        = null;
            MSWord.Document    actualDocument = null;

            winword = new MSWord.Application();
            MSWord.Document docNew = null;

            winword.ShowAnimation = false;
            winword.Visible       = true;
            object missing = System.Reflection.Missing.Value;

            try
            {
                docNew = winword.Documents.Open(fileNameTemplate);
                docNew.Activate();
                actualDocument = docNew;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            var wrdMailMerge = actualDocument.MailMerge;

            wrdMailMerge.OpenDataSource(@"C:\ErasmDB\localDB.accdb", missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing,
                                        "SELECT * FROM [tblWordMailMerge] WHERE ProjectID='" + projectid + "'");

            actualDocument.Save();
            actualDocument.Close();
        }
예제 #9
0
파일: frmKiemQuy.cs 프로젝트: halong84/CRM
        void PutStringIntoTable(Word.Document doc)
        {
            object oMissing = System.Reflection.Missing.Value;

            Word.Table tb = doc.Tables[2];
            for (int i = 0; i < usersKiemQuy.Count; i++)
            {
                string pb     = Thong_tin_dang_nhap.ten_cn;
                string hoTen  = "- " + usersKiemQuy[i].tennv;
                string chucVu = "- " + usersKiemQuy[i].chucvu + " " + Thong_tin_dang_nhap.tenPb;
                if (usersKiemQuy[i].chucvu == "Giám đốc" || usersKiemQuy[i].chucvu == "Phó Giám đốc")
                {
                    chucVu = "- " + usersKiemQuy[i].chucvu.Replace("Phó Giám đốc", "PGĐ").Replace("Giám đốc", "GĐ") + " " + Thong_tin_dang_nhap.ten_cn.Replace("chi nhánh", "CN").Replace("Thành phố", "tp");
                }
                else if (usersKiemQuy[i].chucvu == "Nhân viên")
                {
                    chucVu = "- " + "Cán bộ nghiệp vụ thẻ";
                }
                string chucDanh = "- " + "Thành viên";
                if (usersKiemQuy[i] == usersKiemQuy[0])
                {
                    chucDanh = "- " + "Trưởng ban";
                }

                tb.Rows[i + 1].Cells[1].Range.Text = hoTen;
                tb.Rows[i + 1].Cells[2].Range.Text = chucVu;
                tb.Rows[i + 1].Cells[3].Range.Text = chucDanh;
                if (i != usersKiemQuy.Count - 1)
                {
                    tb.Rows.Add(oMissing);
                }
                doc.Save();
            }
        }
예제 #10
0
        /*Function  which starts DAISY Translation*/
        private void DoConvert()
        {
            try
            {
                for (int pGh = 1; pGh <= doc.Paragraphs.Count; pGh++)
                {
                    progressBar1.Increment(1);
                    float percentShow = (this.progressBar1.Value * 100) / count;
                    lblProgress.Text = "Updation Process: " + percentShow.ToString() + "% " + "" + "completed";
                    Application.DoEvents();
                    MSword.WdLanguageID lngId = DetectLng(doc.Paragraphs[pGh].Range);

                    try
                    {
                        doc.Paragraphs[pGh].Range.LanguageID = lngId;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
                doc.Save();
                WorkComplete(null);
            }
            catch (Exception e)
            {
                WorkComplete(e);
            }
        }
예제 #11
0
 protected override void OnButtonAction(XRibbonButton xRibbonButton, RibbonEventArgs e)
 {
     //Commands.DocumentAdmin.Execute(SceneContext.Instance);
     OfficeWord.Application app = SceneContext.Instance.WordAppAdmin.Application;
     OfficeWord.Document    doc = app.ActiveDocument;
     if (doc != null)
     {
         doc.Save();
         var entry = new SecretEntry()
         {
             LoginEntity = null,
             BizFileName = doc.FullName,
             BizFileId   = "",
         };
         SceneContext.Instance.SecretDataAdmin.Set(doc, entry);
         string filename     = doc.FullName;
         string tempFileName = Path.Combine(Logger.TemporaryDirectory, doc.Name);
         File.Copy(filename, tempFileName);
         if (SceneContext.Instance.FileServer.Upload(tempFileName, doc.Name))
         {
             MessageBox.Show("文件新增成功!");
         }
         File.Delete(tempFileName);
     }
 }
예제 #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            word.Application app = new word.Application();
            app.Visible = true;

            CommandBar pdbar = app.CommandBars.Add("prontodoc link");


            CommandBarButton ctrl = pdbar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton, Type.Missing, Type.Missing, Type.Missing, true) as CommandBarButton;

            ctrl.Tag     = "test";
            ctrl.Caption = "Add ProntoDoc link";
            //ctrl.Style = MsoButtonStyle.msoButtonIconAndCaption;
            ctrl.Visible = true;
            //ctrl.Click += new _CommandBarButtonEvents_ClickEventHandler(ctrl_Click);
            // ctrl.OnAction
            pdbar.Visible = true;


            word.Document    doc = app.Documents.Open(@"e:\Doc1.docx");
            word.InlineShape img = doc.InlineShapes[1];


            string link = img.Hyperlink.Address;

            MessageBox.Show("old link: " + link);
            img.Hyperlink.Address = "http://localhost:81/";
            doc.Save();
            doc.Close();
            app.Quit();
        }
예제 #13
0
        private void FormatDocumentMargins(string DocToFormat)
        {
            var application = new Word.Application();

            Word.Document document = application.Documents.Open(DocToFormat);

            try
            {            // format entire document first , remember 1 cm = 28.35 points
                document.PageSetup.PaperSize    = Word.WdPaperSize.wdPaperA4;
                document.PageSetup.BottomMargin = (float)85;
                document.PageSetup.TopMargin    = (float)99;
                document.PageSetup.LeftMargin   = (float)57;
                document.PageSetup.RightMargin  = (float)57;
                document.PageSetup.Gutter       = 0;
                document.PageSetup.GutterPos    = Word.WdGutterStyle.wdGutterPosLeft;

                document.PageSetup.HeaderDistance = (float)35;
                document.PageSetup.FooterDistance = (float)31;

                //document.SaveAs2(@"C:\hmz\ProcessedDocuments\InterOP_Processed_" + FileName);
                document.Save();
                document.Close();
                application.Quit();
            }
            catch (Exception we)
            {
                MessageBox.Show(we.Message.ToString());
                document.Close();
                application.Quit();
            }
        }
예제 #14
0
        public void TakeScreenshot()
        {
            try
            {
                String stepType = ScenarioStepContext.Current.StepInfo.StepDefinitionType.ToString();
                if (stepType.Equals("Then", StringComparison.InvariantCultureIgnoreCase) &&
                    IsObjectEvidenceTagExists())
                {
                    String scenarioTitle = ScenarioContext.Current.ScenarioInfo.Title;
                    String step          = ScenarioContext.Current.StepContext.StepInfo.Text;

                    ITakesScreenshot takesScreenshot    = BrowserUtilities.WebDriver as ITakesScreenshot;
                    Screenshot       screenShot         = takesScreenshot.GetScreenshot();
                    String           screenshotFullPath = FeatureContext.Current["Screenshot_TempFolder"] + "\\temp.png";
                    screenShot.SaveAsFile(screenshotFullPath);

                    Word.Application application = new Word.Application();
                    application.Visible = false;
                    Word.Document doc = application.Documents.Open(FeatureContext.Current["ReportsFolderPath"].ToString() + FeatureContext.Current["OELog"].ToString() + ".docx");

                    Word.Table table = doc.Tables[2];
                    table.Rows.Add(System.Reflection.Missing.Value);
                    int lastRowIndex = table.Rows.Count;
                    table.Rows[lastRowIndex].Range.Bold = 1;
                    String text = "STEP " + FeatureContext.Current["StepNumber"];
                    text += "\n Scenario: " + scenarioTitle + ", ScenarioStep: " + step + ", Date: " + DateTime.Now.ToString();
                    table.Cell(lastRowIndex, 1).Range.Text      = text;
                    table.Cell(lastRowIndex, 1).Range.Font.Size = 11;
                    table.Cell(lastRowIndex, 1).Range.Font.Name = "Times New Roman";

                    table.Rows.Add(System.Reflection.Missing.Value);
                    lastRowIndex = table.Rows.Count;
                    Word.InlineShape image = table.Cell(lastRowIndex, 1).Range.InlineShapes.AddPicture(screenshotFullPath);
                    image.Width  = 500;
                    image.Height = 300;
                    doc.Save();
                    File.Delete(screenshotFullPath);

                    doc.Save();
                    doc.Close();
                    application.Quit();
                }
            }
            catch (Exception e)
            {
            }
        }
        /// <summary>
        /// 设置Word文件属性
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="fileId">文件Id</param>
        public static void SetWordFileID(ref string filePath, string fileId)
        {
            Word.Application application = null;
            Word.Document    doc         = null;
            try
            {
                _log.Debug($"SetWordFileID Start.");

                application         = new Word.Application();
                application.Visible = false;
                object documentPath = filePath;

                // 设置文件
                doc = application.Documents.Open(ref documentPath);
                var  oDocBuiltInProps    = doc.BuiltInDocumentProperties;
                Type typeDocBuiltInProps = oDocBuiltInProps.GetType();

                //Set the Comments property.
                typeDocBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oDocBuiltInProps, new object[] { "Comments", fileId });
                doc.Save();

                var dirPath = Path.GetDirectoryName(filePath);
                var ext     = Path.GetExtension(filePath);
                filePath = $"{dirPath}\\{Guid.NewGuid()}{ext}";
                doc.SaveAs2(filePath);
            }
            catch (Exception ex)
            {
                _log.Debug($"SetWordFileID Exception: {ex.Message}");
            }
            finally
            {
                KillProcessesTask("WINWORD");

                try
                {
                    if (doc != null)
                    {
                        doc.Close();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                    }
                }
                catch (Exception ex)
                {
                    doc = null;
                    _log.Debug($"SetWordFileID DocClose Finally Exception: {ex.Message}");
                }
                try
                {
                    application.Quit();
                }
                catch (Exception ex)
                {
                    application = null;
                    _log.Debug($"SetWordFileID AppClose Finally Exception: {ex.Message}");
                }
                _log.Debug($"SetWordFileID End.");
            }
        }
예제 #16
0
        public void CoautherWithoutConflict()
        {
            // Upload a document
            SharepointClient.UploadFile(Word);
            // Refresh web address
            Browser.Goto(Browser.BaseAddress);
            // Find document on site
            IWebElement document = Browser.webDriver.FindElement(By.CssSelector("a[href*='" + filename + ".docx']"));

            // Open document by office word
            Browser.RClick(document);
            var elementOpenInWord = Browser.webDriver.FindElement(By.XPath("//div[@id='ID_EditIn_Word']"));

            Browser.Click(elementOpenInWord);
            // Close Microsoft office dialog and access using expected account
            Utility.CloseMicrosoftOfficeDialog();
            string username = ConfigurationManager.AppSettings["UserName"];
            string password = ConfigurationManager.AppSettings["Password"];

            Utility.OfficeSignIn(username, password);
            // Wait for document is opened
            Utility.WaitForDocumentOpenning(filename);
            // Get the opened word process, and edit it
            Word.Application wordToOpen = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
            Word.Document    oDocument  = (Word.Document)wordToOpen.ActiveDocument;
            oDocument.Content.InsertAfter("HelloWord");

            // Double click the document in root site
            Browser.Click(document);
            // Find and click "Edit Document" tab
            var editWord = Browser.FindElement(By.XPath("//a[@id='flyoutWordViewerEdit-Medium20']"), false);

            editWord.SendKeys(OpenQA.Selenium.Keys.Enter);
            SendKeys.SendWait("Enter");
            // Find and click "Edit in Browser" tab
            var editInbrowser = Browser.webDriver.FindElement(By.XPath("//a[@id ='btnFlyoutEditOnWeb-Menu32']"));

            editInbrowser.SendKeys(OpenQA.Selenium.Keys.Enter);
            SendKeys.SendWait("Enter");
            // Wait for document is opened
            var saved = Browser.FindElement(By.XPath("//span[@id='BreadcrumbSaveStatus'][text()='Saved']"), false);

            oDocument.Save();
            oDocument.Close();
            Utility.DeleteDefaultWordFormat();
            Marshal.ReleaseComObject(oDocument);
            Marshal.ReleaseComObject(wordToOpen);
            // Refresh web address
            Browser.Goto(Browser.BaseAddress);
            // Delete the new upload document
            SharepointClient.DeleteFile(filename + ".docx");

            bool result = FormatConvert.SaveSAZ(TestBase.testResultPath, testName, out file);

            Assert.IsTrue(result, "The saz file should be saved successfully.");
            bool parsingResult = MessageParser.ParseMessageUsingWOPIInspector(file);

            Assert.IsTrue(parsingResult, "Case failed, check the details information in error.txt file.");
        }
예제 #17
0
        //Accept button
        private void accept_Click(object sender, EventArgs e)
        {
            String localFileName = "";

            try
            {
                disableAllButtons();
                if (application is Word.Document)
                {
                    Word.Document activeDocument = ((Word.Document)application);
                    activeDocument.Save(); // Saves the document
                    localFileName = activeDocument.FullName;
                }
                else if (application is Excel.Workbook)
                {
                    Excel.Workbook actitiveWorkBook = ((Excel.Workbook)application);
                    actitiveWorkBook.Save(); // Saves the document;
                    localFileName = actitiveWorkBook.FullName;
                }
                else if (application is PowerPoint.Presentation)
                {
                    PowerPoint.Presentation activePresentation = ((PowerPoint.Presentation)application);
                    activePresentation.Save(); // Saves the document
                    localFileName = activePresentation.FullName;
                }
                else if (application is Visio.Document)
                {
                    Visio.Document activeDocument = ((Visio.Document)application);
                    activeDocument.Save(); // Saves the document
                    localFileName = activeDocument.FullName;
                }
                else if (application is String)
                {
                    localFileName = (String)application;
                }

                String docPath = Util.getOpenKMPath(localFileName, (MSOpenKMCore.ws.folder)actualNode.Tag);
                // Must save a temporary file to be uploaded
                File.Copy(localFileName, localFileName + "_TEMP");
                localFileName = localFileName + "_TEMP";
                DocumentLogic.create(localFileName, docPath, configXML.getHost(), configXML.getUser(), configXML.getPassword());
                File.Delete(localFileName); // Deletes temporary file
                MessageBox.Show(resources.GetString("uploaded"));
            }
            catch (Exception ex)
            {
                // Ensure temporary file is deleted
                if (!localFileName.Equals("") && File.Exists(localFileName))
                {
                    File.Delete(localFileName); // Deletes temporary file
                }
                String errorMsg = "TreeForm - (accept_Click)\n" + ex.Message + "\n\n" + ex.StackTrace;
                MessageBox.Show(errorMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                Hide();
            }
        }
예제 #18
0
 /// <summary>
 /// 保存
 /// </summary>
 public void Save()
 {
     if (_wordDocument == null)
     {
         _wordDocument = _wordApplication.ActiveDocument;
     }
     _wordDocument.Save();
 }
예제 #19
0
 public void SaveDocument()
 {
     try{
         aDoc.Save();
     }catch (Exception ex) {
         MessageBox.Show("Error durante el proceso. Descripcion: " + ex.Message, "Error Interno", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
예제 #20
0
 //Directly save file without naming
 public void Save()
 {
     if (wordDoc == null)
     {
         wordDoc = wordApp.ActiveDocument;
     }
     wordDoc.Save();
 }
예제 #21
0
파일: Form1.cs 프로젝트: Cesar18102/Media
        private void PrintWord <Q>(List <string> headers, ValueAt <Q> V, List <Q> Values, string head)
        {
            this.UseWaitCursor = true;
            FileStream FS = File.Create(Environment.CurrentDirectory + "/Print.doc");

            FS.Close();

            Application = new Word.Application();
            Object PrintPath = Environment.CurrentDirectory + "/Print.doc";

            Document = Application.Documents.Add(ref PrintPath, ref missingObj, ref missingObj, ref missingObj);
            Document.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
            R = Document.Sections[1].Range;

            T = Document.Tables.Add(R, Values.Count + 3, headers.Count, missingObj, missingObj);
            T.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            T.Borders.InsideLineStyle  = Word.WdLineStyle.wdLineStyleSingle;

            T.Rows[1].Cells.Merge();
            T.Rows[1].Cells[1].Width           = 698;
            T.Rows[1].Cells[1].Range.Text      = head;
            T.Rows[1].Cells[1].Range.Font.Size = 18;
            T.Rows[1].Cells[1].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            T.Rows[1].Cells[1].Range.Borders.Enable            = 0;

            for (int i = 1; i <= headers.Count; i++)
            {
                T.Rows[2].Cells[i].Width      = 700 / headers.Count;
                T.Rows[2].Cells[i].Range.Text = headers[i - 1];

                T.Rows[2].Cells[i].Range.Font.Size = 14;
                T.Rows[2].Cells[i].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            }

            for (int i = 0; i < Values.Count; i++)
            {
                for (int j = 0; j < headers.Count; j++)
                {
                    T.Rows[i + 3].Cells[j + 1].Width      = 700 / headers.Count;
                    T.Rows[i + 3].Cells[j + 1].Range.Text = V(Values[i], j);
                }
            }

            T.Rows[Values.Count + 3].Cells.Merge();
            T.Rows[Values.Count + 3].Cells[1].Range.Text      = DateTime.Now.ToShortDateString();
            T.Rows[Values.Count + 3].Cells[1].Range.Font.Size = 14;
            T.Rows[Values.Count + 3].Cells[1].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            T.Rows[Values.Count + 3].Cells[1].Range.Borders.Enable            = 0;

            try
            {
                Document.Save();
                Document.Close(missingObj, missingObj, missingObj);
            }
            catch { MessageBox.Show("Отчет не создан!", "Ошибка"); }

            this.UseWaitCursor = false;
        }
        private void ibuttonReplace_Click(object sender, EventArgs e)
        {
            string headerDocument = "";
            string newtemplate    = textTemplate.Text.Replace(".docx", "-newheader.docx");
            string newheader      = Program.GData.CFGFolderLocal + "\\NewDocHeader.docx";
            string tmpfile        = Program.GData.CFGFolderLocal + "\\tmp.docx";

            MessageBox.Show("Allow designer mode");

            SetStatus("Saving temporary file" + tmpfile);
            actualDocument.SaveAs2(tmpfile);

            SetStatus("Deleting first 2 pages");
            DeleteFirstPage();
            DeleteFirstPage();
            actualDocument.Close();

            headerDocument = Program.GData.CFGFolderLocal + @"\assets\NewHeader.docx";
            ProcessFile(headerDocument);
            SetStatus("Saving temporary file" + newheader);
            actualDocument.SaveAs2(newheader);

            SetStatus("replace old variables");
            ReplaceOldVars();

            //LockFields();

            actualDocument.Save();
            actualDocument.Close();

            string[] docs = new string[2];
            docs[0] = newheader;
            docs[1] = tmpfile;

            SetStatus("merge document " + newheader + " / " + tmpfile);
            MergeWordDocs(docs, newtemplate, true);

            textTemplate.Text = newtemplate;
            ProcessFile(textTemplate.Text);

            SetStatus("replace old variables");
            ReplaceOldVars();
            actualDocument.Save();
            SetStatus("");
        }
예제 #23
0
        private void test()
        {
            try
            {
                //  Just to kill WINWORD.EXE if it is running
                //killprocess("winword");
                //  copy letter format to temp.doc
                //File.Copy("C:\\OfferLetter.doc", "c:\\temp.doc", true);
                //  create missing object
                object missing = Missing.Value;
                //  create Word application object
                Word.Application wordApp = new Word.Application();
                wordApp.Visible = false;

                //  create Word document object
                Word.Document aDoc = null;

                //  create & define filename object with temp.doc
                object filename = "C:\\Users\\temp\\Documents\\samplee.docx";
                //  if temp.doc available
                if (File.Exists((string)filename))
                {
                    object readOnly  = false;
                    object isVisible = false;
                    //  make visible Word application
                    wordApp.Documents.Application.Visible = false;
                    //  open Word document named temp.doc
                    aDoc = wordApp.Documents.Open(ref filename, ref missing,
                                                  ref readOnly, ref missing, ref missing, ref missing,
                                                  ref missing, ref missing, ref missing, ref missing,
                                                  ref missing, ref isVisible, ref missing, ref missing,
                                                  ref missing, ref missing);
                    aDoc.Activate();
                    //  Call FindAndReplace()function for each change
                    this.FindAndReplace(wordApp, "<Name>", "Emmanuel Sunesis".Trim());
                    this.FindAndReplace(wordApp, "<Phone number>", "08142412522".Trim());
                    this.FindAndReplace(wordApp, "<Address>",
                                        "Plot 22, Owoseni Street".Trim());
                    //  save temp.doc after modified
                    aDoc.Save();
                    wordApp.Documents.Close();
                    wordApp.Quit(true, ref missing, ref missing);
                }
                else
                {
                    MessageBox.Show("File does not exist.",
                                    "No File", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
                //killprocess("winword");
            }
            catch (Exception)
            {
                MessageBox.Show("Error in process.", "Internal Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #24
0
        public void _mSaveFileDOC(string fileSave, bool checkDelete, bool closeFile)
        {
            try
            {
                if (checkDelete)
                {
                    if (System.IO.File.Exists(fileSave))
                    {
                        System.IO.File.Delete(fileSave);
                    }
                }
                if (xlApplicationWord != null && fileSave == "")
                {
                    doc.Save();
                }
                if (xlApplicationWord != null && fileSave != "")
                {
                    object fileNameSave     = fileSave;
                    object oMissing         = System.Reflection.Missing.Value;
                    object FileFormat       = Word.WdSaveFormat.wdFormatDocument;
                    object LockComments     = false;
                    object Password         = "";
                    object AddToRecentFiles = false;

                    //Save tập tin word.

                    doc.SaveAs(ref fileNameSave, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref objMiss);

                    //if (_vfileSave.ToLower().IndexOf(".docx") != -1)
                    //    doc.SaveAs(ref _vFileNameSave, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                }
                if (closeFile) //Đóng tập tin lại
                {
                    _mCloseFileDOC();
                }
            }
            catch
            {
                if (closeFile)
                {
                    _mCloseFileDOC();
                }
            }
        }
        /// <summary>
        /// Remove Blank Page in Word document
        /// </summary>
        private bool RemoveBlankPage()
        {
            Word.Application wordapp    = null;
            Word.Document    doc        = null;
            Word.Paragraphs  paragraphs = null;
            try
            {
                // Start Word APllication and set it be invisible
                wordapp         = new Word.Application();
                wordapp.Visible = false;
                doc             = wordapp.Documents.Open(wordPath);
                paragraphs      = doc.Paragraphs;
                foreach (Word.Paragraph paragraph in paragraphs)
                {
                    if (paragraph.Range.Text.Trim() == string.Empty)
                    {
                        paragraph.Range.Select();
                        wordapp.Selection.Delete();
                    }
                }

                // Save the document and close document
                doc.Save();
                ((Word._Document)doc).Close();

                // Quit the word application
                ((Word._Application)wordapp).Quit();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception Occur, error message is: " + ex.Message);
                return(false);
            }
            finally
            {
                // Clean up the unmanaged Word COM resources by explicitly
                // call Marshal.FinalReleaseComObject on all accessor objects
                if (paragraphs != null)
                {
                    Marshal.FinalReleaseComObject(paragraphs);
                    paragraphs = null;
                }
                if (doc != null)
                {
                    Marshal.FinalReleaseComObject(doc);
                    doc = null;
                }
                if (wordapp != null)
                {
                    Marshal.FinalReleaseComObject(wordapp);
                    wordapp = null;
                }
            }

            return(true);
        }
예제 #26
0
        public void PasteBookmark(object bookmark)
        {
            document.Bookmarks[bookmark].Range.Select();
            document.Bookmarks[bookmark].Range.Paste();

            foreach (Word.Bookmark bm in document.Bookmarks)
            {
                if (bm.Name != "Проект_договора" && bm.Name != "Техническая_спецификация" && bm.Name != "Квалификационные_требования")
                {
                    document.Bookmarks.Add(bookmark.ToString(), bm.Range);
                    bm.Delete();
                    break;
                }
            }

            document.Save();

            AutoFitTables();
        }
예제 #27
0
        private void WordSave(string strFileName)
        {
            object missing  = System.Reflection.Missing.Value;
            object fileName = strFileName;

            _WordDoc.Save();

            //object saveChanges = Word.WdSaveOptions.wdSaveChanges;
            //_WordDoc.Close(ref saveChanges, ref missing, ref missing);
        }
예제 #28
0
파일: Logger.cs 프로젝트: dances273/Daences
        private static void Penztar()
        {
            Word.Application app     = new Microsoft.Office.Interop.Word.Application();
            Word.Document    doc     = app.Documents.Open(@"D:\Log\testdoc1.docx");
            object           missing = System.Reflection.Missing.Value;

            doc.Content.Text +=
                app.Visible   = true; //Optional
            doc.Save();
        }
예제 #29
0
        public void Close()
        {
            table.Rows.First.Delete();

            // конец экспорта
            if (data.openFileExport)
            {
                // сохранить изменения и открыть документ
                document.Save();
                wordApp.Visible = true;
            }
            else
            {
                // для закрытия документа без показа
                document.Save();
                document.Close();
                wordApp.Quit();
            }
        }
예제 #30
0
파일: ThisAddIn.cs 프로젝트: leonchen09/poc
        private void Application_DocumentBeforeClose(Word.Document Doc, ref bool Cancel)
        {
            // remove internal bookmark, makrup object and datasegment
            // Doc.Shapes.AddLabel(Office.MsoTextOrientation.msoTextOrientationMixed, 30, 2, 33, 44);
            Doc.Save();
            Zip zip = new Zip();

            zip.ServerDir = @"E:\ProntoDir\pde\";
            zip.UnZipFile("doc3.docx");
        }
예제 #31
0
        private void insertarPrimerosCodigosDeBarra(bool EtiquetaMultiples)
        {
            this.generarPrimerosCodigosDeBarra(true);
            List<string> bcdUsados = new List<string>();
            foreach (Etiqueta_C.Estructura_etqMultiple etqM in ListaEtiquetasMultiples)
            {
                string path = @rutasEnModAdmin.RutaDePlantillas + "/temp_EtiquetaActual" + ListaEtiquetasMultiples.IndexOf(etqM) + ".docx";
                appWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
                appWord.Visible = false;

                doc = appWord.Documents.Open(path);
                List<Word.Shape> lst = new List<Word.Shape>();

                foreach (Word.Shape sh in doc.Shapes)
                {
                    if (sh.Type.ToString() == "msoPicture")
                    {
                        while (sh.Name.Contains("\n"))
                            sh.Name = sh.Name.Replace("\n", "");
                        lst.Add(sh);
                    }
                }
                foreach (string bcd in lista_camposCodBarr)
                {
                    foreach (Control txt in gb_CamposAdicionales.Controls.OfType<TextBox>())
                    {
                        if (!txt.Name.Contains(bcd.Replace("bcd", "")))
                            continue;
                        try
                        {
                            bcdUsados.Add(bcd);
                            float left, top, h, w;
                            string tempname = "";
                            List<Word.Range> ranges = new List<Word.Range>();
                            Word.Shape removed = null;
                            foreach (Word.Shape sh in lst)
                            {
                                if (sh.Name == bcd)
                                {
                                    left = sh.Left;
                                    top = sh.Top;
                                    h = sh.Height;
                                    w = sh.Width;
                                    sh.ConvertToInlineShape();
                                    foreach (Word.InlineShape s in doc.InlineShapes)
                                    {
                                        if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                        {
                                            tempname = sh.Name;
                                            ranges.Add(s.Range);
                                            s.Delete();
                                            removed = sh;
                                        }
                                    }
                                    foreach (Word.Range r in ranges)
                                    {
                                        if (File.Exists(@rutasEnModAdmin.RutaDeTemp + "/" + bcd + ".jpg"))
                                            r.InlineShapes.AddPicture(@rutasEnModAdmin.RutaDeTemp + "/" + bcd + ".jpg", Type.Missing, Type.Missing, Type.Missing);
                                    }
                                    ranges.Clear();
                                    Word.Shape pic;
                                    foreach (Word.InlineShape s in doc.InlineShapes)
                                    {
                                        if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                        {
                                            pic = s.ConvertToShape();
                                            pic.Name = tempname;
                                            pic.Top = top;
                                            pic.Left = left;
                                            pic.Height = h;
                                            pic.Width = w;
                                        }
                                    }
                                }
                                
                            }
                            lst.Remove(removed);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message + "\n\n" + ex.ToString());
                        }
                    }
                }
                doc.Save();
                doc.Saved = true;
                ((Microsoft.Office.Interop.Word._Document)doc).Close();
                
            }
            foreach (string str in bcdUsados)
                lista_camposCodBarr.Remove(str);

        }
예제 #32
0
        void RunSummary()
        {
            NotamFilter filter = new NotamFilter();
            
            filter.TypeFilter = NType;
            filter.FromDateFilter = FromDate;
            filter.ToDateFilter = ToDate;
            _notamService.Archive();
            List<Notam> notamList = _notamService.GetFilterNotams(filter);
            List<string> aeroList = notamList.Select(x => x.FirAero).ToList<string>();
            Dictionary<string, string> aeroDic = _aerodomService.GetAddressList(aeroList);
            object fileName = System.Configuration.ConfigurationManager.AppSettings.Get("DocTemplatePath").ToString();
            Word.Application word = new Word.Application();
            Word.Document doc = new Word.Document();
            object missing = System.Type.Missing;
            try
            {
                doc = word.Documents.Open(ref fileName, 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);
                doc.Activate();
                string newFileName = fileName.ToString();
                newFileName = newFileName.Replace(".docx", "1.docx");
                doc.SaveAs(newFileName);
                Process.Start(newFileName.ToString());
                int icol = 2, irow = 1;
                var queryYear = notamList.GroupBy(item => item.Year).Select(group =>
                                        new
                                        {
                                            Year = group.Key,
                                            nums = group.OrderBy(x => x.Number)
                                        }).OrderBy(group => group.nums.First().Number);
                Word.Table newTable = doc.Application.ActiveDocument.Tables[1];
                //                newTable.Rows.Add(newTable.Rows[1]);
                foreach (var yearItem in queryYear)
                {
                    newTable.Cell(irow, 1).Range.Text = "20" + yearItem.Year + ":";
                    foreach (var nt in yearItem.nums)
                    {
                        if (icol > 14)
                        {
                            icol = 2;
                            irow++;
                            newTable.Rows.Add(ref missing);

                        }
                        if (nt.Number!=null)
                            newTable.Cell(irow, icol).Range.Text = nt.Number.ToString();
                        doc.Save();
                        icol++;
                    }
                    irow++;
                    icol = 2;
                    newTable.Rows.Add(ref missing);
                    doc.Save();
                }
                

                //add0519
                var queryAero = notamList.Where(x => x.FirAero!=null).GroupBy(item => item.FirAero).Select(group =>
                        new
                        {
                            Aero = group.Key,
                            Addr = aeroDic.ContainsKey(group.Key) ? aeroDic[group.Key]:"",
                            nums = group.OrderBy(x => x.Number)
                        }).OrderBy(group => group.Addr);
                Word.Table secTable = doc.Application.ActiveDocument.Tables[2];
                irow = 1;
                //                newTable.Rows.Add(newTable.Rows[1]);
                
                foreach (var aeroItem in queryAero)
                {
                    secTable.Rows.Add(ref missing);
                    irow++;
                    secTable.Cell(irow, 3).Range.Font.Size = 11;
                    secTable.Cell(irow, 3).Range.Font.Bold = 1;
                    secTable.Cell(irow, 3).Range.Font.Italic = 1;
                    string strAeroCity = aeroItem.Addr;
                    secTable.Cell(irow, 3).Range.Text = strAeroCity + "." + aeroItem.Aero;
                    doc.Save();

                    foreach (var nt in aeroItem.nums)
                    {
                        secTable.Rows.Add(ref missing);
                        irow++;
                        secTable.Cell(irow, 1).Range.Font.Bold = 0;
                        secTable.Cell(irow, 1).Range.Font.Italic = 0;
                        secTable.Cell(irow, 1).Range.Font.Size = 10;
                        if (nt.Number!=null)
                            secTable.Cell(irow, 1).Range.Text = nt.Type+ nt.Number.ToString();
                        secTable.Cell(irow, 2).Range.Font.Bold = 0;
                        secTable.Cell(irow, 2).Range.Font.Italic = 0;
                        secTable.Cell(irow, 2).Range.Font.Size = 10;
                        if (nt.FromDate!=null)
                            secTable.Cell(irow, 2).Range.Text = nt.FromDate.Substring(0, 6);
                        string str = nt.FromDate + "/" + nt.ToDate + "/" + nt.PermEst + "\n";
                        string iteme = nt.EFreeText;
                        secTable.Cell(irow, 3).Range.Font.Bold = 0;
                        secTable.Cell(irow, 3).Range.Font.Italic = 0;
                        secTable.Cell(irow, 3).Range.Font.Size = 9;
                        secTable.Cell(irow, 3).Range.Text = str + iteme;
                        doc.Save();

                    }
                }


                doc.Save();
                MessageBox.Show("Summary created successfully.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }
예제 #33
0
        private void buttonPDF_Click(object sender, RoutedEventArgs e)
        {
            var wrd_name = Convert.ToString(comboBox.SelectedValue);
            var xls_name = textBoxExcelPath.Text;

            if (string.IsNullOrEmpty(wrd_name))
            {
                MessageBox.Show("Выберите шаблон КП");
                return;
            }

            ProgressWnd pw = new ProgressWnd("Создаем КП по шаблону...");
            pw.Show();

            string fn = "";
            try
            {

                WordApp = new Wd.Application() { Visible = false };
                WordDoc = WordApp.Documents.Open(wrd_name);
                fn=SaveW(WordApp, WordDoc);

                var ad = DataContext as AllData;

                ReplaceAll(WordDoc,"[OurCompany]", ad.Our.OurCompany);
                ReplaceAll(WordDoc, "[ForWho]", ad.ForWho);
                ReplaceAll(WordDoc, "[ContractPeriodYears]", ad.HowLongYears);
                ReplaceAll(WordDoc, "[ServiceType]", ad.ServiceType);
                ReplaceAll(WordDoc, "[DaysToStart]", ad.DaysToStart);
                ReplaceAll(WordDoc, "[DateStart]", ad.DateStart);
                ReplaceAll(WordDoc, "[CostMonthString]", ad.CostMonthString);
                ReplaceAll(WordDoc, "[CostMonth]", ad.CostMonth);
                ReplaceAll(WordDoc, "[CostYear]", (o2d(ad.CostMonth) * 12).ToString());
                ReplaceAll(WordDoc, "[Address]", ad.Address);
                ReplaceAll(WordDoc, "[Date]", ad.Date);
                ReplaceAll(WordDoc, "[Area]", ad.Area.ToString());
                ReplaceAll(WordDoc, "[NameObject]", ad.ForWho);

                int kk = 1;
                foreach(var ee in ad.e1)
                {
                    var trg="[Extra" + kk + "]";
                    if (ee.IsSelected==true)
                    {
                        ReplaceAll(WordDoc, trg, ee.Text);
                    }
                    else
                    {
                        WordDoc.Bookmarks["bExtra" + kk].Range.Delete();
                        ReplaceAll(WordDoc, trg, "");
                    }
                    ++kk;
                }

                kk = 1;
                foreach (var ee in ad.e2)
                {
                    var trg = "[Sod" + kk + "]";
                    if (ee.IsSelected == true)
                    {
                        ReplaceAll(WordDoc, trg, ee.Text);
                    }
                    else
                    {
                        WordDoc.Bookmarks["bSod" + kk].Range.Delete();
                        ReplaceAll(WordDoc, trg, "");
                    }
                    ++kk;
                }

                if(radioButton.IsChecked==true)
                {
                    ReplaceAll(WordDoc, "[NaOsnovanii]", ad.NaOsn1);
                }
                else
                {
                    ReplaceAll(WordDoc, "[NaOsnovanii]", ad.NaOsn2);
                }

                if(checkBoxServicePlan.IsChecked==false)
                {
                    Wd.Range delRange = WordDoc.Range();
                    delRange.Start=WordDoc.Bookmarks["b0"].Range.Start;
                    delRange.End = WordDoc.Bookmarks["b1"].Range.End;
                    delRange.Delete();

                }
                ReplaceAll(WordDoc, "[ServicePlanStart]", "");
                ReplaceAll(WordDoc, "[ServicePlanEnd]", "");
                //ReplaceAll(WordDoc, "[NameCost]", ad.ForWho);

                //Sebestoimost
                Wd.Table tt=FindTable(WordDoc, WordDoc.Bookmarks["tab6"]);

                double total = 0;
                foreach (var s in ad.Sebestimost)
                {
                    tt.Rows.Add();

                    tt.Cell(tt.Rows.Count, 1).Range.Text = s.Name;
                    tt.Cell(tt.Rows.Count, 2).Range.Text = s.CostMonth.ToString();
                    total += s.CostMonth;
                }
                tt.Rows.Add();
                tt.Cell(tt.Rows.Count, 1).Range.Text = "Итого";
                tt.Cell(tt.Rows.Count, 2).Range.Text = total.ToString();
                ///

                //FOT
                Wd.Table ttFOT = FindTable(WordDoc, WordDoc.Bookmarks["tab7"]);

                total = 0;
                foreach (var s in ad.ShtatRasstanovka)
                {
                    ttFOT.Rows.Add();

                    ttFOT.Cell(tt.Rows.Count, 1).Range.Text = s.Num.ToString();
                    ttFOT.Cell(tt.Rows.Count, 2).Range.Text = s.Name;
                    ttFOT.Cell(tt.Rows.Count, 3).Range.Text = s.Quant.ToString();
                    ttFOT.Cell(tt.Rows.Count, 4).Range.Text = s.Smena.ToString();
                }
                ////

                //os sredstv
                Wd.Table ttOS = FindTable(WordDoc, WordDoc.Bookmarks["tab8"]);

                total = 0;
                foreach (var s in ad.OsnSredstva)
                {
                    ttOS.Rows.Add();

                    ttOS.Cell(tt.Rows.Count, 1).Range.Text = s.Num.ToString()+".";
                    ttOS.Cell(tt.Rows.Count, 2).Range.Text = s.Name;
                    ttOS.Cell(tt.Rows.Count, 3).Range.Text = s.Quant.ToString();
                    ttOS.Cell(tt.Rows.Count, 4).Range.Text = s.CostMonth.ToString();

                    total += s.CostMonth;
                }
                ttOS.Rows.Add();
                ttOS.Cell(tt.Rows.Count, 1).Range.Text = "Итого";
                ttOS.Cell(tt.Rows.Count, 4).Range.Text = total.ToString();

                //rash san
                Wd.Table ttSAN = FindTable(WordDoc, WordDoc.Bookmarks["tab9"]);

                total = 0;
                foreach (var s in ad.RashMaterials)
                {
                    ttSAN.Rows.Add();

                    ttSAN.Cell(tt.Rows.Count, 1).Range.Text = s.Name;
                    ttSAN.Cell(tt.Rows.Count, 2).Range.Text = s.Quant.ToString();
                    ttSAN.Cell(tt.Rows.Count, 3).Range.Text = s.Price.ToString();
                    ttSAN.Cell(tt.Rows.Count, 4).Range.Text = s.CostMonth.ToString();

                    total += s.CostMonth;
                }
                ttSAN.Rows.Add();
                ttSAN.Cell(tt.Rows.Count, 1).Range.Text = "Итого в месяц";
                ttSAN.Cell(tt.Rows.Count, 4).Range.Text = total.ToString();

                StringBuilder sb = new StringBuilder();
                foreach(var c in ad.Contacts)
                {
                    if(c.IsSelected)
                    {
                        sb.AppendLine(c.Dolj);
                        sb.AppendLine(c.Name);
                        sb.AppendLine(c.Tel);
                        sb.AppendLine(c.MobTel);
                        sb.AppendLine(c.Email);
                        sb.AppendLine();
                    }
                }
                ReplaceAll(WordDoc, "[Contacts]", sb.ToString());

                WordDoc.TablesOfContents[1].Update();

                foreach (Wd.Range docRange in WordDoc.Words)
                {
                    docRange.HighlightColorIndex = Wd.WdColorIndex.wdNoHighlight;
                }

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
            finally
            {
                WordDoc.Save();
                WordApp.Documents.Close();
                WordApp.Quit(Wd.WdSaveOptions.wdDoNotSaveChanges);

                string convertedXpsDoc = string.Concat(System.IO.Path.GetTempPath(), "\\", Guid.NewGuid().ToString(), ".xps");
                XpsDocument xpsDocument = ConvertWordToXps(fn, convertedXpsDoc);
                if (xpsDocument != null)
                {
                    documentViewer.Document = xpsDocument.GetFixedDocumentSequence();
                }

                pw.Stop();

            }

            // doc.Content.Find.Execute("[ND]", ReplaceWith: Doc.No);

            //   SaveW(app, doc, TemplateFilePath);
        }
예제 #34
0
        public void processWord(string saved_path, bool newSmry)
        {
            word_app = createWordApp();
            this.insertBookmark(saved_doc_list);
            object strFileName = saved_path;
            Object Nothing = System.Reflection.Missing.Value;
            object readOnly = false;
            object isVisible = false;

            word_wrt = word_app.Documents.Open(ref strFileName, ref Nothing, ref readOnly,
                    ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                    ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing,
                    ref Nothing, ref Nothing, ref Nothing);
            word_wrt.Activate();
            //word_wrt.Paragraphs.Last.Range.Text = "test text" + "\n";//加个结束符(增加一段),否则再次插入的时候就成了替换.
            this.writeSammary();
            //保存
            word_wrt.Save();

               // test code
            this.buildTOC(saved_path, newSmry);
               // test code

            try
            {
                word_show.Quit(ref Nothing, ref Nothing, ref Nothing);
                word_app.Quit(ref Nothing, ref Nothing, ref Nothing);
            }
            catch (Exception)
            {
            }

            word_app = null;
            word_show = null;
        }
        private void insertarPrimerosCodigosDeBarra()
        {
            string path = @rutasEnModAdmin.RutaDePlantillas + "/temp_EtiquetaActual.docx";
            appWord = new Word.Application();
            appWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
            appWord.Visible = false;
            bool isOpen = false;
            FileStream stream = null;
            try
            {
                stream = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                isOpen = true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            if (isOpen)
            {
                Process[] proces = Process.GetProcessesByName("WINWORD");
                foreach (Process proc in proces)
                {
                    if (proc.MainWindowTitle == "")
                        proc.Kill();
                }
                MessageBox.Show("Existía un proceso abierto, y se ha cerrado correctamente. Favor de intentar nuevamente.", "Proceso Terminado", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                //return -1;
            }


            doc = appWord.Documents.Open(path);
            List<Word.Shape> lst = new List<Word.Shape>();

            foreach (Word.Shape sh in doc.Shapes)
            {
                if (sh.Type.ToString() == "msoPicture")
                {
                    while (sh.Name.Contains("\n"))
                        sh.Name = sh.Name.Replace("\n", "");
                    lst.Add(sh);
                }
            }
            this.generarPrimerosCodigosDeBarra();
            List<string> bcdUsados = new List<string>();
            foreach (string bcd in lista_camposCodBarr)
            {
                foreach (Control txt in gb_CamposAdicionales.Controls.OfType<TextBox>())
                {
                    if (!txt.Name.Contains(bcd.Replace("bcd", "")))
                        continue;
                    try
                    {
                        bcdUsados.Add(bcd);
                        float left, top, h, w;
                        string tempname = "";
                        List<Word.Range> ranges = new List<Word.Range>();
                        Word.Shape removed = null;
                        foreach (Word.Shape sh in lst)
                        {
                            if (sh.Name == bcd)
                            {
                                left = sh.Left;
                                top = sh.Top;
                                h = sh.Height;
                                w = sh.Width;
                                sh.ConvertToInlineShape();
                                foreach (Word.InlineShape s in doc.InlineShapes)
                                {
                                    if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                    {
                                        tempname = sh.Name;
                                        ranges.Add(s.Range);
                                        s.Delete();
                                        removed = sh;
                                    }
                                }
                                foreach (Word.Range r in ranges)
                                {
                                    r.InlineShapes.AddPicture(@rutasEnModAdmin.RutaDeTemp + "/" + bcd + ".jpg", Type.Missing, Type.Missing, Type.Missing);
                                }
                                Word.Shape pic;
                                foreach (Word.InlineShape s in doc.InlineShapes)
                                {
                                    if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                    {
                                        pic = s.ConvertToShape();
                                        pic.Name = tempname;
                                        pic.Top = top;
                                        pic.Left = left;
                                        pic.Height = h;
                                        pic.Width = w;
                                    }
                                }
                            }
                        }
                        lst.Remove(removed);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            doc.Save();
            doc.Saved = true;
            ((Microsoft.Office.Interop.Word._Document)doc).Close();
            foreach (string str in bcdUsados)
                lista_camposCodBarr.Remove(str);
        }