/// 
        /// 创建文档 
        ///
        public void CreateAWord()
        {
            //实例化word应用对象
            this._wordApplication = new Word.ApplicationClass();
            Object myNothing = System.Reflection.Missing.Value;

            this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing);
        }
Example #2
0
        public static void Convert(System.Web.UI.Page page, DocPair[] dps)
        {
            // Use for the parameter whose type are not known or
            // say Missing
            object Unknown =Type.Missing;

            //Creating the instance of Word Application
            Word.Application newApp = new Word.Application();

            for(int i=0;i<dps.Length;i++)
            {
                // specifying the Source & Target file names
                object Source=dps[i].SourceFile;
                object Target=dps[i].DestinationFile;

                try
                {
                    // Source document open here
                    // Additional Parameters are not known so that are
                    // set as a missing type
                    newApp.Documents.Open(ref Source,ref Unknown,
                        ref Unknown,ref Unknown,ref Unknown,
                        ref Unknown,ref Unknown,ref Unknown,
                        ref Unknown,ref Unknown,ref Unknown,
                        ref Unknown,ref Unknown,ref Unknown,
                        ref Unknown,ref Unknown);

                    // Specifying the format in which you want the output file
                    object format = Word.WdSaveFormat.wdFormatHTML;

                    //Changing the format of the document
                    newApp.ActiveDocument.SaveAs(ref Target,ref format,
                        ref Unknown,ref Unknown,ref Unknown,
                        ref Unknown,ref Unknown,ref Unknown,
                        ref Unknown,ref Unknown,ref Unknown,
                        ref Unknown,ref Unknown,ref Unknown,
                        ref Unknown,ref Unknown);
                }
                catch(Exception ex)
                {
                    //log

                    newApp.ActiveDocument.Close(ref Unknown,ref Unknown,ref Unknown);
                    page.Trace.Warn("Ex=" + ex.Message);
                }
                finally
                {
                    //log
                }
            }

            // for closing the application
            newApp.Quit(ref Unknown,ref Unknown,ref Unknown);
        }
        public static void FindAndReplaceY(
            object vkFind,
            object vkReplace,
            object vkNum,
            Word.Application vkWordApp,
            Word.Document vkMyDoc
            )
        {
            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object missing    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;
            object replaceAll = Word.WdReplace.wdReplaceAll;

            // Replace Word Document body
            //

            foreach (Word.Range myStoryRange in vkMyDoc.StoryRanges)
            {
                ReplaceRange(myStoryRange, vkMyDoc, vkWordApp, vkFind, vkReplace);
            }
        }
Example #4
0
        // ---------------------------------------------
        //
        // ---------------------------------------------
        /// <summary>
        /// Create client document and replace document tags
        /// </summary>
        /// <param name="fromFileName"></param>
        /// <param name="destinationFileName"></param>
        /// <param name="tag"></param>
        /// <param name="vkWordApp"></param>
        /// <returns></returns>
        public static ResponseStatus CopyDocument(
            object fromFileName,
            object destinationFileName,
            List <WordDocumentTasks.TagStructure> tag,
            Word.Application vkWordApp,
            IOutputMessage uioutput,
            string processName, string userID
            )
        {
            ResponseStatus ret = new ResponseStatus();

            object saveFile = destinationFileName;

            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;

            object vkMissing = System.Reflection.Missing.Value;

            // Let's make the word application not visible
            // vkWordApp.Visible = false;
            // vkWordApp.Activate();

            // Let's copy the document

            if (uioutput != null)
            {
                uioutput.AddOutputMessage("Copying file from: " + fromFileName + " to: " + destinationFileName, processName, userID);
            }

            File.Copy(fromFileName.ToString(), destinationFileName.ToString(), true);

            // Let's open the DESTINATION document

            Word.Document vkMyDoc;
            try
            {
                //vkMyDoc = vkWordApp.Documents.Open(
                //    ref destinationFileName, ref vkMissing, ref vkReadOnly,
                //    ref vkMissing, ref vkMissing, ref vkMissing,
                //    ref vkMissing, ref vkMissing, ref vkMissing,
                //    ref vkMissing, ref vkMissing, ref vkVisible );

                //vkMyDoc = vkWordApp.Documents.Open(
                //    ref destinationFileName, ref vkMissing, ref vkReadOnly,
                //    ref vkMissing, ref vkMissing, ref vkMissing,
                //    ref vkMissing, ref vkMissing, ref vkMissing,
                //    ref vkMissing, ref vkMissing, ref vkVisible );

                if (uioutput != null)
                {
                    uioutput.AddOutputMessage("Opening file: " + destinationFileName, processName, userID);
                }

                vkMyDoc = vkWordApp.Documents.Open(
                    FileName: destinationFileName,
                    ConfirmConversions: vkFalse,
                    ReadOnly: vkFalse,
                    AddToRecentFiles: vkMissing,
                    PasswordDocument: vkMissing,
                    PasswordTemplate: vkMissing,
                    Revert: vkMissing,
                    WritePasswordDocument: vkMissing,
                    WritePasswordTemplate: vkMissing,
                    Format: vkMissing,
                    Encoding: vkMissing,
                    Visible: vkFalse);
            }
            catch (Exception ex)
            {
                ret.ReturnCode = -1;
                ret.ReasonCode = 1000;
                ret.Message    = "Error opening file." + destinationFileName;
                ret.Contents   = ex;
                return(ret);
            }

            //
            // In case the file is still read-only...
            //
            if (uioutput != null)
            {
                uioutput.AddOutputMessage("Checking if file is read-only: " + destinationFileName, processName, userID);
            }
            if (vkMyDoc.ReadOnly)
            {
                uioutput.AddOutputMessage("(Word) File is Read-only contact support:  " + fromFileName, processName, userID);
                vkMyDoc.Close();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc);
                return(ret);
            }

            if (uioutput != null)
            {
                uioutput.AddOutputMessage("File is NOT read-only!!  " + destinationFileName, processName, userID);
            }

            if (uioutput != null)
            {
                uioutput.AddOutputMessage("Starting find and replace loop", processName, userID);
            }


            // 18/04/2013
            //
            vkMyDoc.Activate();

            foreach (var t in tag)
            {
                if (t.TagType == Helper.Utils.InformationType.FIELD || t.TagType == Helper.Utils.InformationType.VARIABLE)
                {
                    FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc);
                    // ReplaceProperty(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc);
                }
                else
                {
                    insertPicture(vkMyDoc, t.TagValue, t.Tag);
                }
            }

            // 15/03/2013
            // Force field update
            if (uioutput != null)
            {
                uioutput.AddOutputMessage("Force field updates.", processName, userID);
            }
            foreach (Word.Range myStoryRange in vkMyDoc.StoryRanges)
            {
                myStoryRange.Fields.Update();
            }

            // 24/10/2010 - Modificado quando troquei a referencia do Word
            //
            //vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update();
            //vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update();

            try
            {
                if (vkMyDoc.ReadOnly)
                {
                    if (uioutput != null)
                    {
                        uioutput.AddOutputMessage("(Word) File is Read-only contact support:  " + fromFileName, processName, userID);
                    }
                }
                else
                {
                    if (uioutput != null)
                    {
                        uioutput.AddOutputMessage("Saving file, it is no read-only.", processName, userID);
                    }

                    vkMyDoc.Save();
                }
            }
            catch (Exception ex)
            {
                if (uioutput != null)
                {
                    uioutput.AddOutputMessage("(Word) ERROR Saving in file:  " + fromFileName + " --- Message: " + ex.ToString(), processName, userID);
                }
            }

            // close the new document
            try
            {
                if (uioutput != null)
                {
                    uioutput.AddOutputMessage("Closing file", processName, userID);
                }
                vkMyDoc.Close(SaveChanges: vkTrue);
            }
            catch (Exception ex)
            {
                if (uioutput != null)
                {
                    uioutput.AddOutputMessage("(Word) ERROR Closing file:  " + fromFileName + " --- Message: " + ex.ToString(), processName, userID);
                }
            }



            // Trying to release COM object
            if (uioutput != null)
            {
                uioutput.AddOutputMessage("Releasing COM object", processName, userID);
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc);

            return(ret);
        }
Example #5
0
        // ---------------------------------------------
        //
        // ---------------------------------------------
        /// <summary>
        /// Create client document and replace document tags
        /// </summary>
        /// <param name="fromFileName"></param>
        /// <param name="destinationFileName"></param>
        /// <param name="tag"></param>
        /// <param name="vkWordApp"></param>
        /// <returns></returns>
        public static ResponseStatus CopyDocument(
            object fromFileName,
            object destinationFileName,
            List <WordDocumentTasks.TagStructure> tag,
            Word.Application vkWordApp,
            IOutputMessage uioutput
            )
        {
            ResponseStatus ret = new ResponseStatus();

            object saveFile = destinationFileName;

            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;

            object vkMissing = System.Reflection.Missing.Value;

            // Let's make the word application not visible
            // vkWordApp.Visible = false;
            // vkWordApp.Activate();

            // Let's copy the document
            File.Copy(fromFileName.ToString(), destinationFileName.ToString(), true);

            // Let's open the DESTINATION document

            Word.Document vkMyDoc;
            try
            {
                vkMyDoc = vkWordApp.Documents.Open(
                    ref destinationFileName, ref vkMissing, ref vkReadOnly,
                    ref vkMissing, ref vkMissing, ref vkMissing,
                    ref vkMissing, ref vkMissing, ref vkMissing,
                    ref vkMissing, ref vkMissing, ref vkVisible);
            }
            catch (Exception ex)
            {
                ret.ReturnCode = -1;
                ret.ReasonCode = 1000;
                ret.Message    = "Error copying file.";
                ret.Contents   = ex;
                return(ret);
            }

            foreach (var t in tag)
            {
                if (t.TagType == Utils.InformationType.FIELD || t.TagType == Utils.InformationType.VARIABLE)
                {
                    FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc);
                }
                else
                {
                    insertPicture(vkMyDoc, t.TagValue, t.Tag);
                }
            }

            // 24/10/2010 - Modificado quando troquei a referencia do Word
            //
            //vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update();
            //vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update();


            try
            {
                vkMyDoc.Save();
            }
            catch (Exception ex)
            {
                uioutput.AddOutputMessage("(Word) ERROR in file:  " + fromFileName + " --- Message: " + ex.ToString());
            }

            // close the new document
            vkMyDoc.Close();

            // Trying to release COM object
            System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc);

            return(ret);
        }
Example #6
0
        private void btn_start_Click(object sender, EventArgs e)
        {
            //check if template exists
            if (ofd_template.FileName.Length == 0)
            {
                MessageBox.Show("first choose a doc word");
                return;
            }

            // check empty table
            if (dgv_data.Rows.Count == 0)
            {
                MessageBox.Show("table is empty"); return;
            }

            //check row contents
            int base_vle = -1;

            for (int i = 0; i < dgv_data.Rows.Count - 1; i++)
            {
                if (base_vle == -1)
                {
                    base_vle = Convert.ToInt32(dgv_data.Rows[i].Cells[2].Value);
                }
                else
                {
                    int this_vle = Convert.ToInt32(dgv_data.Rows[i].Cells[2].Value);;
                    if (this_vle != base_vle)
                    {
                        MessageBox.Show("content rows are not same!");
                        return;
                    }
                }
            }

            Directory.CreateDirectory("export/");
            if (Directory.GetFiles("export/").Length > 0)
            {
                MessageBox.Show("first empty export folder"); return;
            }

            progressBar1.Maximum = base_vle;
            progressBar1.Value   = 0;
            for (int i = 0; i < base_vle; i++)
            {
                progressBar1.Value = i + 1;

                Word.Application wordApp = new Word.Application();

                Word.Document aDoc = null;


                wordApp.Visible = false;


                File.Copy(ofd_template.FileName, "export/" + i + ".docx");

                aDoc = wordApp.Documents.Open(System.Windows.Forms.Application.StartupPath + "/export/" + i + ".docx");


                aDoc.Activate();


                //  Call FindAndReplace()function for each change
                for (int ii = 0; ii < dgv_data.RowCount - 1; ii++)
                {
                    string   this_tag = dgv_data.Rows[ii].Cells[0].Value.ToString();
                    string[] contents = dic_data[this_tag];

                    this.FindAndReplace(wordApp, this_tag, contents[i]);
                }


                aDoc.Save();
                aDoc.Close();
            }
            MessageBox.Show("done!");
        }
Example #7
0
        public void InsertBT()
        {
            object missing = System.Reflection.Missing.Value;
            Word._Application app = new Word.Application();
            object path = RandomPath;
            //object fileName = @"\tmp\show.doc";
            // Word.Document doc = app.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);

            //doc.Activate();
            Word.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            doc.Activate();
            Word.Range range = doc.Paragraphs.Last.Range;//定位到段尾
            range.Text = "脚手架专项施工方案";
            range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//文字居中
            //object styleName = "标题 2";
               // range.set_Style(ref styleName);
            range.Font.Size = 20;
            range.Font.Name = "黑体";
            range.Font.Bold = 1;

            doc.SaveAs(ref path, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            app.Quit(ref missing, ref missing, ref missing);
            InsertFile(path.ToString());

            //range.InsertParagraphAfter();
        }
        /// <summary>
        /// Generate documents selected for a client
        /// </summary>
        /// <param name="clientID"></param>
        /// <param name="clientDocSetID"></param>
        /// <param name="uioutput"></param>
        /// <param name="overrideDocuments"></param>
        private void TBD_GenerateDocumentsForClient(
            int clientID, int clientDocSetID,
            string overrideDocuments)
        {
            uioutput.AddOutputMessage("Start time: " + System.DateTime.Now.ToString());

            // Instantiate Word
            //
            object vkFalse = false;

            Word.Application vkWordApp =
                new Word.Application();

            // Make it not visible
            vkWordApp.Visible = false;

            Excel.Application vkExcelApp = new Excel.Application();

            // Make it not visible
            vkExcelApp.Visible = false;

            // Get Metadata for client

            ReportMetadataList clientMetadata = new ReportMetadataList();

            clientMetadata.ListMetadataForClient(clientID);

            var ts = new List <WordDocumentTasks.TagStructure>();

            // Load variables/ metadata into memory
            //
            foreach (ReportMetadata metadata in clientMetadata.reportMetadataList)
            {
                // Retrieve value for the field selected
                //
                string value = metadata.GetValue();

                // If the field is not enabled, the program has to replace the value with spaces.
                //
                var valueOfTag = metadata.Enabled == 'Y' ? value : string.Empty;

                // When the field is an image and it is not enable, do not include the "No image" icon in the list
                //
                if (metadata.InformationType == Utils.InformationType.IMAGE && metadata.Enabled == 'N')
                {
                    continue;
                }

                ts.Add(new WordDocumentTasks.TagStructure()
                {
                    TagType  = metadata.InformationType,
                    Tag      = metadata.FieldCode,
                    TagValue = valueOfTag
                });
            }

            // Get Client Document Set Details
            // To get the source and destination folders
            ClientDocumentSet cds = new ClientDocumentSet();

            cds.Get(clientID, clientDocSetID);

            // Get List of documents for a client
            //
            var cdl = new ClientDocument();

            cdl.List(Utils.ClientID, Utils.ClientSetID);


            bool fileNotFound = false;
            // ---------------------------------------------------------------------------
            //    Check if source files exist before generation starts
            // ---------------------------------------------------------------------------
            int filecount = 0;

            foreach (scClientDocSetDocLink doco in cdl.clientDocSetDocLink)
            {
                #region File Inspection
                filecount++;

                // Ignore for now
                //
                if (doco.clientDocument.RecordType.Trim() == Utils.RecordType.FOLDER)
                {
                    string er = "Folder " + doco.document.Name;

                    uioutput.AddOutputMessage(er);
                    continue;
                }


                // Retrieve updated file name from source
                Document.Document document = new Document.Document();
                document.UID = doco.clientDocument.FKDocumentUID;
                document.Read();

                uioutput.AddOutputMessage("Inspecting file: " + document.UID + " === " + document.Name);

                // Client Document.SourceFileName is the name for the FCM File
                // Client Document.FileName is the client file name

                // Update client records with new file name
                //
                // Instantiate client document
                ClientDocument cd = new ClientDocument();
                cd.UID = doco.clientDocument.UID;
                // cd.FileName = document.FileName;
                cd.SourceFileName = document.FileName;
                cd.UpdateSourceFileName();

                // Update memory with latest file name
                // doco.clientDocument.SourceFileName = cd.FileName;
                doco.clientDocument.SourceFileName = cd.SourceFileName;

                string sourceFileLocationName = Utils.getFilePathName(
                    doco.clientDocument.SourceLocation,
                    doco.clientDocument.SourceFileName);

                // check if source folder/ file exists
                if (string.IsNullOrEmpty(doco.clientDocument.Location))
                {
                    MessageBox.Show("Document Location is empty.");
                    return;
                }

                if (string.IsNullOrEmpty(doco.clientDocument.FileName))
                {
                    MessageBox.Show("File Name is empty.");
                    return;
                }

                if (!File.Exists(sourceFileLocationName))
                {
                    string er = "File does not exist " +
                                sourceFileLocationName + " - File Name: " + doco.clientDocument.SourceFileName;

                    uioutput.AddOutputMessage(er);
                    uioutput.AddErrorMessage(er);
                    fileNotFound = true;
                    continue;
                }
                #endregion File Inspection
            }


            // Can't proceed if file not found
            if (fileNotFound)
            {
                return;
            }

            // Check if destination folder exists
            //
            if (string.IsNullOrEmpty(cds.Folder))
            {
                MessageBox.Show("Destination folder not set. Generation stopped.");
                return;
            }
            string PhysicalCDSFolder = Utils.GetPathName(cds.Folder);
            if (!Directory.Exists(PhysicalCDSFolder))
            {
                Directory.CreateDirectory(PhysicalCDSFolder);
            }


            // -----------------------------------------------------------------------
            //                          Generation starts here
            // -----------------------------------------------------------------------

            fileprocessedcount  = 0;
            valueForProgressBar = 0;
            startTime           = System.DateTime.Now.ToString();
            estimated           = System.DateTime.Now.AddSeconds(5 * filecount);

            var previousTime = System.DateTime.Now;
            var agora        = System.DateTime.Now;

            foreach (scClientDocSetDocLink doco in cdl.clientDocSetDocLink)
            {
                fileprocessedcount++;
                valueForProgressBar = (fileprocessedcount / filecount) * 100;

                // Get current time
                agora = System.DateTime.Now;

                // Get the time it took to process one file
                TimeSpan span = agora.Subtract(previousTime);

                // Calculate the estimated time to complete
                estimated = System.DateTime.Now.AddSeconds(span.TotalSeconds * filecount);

                uioutput.UpdateProgressBar(valueForProgressBar, estimated);

                previousTime = System.DateTime.Now;

                // Retrieve latest version
                //
                Document.Document document = new Document.Document();
                document.UID = doco.clientDocument.FKDocumentUID;
                document.Read();


                uioutput.AddOutputMessage(">>> Generating file: " + document.UID + " === " + document.SimpleFileName);


                string sourceFileLocationName = Utils.getFilePathName(
                    doco.clientDocument.SourceLocation,
                    doco.clientDocument.SourceFileName);

                // This is the client file name
                //
                string clientFileLocation = cds.Folder.Trim() +
                                            doco.clientDocument.Location.Trim();

                string clientFileLocationName = Utils.getFilePathName(
                    clientFileLocation,
                    doco.clientDocument.FileName.Trim());



                // Check if file destination directory exists
                //
                string PhysicalLocation = Utils.GetPathName(clientFileLocation);

                if (string.IsNullOrEmpty(PhysicalLocation))
                {
                    string er = "Location is empty " + doco.clientDocument.Location + "\n" +
                                "File Name: " + doco.document.Name;

                    uioutput.AddOutputMessage(er);
                    continue;
                }

                if (!Directory.Exists(PhysicalLocation))
                {
                    Directory.CreateDirectory(PhysicalLocation);
                }

                if (File.Exists(clientFileLocationName))
                {
                    // Proceed but report in list
                    //
                    if (overrideDocuments == "Yes")
                    {
                        // Delete file
                        try
                        {
                            File.Delete(clientFileLocationName);
                            uioutput.AddOutputMessage("File replaced " +
                                                      document.SimpleFileName);
                        }
                        catch (Exception)
                        {
                            uioutput.AddOutputMessage("Error deleting file " +
                                                      document.SimpleFileName);
                            uioutput.AddErrorMessage("Error deleting file " +
                                                     document.SimpleFileName);

                            continue;
                        }
                    }
                    else
                    {
                        uioutput.AddOutputMessage("File already exists " +
                                                  document.SimpleFileName);
                        continue;
                    }
                }

                // Copy and fix file
                //

                // Word Documents
                //
                if (doco.clientDocument.RecordType.Trim() == Utils.RecordType.FOLDER)
                {
                    // Update file - set as GENERATED.
                    //

                    uioutput.AddOutputMessage("FOLDER: " + doco.clientDocument.SourceFileName);
                }
                else
                {
                    // If is is not a folder, it must be a regular file.
                    // Trying to copy it as well...
                    //

                    var currentDocumentPath = Path.GetExtension(doco.clientDocument.FileName);

                    if (doco.clientDocument.DocumentType == Utils.DocumentType.WORD)
                    {
                        #region Word
                        // ------------------------------------------------------------------------
                        // ------------------------------------------------------------------------
                        // Generate Document and replace tag values in new document generated
                        // ------------------------------------------------------------------------
                        // ------------------------------------------------------------------------
                        var results = WordDocumentTasks.CopyDocument(sourceFileLocationName, clientFileLocationName, ts, vkWordApp, uioutput);
                        if (results.ReturnCode < 0)
                        {
                            // Error has occurred
                            //
                            var er = (System.Exception)results.Contents;
                            uioutput.AddOutputMessage("ERROR: " + er.ToString());
                            uioutput.AddErrorMessage("ERROR: " + er.ToString());

                            continue;
                        }


                        //
                        // Instantiate client document
                        ClientDocument cd = new ClientDocument();
                        cd.UID = doco.clientDocument.UID;


                        // Update file - set as GENERATED.
                        //

                        cd.SetGeneratedFlagVersion('Y', document.IssueNumber);

                        uioutput.AddOutputMessage("Document generated: " +
                                                  clientFileLocationName);

                        #endregion Word
                    }
                    else if (doco.clientDocument.DocumentType == Utils.DocumentType.EXCEL)
                    {
                        // ------------------------------------------------------------------------
                        // ------------------------------------------------------------------------
                        // Generate Document and replace tag values in new document generated
                        // ------------------------------------------------------------------------
                        // ------------------------------------------------------------------------

                        ExcelSpreadsheetTasks.CopyDocument(sourceFileLocationName, clientFileLocationName, ts, vkExcelApp, uioutput);

                        //
                        // Instantiate client document
                        ClientDocument cd = new ClientDocument();
                        cd.UID = doco.clientDocument.UID;


                        // Update file - set as GENERATED.
                        //

                        cd.SetGeneratedFlagVersion('Y', document.IssueNumber);

                        uioutput.AddOutputMessage("Document generated: " +
                                                  clientFileLocationName);
                    }
                    else
                    {
                        File.Copy(sourceFileLocationName, clientFileLocationName);

                        uioutput.AddOutputMessage("File copied but not modified: " +
                                                  Path.GetExtension(doco.clientDocument.FileName) + " == File: " + clientFileLocationName);
                    }
                }
            }

            // close word application
            vkWordApp.Quit(ref vkFalse, ref vkFalse, ref vkFalse);
            vkExcelApp.Quit();

            uioutput.AddOutputMessage("End time: " + System.DateTime.Now.ToString());
        }
Example #9
0
        /// <summary>
        /// Find and replace words in document
        /// </summary>
        /// <param name="vkFind"></param>
        /// <param name="vkReplace"></param>
        /// <param name="vkNum"></param>
        /// <param name="vkWordApp"></param>
        /// <param name="vkMyDoc"></param>
        public static void FindAndReplace(
            object vkFind,
            object vkReplace,
            object vkNum,
            Word.Application vkWordApp,
            Word.Document vkMyDoc
            )
        {
            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object missing    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;
            object replaceAll = Word.WdReplace.wdReplaceAll;

            if (vkMyDoc == null)
            {
                return;
            }
            if (vkWordApp == null)
            {
                return;
            }

            // 12.01.2013
            // Allow spaces in replace variable - it will cause the system to clean-up unwanted variables.
            //
            //if (vkReplace.ToString().Trim().Length == 0)
            //{
            //    return;
            //}

            if (vkFind.ToString().Trim().Length == 0)
            {
                return;
            }

            string findText    = vkFind.ToString().Trim();
            string replaceText = vkReplace.ToString().Trim();

            // In theory not needed...
            //

            //foreach (Word.Comment comment in vkMyDoc.Comments)
            //{
            //    ReplaceRange(comment.Range, vkMyDoc, vkWordApp, findText, replaceText);
            //}

            //foreach (Word.HeaderFooter header in vkMyDoc.Sections.Last.Headers)
            //{
            //    ReplaceRange(header.Range, vkMyDoc, vkWordApp, findText, replaceText);
            //}

            //foreach (Word.HeaderFooter footer in vkMyDoc.Sections.Last.Footers)
            //{
            //    ReplaceRange(footer.Range, vkMyDoc, vkWordApp, findText, replaceText);
            //}
            // End of changes on 07/01/2013
            // I have enabled the code above to see if it work for the IMS document
            //

            foreach (Word.Shape shp in vkMyDoc.Shapes)
            {
                if (shp.TextFrame.HasText < 0)
                {
                    ReplaceRange(shp.TextFrame.TextRange, vkMyDoc, vkWordApp, findText, replaceText);
                }
            }

            foreach (Word.Range myStoryRange in vkMyDoc.StoryRanges)
            {
                ReplaceRange(myStoryRange, vkMyDoc, vkWordApp, findText, replaceText);

                foreach (Word.InlineShape shp in myStoryRange.InlineShapes)
                {
                    ReplaceRange(shp.Range, vkMyDoc, vkWordApp, findText, replaceText);
                }

                // 23.02.2013
                // This is to try to address header in different sections
                // It works!
                //
                foreach (Word.HeaderFooter header in myStoryRange.Sections.Last.Headers)
                {
                    ReplaceRange(header.Range, vkMyDoc, vkWordApp, findText, replaceText);
                }
                foreach (Word.HeaderFooter footer in myStoryRange.Sections.Last.Footers)
                {
                    ReplaceRange(footer.Range, vkMyDoc, vkWordApp, findText, replaceText);
                }
            }
        }
Example #10
0
File: Form1.cs Project: a-vodka/ics
 public Form1()
 {
     InitializeComponent();
     excelApp = new Excel.Application();
     wordApp  = new Word.Application();
 }
Example #11
0
        private void CheckSpelling()
        {
            TextDocumentHandler handler = new TextDocumentHandler(this.dte);

            if (handler.HasNonEmptySelection)
            {
                try
                {
                    // Launch Word.
                    Word._Application wordApp = new Word.Application();

                    // Add a document.
                    Word._Document wordDoc = wordApp.Documents.Add();

                    // Clear current contents.
                    Word.Range range = wordApp.Selection.Range;
                    range.WholeStory();
                    range.Delete();
                    range = null;

                    // Add the text the user selected.
                    wordApp.Selection.Text = handler.SelectedText;

                    // Show it
                    wordApp.Visible = true;
                    wordApp.Activate();
                    wordDoc.Activate();

                    // Check spelling
                    wordDoc.CheckSpelling();

                    // Get the edited text back
                    wordApp.Selection.WholeStory();
                    string newText = wordApp.Selection.Text;

                    // Word always adds an extra CR, so strip that off.
                    // Also it converts all LFs to CRs, so change
                    // that back.
                    if (!string.IsNullOrEmpty(newText))
                    {
                        if (newText.EndsWith("\r"))
                        {
                            newText = newText.Substring(0, newText.Length - 1);
                        }

                        newText = newText.Replace("\r", "\r\n");
                    }

                    handler.SetSelectedTextIfUnchanged(newText, "Check Spelling");

                    // Tell the doc and Word to go away.
                    object saveChanges = false;
                    wordDoc.Close(ref saveChanges);
                    wordApp.Visible = false;
                    wordApp.Quit();
                }
                catch (COMException ex)
                {
                    // If we get REGDB_E_CLASSNOTREG, then Word probably isn't installed.
                    const uint REGDB_E_CLASSNOTREG = 0x80040154;
                    if (unchecked ((uint)ex.ErrorCode) == REGDB_E_CLASSNOTREG)
                    {
                        this.package.ShowMessageBox(
                            "Microsoft Word is required in order to check spelling, but it isn't available.\r\n\r\nDetails:\r\n" + ex.Message,
                            true);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Example #12
0
        public static bool WordImportUmowa(string fileName, ref string rodzaj, ref string numer, ref string konto, ref string osoba)
        {
            Word._Application wordApp = new Word.Application();
            wordApp.Visible        = true;
            wordApp.ScreenUpdating = true;

            object wdStory  = Word.WdUnits.wdStory;
            object wdLine   = Word.WdUnits.wdLine;
            object wdMove   = Word.WdMovementType.wdMove;
            object count1   = (object)1;
            object wdExtend = Word.WdMovementType.wdExtend;

            try
            {
                Word._Document objDoc     = null;
                object         objDocName = fileName;
                objDoc = WordOpen(wordApp, objDocName);

                string text = "";
                int    granica;
                bool   isend = false;

                granica = 0;
                while (true)//while szukaj kopert
                {
                    wordApp.Selection.HomeKey(ref wdLine, ref wdMove);
                    wordApp.Selection.EndKey(ref wdLine, ref wdExtend);

                    if (++granica > 30)
                    {
                        isend = true;
                    }

                    //if(wordApp.Selection.End == ((Word.Range)objDoc.Range).End)
                    //  isend = true;

                    text = wordApp.Selection.Text.Trim();

                    if (text.Contains("UMOWA"))
                    {
                        if (text.Contains("DZIE£O"))
                        {
                            rodzaj = "Umowa o dzie³o";
                        }
                        else if (text.Contains("ZLECENIE"))
                        {
                            rodzaj = "Umowa na zlecenie";
                            if (text.Contains("student"))
                            {
                                rodzaj = "Umowa na zlecenie - student";
                            }
                        }
                        //numer = text.Substring(text.Length - 14);
                        numer = text;
                    }
                    else if (text.Contains("konta"))
                    {
                        konto = text;
                    }

                    if (text.Contains(osoba))
                    {
                        osoba = text;
                    }

                    wordApp.Selection.HomeKey(ref wdLine, ref wdMove);
                    wordApp.Selection.MoveDown(ref wdLine, ref count1, ref wdMove);

                    if (isend)
                    {
                        break;
                    }
                }//end while szukaj kopert

                objDoc.Close(ref ObjMissing, ref ObjMissing, ref ObjMissing);
            }
            catch (COMException)
            {
                return(false);
            }
            finally
            {
                wordApp.Quit(ref ObjMissing, ref ObjMissing, ref ObjMissing);
            }
            return(true);
        }
 public void close()
 {
     this._wordApplication = null;
     this._wordDocument = null;
 }
Example #14
0
        // ----------------------------------------------------
        //         Find and replace words in MS Word
        // ----------------------------------------------------
        public static void FindAndReplace(
            object vkFind,
            object vkReplace,
            object vkNum,
            Word.Application vkWordApp,
            Word.Document vkMyDoc
            )
        {
            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object missing    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;
            object replaceAll = Word.WdReplace.wdReplaceAll;

            // Replace Word Document body
            //

            // 05/09/2010 - Testando a passagem de paramentros com nome do parametro... nao remover codigo abaixo.

            // Working... Forward = false;

            //vkWordApp.Selection.Find.Execute(
            //    ref vkFind, ref vkFalse, ref vkFalse,
            //    ref vkFalse, ref vkFalse, ref vkFalse,
            //    ref vkTrue, ref vkNum, ref vkFalse,
            //    ref vkReplace, ref vkDynamic, ref vkFalse,
            //    ref vkFalse, ref vkFalse, ref vkFalse );

            //vkWordApp.Selection.Find.Execute(
            //          FindText: vkFind,
            //          ReplaceWith: vkReplace,
            //          MatchCase: vkFalse,
            //          MatchWholeWord: vkTrue,
            //          MatchAllWordForms: vkTrue,
            //          Replace: vkDynamic);

            vkWordApp.Selection.Find.Execute(
                MatchCase: vkFalse,
                MatchWholeWord: vkTrue,
                MatchWildcards: vkFalse,
                MatchSoundsLike: vkFalse,
                MatchAllWordForms: vkFalse,
                Forward: vkFalse,
                Wrap: vkNum,
                Format: vkFalse,
                FindText: vkFind,
                ReplaceWith: vkReplace,
                Replace: vkDynamic,
                MatchKashida: vkFalse,
                MatchDiacritics: vkFalse,
                MatchAlefHamza: vkFalse,
                MatchControl: vkFalse);

            // Replace in the primary header/ footer
            //
            //vkMyDoc.Sections.Item(1).Headers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute(
            //    ref vkFind, ref vkFalse, ref vkFalse,
            //    ref vkFalse, ref vkFalse, ref vkFalse,
            //    ref vkTrue, ref vkNum, ref vkFalse,
            //    ref vkReplace, ref vkDynamic, ref vkFalse,
            //    ref vkFalse, ref vkFalse, ref vkFalse);

            vkMyDoc.Sections.Item(1).Headers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute(
                FindText: vkFind,
                MatchCase: vkFalse,
                MatchWholeWord: vkFalse,
                MatchWildcards: vkFalse,
                MatchSoundsLike: vkFalse,
                MatchAllWordForms: vkFalse,
                Forward: vkFalse,
                Wrap: vkNum,
                Format: vkFalse,
                ReplaceWith: vkReplace,
                Replace: vkDynamic,
                MatchKashida: vkFalse,
                MatchDiacritics: vkFalse,
                MatchAlefHamza: vkFalse,
                MatchControl: vkFalse);

            vkMyDoc.Sections.Item(1).Headers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range.Find.Execute(
                FindText: vkFind,
                MatchCase: vkFalse,
                MatchWholeWord: vkFalse,
                MatchWildcards: vkFalse,
                MatchSoundsLike: vkFalse,
                MatchAllWordForms: vkFalse,
                Forward: vkFalse,
                Wrap: vkNum,
                Format: vkFalse,
                ReplaceWith: vkReplace,
                Replace: vkDynamic,
                MatchKashida: vkFalse,
                MatchDiacritics: vkFalse,
                MatchAlefHamza: vkFalse,
                MatchControl: vkFalse);

            vkMyDoc.Sections.Item(1).Headers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages).Range.Find.Execute(
                FindText: vkFind,
                MatchCase: vkFalse,
                MatchWholeWord: vkFalse,
                MatchWildcards: vkFalse,
                MatchSoundsLike: vkFalse,
                MatchAllWordForms: vkFalse,
                Forward: vkFalse,
                Wrap: vkNum,
                Format: vkFalse,
                ReplaceWith: vkReplace,
                Replace: vkDynamic,
                MatchKashida: vkFalse,
                MatchDiacritics: vkFalse,
                MatchAlefHamza: vkFalse,
                MatchControl: vkFalse);


            // Replace in the first page footer
            //
            //vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute(
            //    ref vkFind, ref vkFalse, ref vkFalse,
            //    ref vkFalse, ref vkFalse, ref vkFalse,
            //    ref vkTrue, ref vkNum, ref vkFalse,
            //    ref vkReplace, ref vkDynamic, ref vkFalse,
            //    ref vkFalse, ref vkFalse, ref vkFalse );


            vkMyDoc.Sections.Item(1).Footers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute(
                FindText: vkFind,
                MatchCase: vkFalse,
                MatchWholeWord: vkFalse,
                MatchWildcards: vkFalse,
                MatchSoundsLike: vkFalse,
                MatchAllWordForms: vkFalse,
                Forward: vkFalse,
                Wrap: vkNum,
                Format: vkFalse,
                ReplaceWith: vkReplace,
                Replace: vkDynamic,
                MatchKashida: vkFalse,
                MatchDiacritics: vkFalse,
                MatchAlefHamza: vkFalse,
                MatchControl: vkFalse);


            vkMyDoc.Sections.Item(1).Footers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range.Find.Execute(
                FindText: vkFind,
                MatchCase: vkFalse,
                MatchWholeWord: vkFalse,
                MatchWildcards: vkFalse,
                MatchSoundsLike: vkFalse,
                MatchAllWordForms: vkFalse,
                Forward: vkFalse,
                Wrap: vkNum,
                Format: vkFalse,
                ReplaceWith: vkReplace,
                Replace: vkDynamic,
                MatchKashida: vkFalse,
                MatchDiacritics: vkFalse,
                MatchAlefHamza: vkFalse,
                MatchControl: vkFalse);

            vkMyDoc.Sections.Item(1).Footers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages).Range.Find.Execute(
                FindText: vkFind,
                MatchCase: vkFalse,
                MatchWholeWord: vkFalse,
                MatchWildcards: vkFalse,
                MatchSoundsLike: vkFalse,
                MatchAllWordForms: vkFalse,
                Forward: vkFalse,
                Wrap: vkNum,
                Format: vkFalse,
                ReplaceWith: vkReplace,
                Replace: vkDynamic,
                MatchKashida: vkFalse,
                MatchDiacritics: vkFalse,
                MatchAlefHamza: vkFalse,
                MatchControl: vkFalse);
        }
Example #15
0
        //// ----------------------------------------------------
        ////         Find and replace words in MS Word
        //// ----------------------------------------------------
        //public static void FindAndReplaceFIRST(
        //                           object vkFind,
        //                           object vkReplace,
        //                           object vkNum,
        //            Word.Application vkWordApp,
        //                    Word.Document vkMyDoc
        //    )
        //{
        //    object vkReadOnly = false;
        //    object vkVisible = true;
        //    object vkFalse = false;
        //    object missing = false;
        //    object vkTrue = true;
        //    object vkDynamic = 2;
        //    object replaceAll = Word.WdReplace.wdReplaceAll;

        //    if (vkMyDoc == null)
        //    {
        //        return;
        //    }
        //    if (vkWordApp == null)
        //    {
        //        return;
        //    }
        //    if (vkReplace.ToString().Trim().Length == 0)
        //    {
        //        return;
        //    }
        //    if (vkFind.ToString().Trim().Length == 0)
        //    {
        //        return;
        //    }


        //    // Replace Word Document body
        //    //

        //    // 05/09/2010 - Testando a passagem de paramentros com nome do parametro... nao remover codigo abaixo.

        //    // Working... Forward = false;

        //    //vkWordApp.Selection.Find.Execute(
        //    //    ref vkFind, ref vkFalse, ref vkFalse,
        //    //    ref vkFalse, ref vkFalse, ref vkFalse,
        //    //    ref vkTrue, ref vkNum, ref vkFalse,
        //    //    ref vkReplace, ref vkDynamic, ref vkFalse,
        //    //    ref vkFalse, ref vkFalse, ref vkFalse );

        //    //vkWordApp.Selection.Find.Execute(
        //    //          FindText: vkFind,
        //    //          ReplaceWith: vkReplace,
        //    //          MatchCase: vkFalse,
        //    //          MatchWholeWord: vkTrue,
        //    //          MatchAllWordForms: vkTrue,
        //    //          Replace: vkDynamic);

        //    vkWordApp.Selection.Find.Execute(
        //        MatchCase: vkFalse,
        //        MatchWholeWord: vkTrue,
        //        MatchWildcards: vkFalse,
        //        MatchSoundsLike: vkFalse,
        //        MatchAllWordForms: vkFalse,
        //        Forward: vkFalse,
        //        Wrap: vkNum,
        //        Format: vkFalse,
        //        FindText: vkFind,
        //        ReplaceWith: vkReplace,
        //        Replace: vkDynamic,
        //        MatchKashida: vkFalse,
        //        MatchDiacritics: vkFalse,
        //        MatchAlefHamza: vkFalse,
        //        MatchControl: vkFalse );

        //    // Replace in the primary header/ footer
        //    //
        //    //vkMyDoc.Sections.Item(1).Headers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute(
        //    //    ref vkFind, ref vkFalse, ref vkFalse,
        //    //    ref vkFalse, ref vkFalse, ref vkFalse,
        //    //    ref vkTrue, ref vkNum, ref vkFalse,
        //    //    ref vkReplace, ref vkDynamic, ref vkFalse,
        //    //    ref vkFalse, ref vkFalse, ref vkFalse);

        //    vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Find.Execute(
        //        FindText: vkFind,
        //        MatchCase: vkFalse,
        //        MatchWholeWord: vkFalse,
        //        MatchWildcards: vkFalse,
        //        MatchSoundsLike: vkFalse,
        //        MatchAllWordForms: vkFalse,
        //        Forward: vkFalse,
        //        Wrap: vkNum,
        //        Format: vkFalse,
        //        ReplaceWith: vkReplace,
        //        Replace: vkDynamic,
        //        MatchKashida: vkFalse,
        //        MatchDiacritics: vkFalse,
        //        MatchAlefHamza: vkFalse,
        //        MatchControl: vkFalse );

        //    vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range.Find.Execute(
        //        FindText: vkFind,
        //        MatchCase: vkFalse,
        //        MatchWholeWord: vkFalse,
        //        MatchWildcards: vkFalse,
        //        MatchSoundsLike: vkFalse,
        //        MatchAllWordForms: vkFalse,
        //        Forward: vkFalse,
        //        Wrap: vkNum,
        //        Format: vkFalse,
        //        ReplaceWith: vkReplace,
        //        Replace: vkDynamic,
        //        MatchKashida: vkFalse,
        //        MatchDiacritics: vkFalse,
        //        MatchAlefHamza: vkFalse,
        //        MatchControl: vkFalse );

        //    vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages).Range.Find.Execute(
        //        FindText: vkFind,
        //        MatchCase: vkFalse,
        //        MatchWholeWord: vkFalse,
        //        MatchWildcards: vkFalse,
        //        MatchSoundsLike: vkFalse,
        //        MatchAllWordForms: vkFalse,
        //        Forward: vkFalse,
        //        Wrap: vkNum,
        //        Format: vkFalse,
        //        ReplaceWith: vkReplace,
        //        Replace: vkDynamic,
        //        MatchKashida: vkFalse,
        //        MatchDiacritics: vkFalse,
        //        MatchAlefHamza: vkFalse,
        //        MatchControl: vkFalse );


        //    // Replace in the first page footer
        //    //
        //    //vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute(
        //    //    ref vkFind, ref vkFalse, ref vkFalse,
        //    //    ref vkFalse, ref vkFalse, ref vkFalse,
        //    //    ref vkTrue, ref vkNum, ref vkFalse,
        //    //    ref vkReplace, ref vkDynamic, ref vkFalse,
        //    //    ref vkFalse, ref vkFalse, ref vkFalse );


        //    vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute(
        //        FindText: vkFind,
        //        MatchCase: vkFalse,
        //        MatchWholeWord: vkFalse,
        //        MatchWildcards: vkFalse,
        //        MatchSoundsLike: vkFalse,
        //        MatchAllWordForms: vkFalse,
        //        Forward: vkFalse,
        //        Wrap: vkNum,
        //        Format: vkFalse,
        //        ReplaceWith: vkReplace,
        //        Replace: vkDynamic,
        //        MatchKashida: vkFalse,
        //        MatchDiacritics: vkFalse,
        //        MatchAlefHamza: vkFalse,
        //        MatchControl: vkFalse );


        //    vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage ).Range.Find.Execute(
        //        FindText: vkFind,
        //        MatchCase: vkFalse,
        //        MatchWholeWord: vkFalse,
        //        MatchWildcards: vkFalse,
        //        MatchSoundsLike: vkFalse,
        //        MatchAllWordForms: vkFalse,
        //        Forward: vkFalse,
        //        Wrap: vkNum,
        //        Format: vkFalse,
        //        ReplaceWith: vkReplace,
        //        Replace: vkDynamic,
        //        MatchKashida: vkFalse,
        //        MatchDiacritics: vkFalse,
        //        MatchAlefHamza: vkFalse,
        //        MatchControl: vkFalse );

        //    vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages ).Range.Find.Execute(
        //        FindText: vkFind,
        //        MatchCase: vkFalse,
        //        MatchWholeWord: vkFalse,
        //        MatchWildcards: vkFalse,
        //        MatchSoundsLike: vkFalse,
        //        MatchAllWordForms: vkFalse,
        //        Forward: vkFalse,
        //        Wrap: vkNum,
        //        Format: vkFalse,
        //        ReplaceWith: vkReplace,
        //        Replace: vkDynamic,
        //        MatchKashida: vkFalse,
        //        MatchDiacritics: vkFalse,
        //        MatchAlefHamza: vkFalse,
        //        MatchControl: vkFalse );

        //}



        /// <summary>
        /// Replace inside the range
        /// </summary>
        /// <param name="range"></param>
        /// <param name="wordDocument"></param>
        /// <param name="wordApp"></param>
        /// <param name="findText"></param>
        /// <param name="replaceText"></param>
        private static void ReplaceRange(Word.Range range, Word.Document wordDocument, Word.Application wordApp, object findText, object replaceText)
        {
            object missing = System.Reflection.Missing.Value;

            wordDocument.Activate();

            //object item = Word.WdGoToItem.wdGoToPage;
            //object whichItem = Word.WdGoToDirection.wdGoToFirst;
            //wordDocument.GoTo(ref item, ref whichItem, ref missing, ref missing);

            //object forward = true;
            //object replaceAll = Word.WdReplace.wdReplaceAll;
            //object matchAllWord = true;

            //range.Find.Execute(ref findText, ref missing, ref matchAllWord,
            //    ref missing, ref missing, ref missing, ref forward,
            //    ref missing, ref missing, ref replaceText, ref replaceAll,
            //    ref missing, ref missing, ref missing, ref missing);

            range.Find.ClearFormatting();
            range.Find.Replacement.ClearFormatting();

            object vkTrue  = true;
            object vkFalse = false;

            range.Find.Execute(
                FindText: findText,
                MatchCase: vkFalse,
                MatchWholeWord: vkTrue,
                MatchWildcards: vkFalse,
                MatchSoundsLike: vkFalse,
                MatchAllWordForms: vkFalse,
                Forward: vkFalse,
                Wrap: 1,
                Format: vkFalse,
                ReplaceWith: replaceText,
                Replace: 2,
                MatchKashida: vkFalse,
                MatchDiacritics: vkFalse,
                MatchAlefHamza: vkFalse,
                MatchControl: vkFalse);
        }
 public Form1()
 {
     InitializeComponent();
     objWord = new Word.Application();
     // ...
 }
Example #17
0
        // ---------------------------------------------
        //             Copy Documents
        // ---------------------------------------------
        public static object CopyDocumentReplaceContents(
            object fromFileName,
            object destinationFileName,
            List <WordDocumentTasks.TagStructure> tag
            )
        {
            Word.Application vkWordApp =
                new Word.Application();

            object saveFile = destinationFileName;

            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;


            object vkMissing = System.Reflection.Missing.Value;

            // Let's make the word application visible
            vkWordApp.Visible = true;
            vkWordApp.Activate();

            // Let's open the document
            Word.Document vkMyDoc = vkWordApp.Documents.Open(
                ref fromFileName, ref vkMissing, ref vkReadOnly,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkVisible);

            // Let's create a new document
            Word.Document vkNewDoc = vkWordApp.Documents.Add(
                ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkVisible);

            // Select and Copy from the original document
            vkMyDoc.Select();
            vkWordApp.Selection.Copy();

            // Paste into new document as unformatted text
            vkNewDoc.Select();
            vkWordApp.Selection.PasteSpecial(ref vkMissing, ref vkFalse,
                                             ref vkMissing, ref vkFalse, ref vkDynamic,
                                             ref vkMissing, ref vkMissing);

            // Save the new document
            vkNewDoc.SaveAs(ref saveFile, ref vkMissing,
                            ref vkMissing, ref vkMissing, ref vkMissing,
                            ref vkMissing, ref vkMissing, ref vkMissing,
                            ref vkMissing, ref vkMissing, ref vkMissing);


            // Copy elements
            // FromString => toString
            //
            // underdevelopment
            //
            vkNewDoc.Select();

            foreach (var t in tag)
            {
                FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc);
            }

            vkNewDoc.Save();

            // close the new document
            vkNewDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing);

            // close the original document
            vkMyDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing);

            // close word application
            vkWordApp.Quit(ref vkFalse, ref vkMissing, ref vkMissing);

            return(saveFile);
        }
Example #18
0
        private void butPrint_Click(object sender, System.EventArgs e)
        {
#if DISABLE_MICROSOFT_OFFICE
            MessageBox.Show(this, "This version of Open Dental does not support Microsoft Word.");
            return;
#endif
            if (listLetters.SelectedIndex == -1)
            {
                MsgBox.Show(this, "Please select a letter first.");
                return;
            }
            LetterMerge letterCur    = ListForCat[listLetters.SelectedIndex];
            string      templateFile = ODFileUtils.CombinePaths(PrefC.GetString(PrefName.LetterMergePath), letterCur.TemplateName);
            string      dataFile     = ODFileUtils.CombinePaths(PrefC.GetString(PrefName.LetterMergePath), letterCur.DataFileName);
            if (!File.Exists(templateFile))
            {
                MsgBox.Show(this, "Template file does not exist.");
                return;
            }
            PrintDocument pd = new PrintDocument();
            if (!PrinterL.SetPrinter(pd, PrintSituation.Default))
            {
                return;
            }
            if (!CreateDataFile(dataFile, letterCur))
            {
                return;
            }
            Word.MailMerge wrdMailMerge;
            //Create an instance of Word.
            Word.Application WrdApp = LetterMerges.WordApp;
            //Open a document.
            Object oName = templateFile;
            wrdDoc = WrdApp.Documents.Open(ref oName, 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);
            wrdDoc.Select();
            wrdMailMerge = wrdDoc.MailMerge;
            //Attach the data file.
            wrdDoc.MailMerge.OpenDataSource(dataFile, 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 oMissing);
            wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToPrinter;
            //WrdApp.ActivePrinter=pd.PrinterSettings.PrinterName;
            //replaced with following 4 lines due to MS bug that changes computer default printer
            object   oWBasic   = WrdApp.WordBasic;
            object[] oWBValues = new object[] { pd.PrinterSettings.PrinterName, 1 };
            String[] sWBNames  = new String[] { "Printer", "DoNotSetAsSysDefault" };
            oWBasic.GetType().InvokeMember("FilePrintSetup", BindingFlags.InvokeMethod, null, oWBasic, oWBValues, null, null, sWBNames);
            wrdMailMerge.Execute(ref oFalse);
            //Close the original form document since just one record.
            wrdDoc.Saved = true;
            wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);
            //At this point, Word remains open with no documents.
            WrdApp.WindowState = Word.WdWindowState.wdWindowStateMinimize;
            wrdMailMerge       = null;
            wrdDoc             = null;
            Commlog CommlogCur = new Commlog();
            CommlogCur.CommDateTime   = DateTime.Now;
            CommlogCur.CommType       = Commlogs.GetTypeAuto(CommItemTypeAuto.MISC);
            CommlogCur.Mode_          = CommItemMode.Mail;
            CommlogCur.SentOrReceived = CommSentOrReceived.Sent;
            CommlogCur.PatNum         = PatCur.PatNum;
            CommlogCur.Note           = "Letter sent: " + letterCur.Description + ". ";
            CommlogCur.UserNum        = Security.CurUser.UserNum;
            Commlogs.Insert(CommlogCur);
            DialogResult = DialogResult.OK;
        }
Example #19
0
        private void work3()
        {
            int i;
            FrmMain frm = (FrmMain) this.Owner;
            prog.Maximum = Gib.fsum[Gib.nowtab];
            if (r31.Checked)
            {
                for (i = 1; i <= Gib.fsum[Gib.nowtab]; ++i)
                {
                    if (Gib.clast[Gib.nowtab, i] != '.' + allchanget.Text && File.Exists(Gib.cpath[Gib.nowtab, i]))
                        File.Move(Gib.cpath[Gib.nowtab, i],
                            Path.GetDirectoryName(Gib.cpath[Gib.nowtab, i]) + '\\' +
                            Path.GetFileNameWithoutExtension(Gib.cname[Gib.nowtab, i]) +
                            '.' + allchanget.Text);
                    prog.Value = i;
                }
            }
            else if (r32.Checked)
            {
                for (i = 1; i <= Gib.fsum[Gib.nowtab]; ++i)
                {
                    if (Gib.clast[Gib.nowtab, i].ToLower() != '.' + changet2.Text.ToLower() &&
                        File.Exists(Gib.cpath[Gib.nowtab, i]) &&
                        Gib.clast[Gib.nowtab, i].ToLower() == '.' + changet1.Text.ToLower())
                        File.Move(Gib.cpath[Gib.nowtab, i],
                            Path.GetDirectoryName(Gib.cpath[Gib.nowtab, i]) + '\\' +
                            Path.GetFileNameWithoutExtension(Gib.cname[Gib.nowtab, i]) +
                            '.' + changet2.Text);
                    prog.Value = i;
                }
            }
            else
            {
                Word.Application oWord = new Word.Application();
                object vOpt = System.Reflection.Missing.Value;
                try
                {
                    //MessageBoxEx.Show(Gib.fpos[Gib.nowtab, Gib.nowp[Gib.nowtab]]);
                    string[] fs = Directory.GetFiles(Gib.fpos[Gib.nowtab, Gib.nowp[Gib.nowtab]], "*.doc");
                    prog.Maximum = fs.Length;
                    int js = 0;
                    foreach (string of in fs)
                    {
                        object f = (object) of;
                        Word.Document vDoc = oWord.Documents.Open(ref f, ref vOpt, ref vOpt, ref vOpt, ref vOpt,
                            ref vOpt,
                            ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt,
                            ref vOpt);

                        string txtf = Path.GetDirectoryName(of) + '\\' + Path.GetFileNameWithoutExtension(of) + ".txt";
                        if (File.Exists(txtf)) File.Delete(txtf);
                        object otxt = (object) txtf;
                        object saveFormat = Word.WdSaveFormat.wdFormatText;
                        vDoc.SaveAs(ref otxt, ref saveFormat, ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt,
                            ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt, ref vOpt);
                        vDoc.Close(ref vOpt, ref vOpt, ref vOpt);
                        ++js;
                        prog.Value = js;
                    }
                }
                catch (Exception ex)
                {
                    MessageBoxEx.Show(ex.Message);
                }
                finally
                {
                    oWord.Quit(ref vOpt, ref vOpt, ref vOpt);
                    oWord = null;
                }
                frm.reffile(Gib.fpos[Gib.nowtab, Gib.nowp[Gib.nowtab]]);
            }
            frm.reffile(Gib.fpos[Gib.nowtab, Gib.nowp[Gib.nowtab]]);
            this.Close();
        }
Example #20
0
        private void Sta_Table_Click(object sender, EventArgs e)
        {
            object Nothing = System.Reflection.Missing.Value;
            object missing = System.Reflection.Missing.Value;

            //创建Word文档
            Word.Application wordApp = new Word.Application();
            Word.Document    wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            wordApp.Visible = true;

            //设置文档宽度
            wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2"));
            wordApp.ActiveWindow.ActivePane.HorizontalPercentScrolled = 11;
            wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2"));

            Object start = Type.Missing;
            Object end   = Type.Missing;

            PictureBox pp = new PictureBox();   //新建一个PictureBox控件
            int        p1 = 0;

            for (int i = 0; i < MyDS_Grid.Rows.Count; i++)
            {
                try
                {
                    byte[]       pic = (byte[])(MyDS_Grid.Rows[i].Cells[23].Value); //将数据库中的图片转换成二进制流
                    MemoryStream ms  = new MemoryStream(pic);                       //将字节数组存入到二进制流中
                    pp.Image = Image.FromStream(ms);                                //二进制流Image控件中显示
                    pp.Image.Save(@"C:\22.bmp");                                    //将图片存入到指定的路径
                }
                catch
                {
                    p1 = 1;
                }
                object rng     = Type.Missing;
                string strInfo = "职工基本信息表" + "(" + MyDS_Grid.Rows[i].Cells[1].Value.ToString() + ")";
                start = 0;
                end   = 0;
                wordDoc.Range(ref start, ref end).InsertBefore(strInfo);                                                        //插入文本
                wordDoc.Range(ref start, ref end).Font.Name = "Verdana";                                                        //设置字体
                wordDoc.Range(ref start, ref end).Font.Size = 20;                                                               //设置字体大小
                wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //设置字体局中

                start = strInfo.Length;
                end   = strInfo.Length;
                wordDoc.Range(ref start, ref end).InsertParagraphAfter();//插入回车

                object     missingValue = Type.Missing;
                object     location     = strInfo.Length; //如果location超过已有字符的长度将会出错。一定要比"明细表"串多一个字符
                Word.Range rng2         = wordDoc.Range(ref location, ref location);

                wordDoc.Tables.Add(rng2, 14, 6, ref missingValue, ref missingValue);
                wordDoc.Tables[1].Rows.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
                wordDoc.Tables[1].Rows.Height     = wordApp.CentimetersToPoints(float.Parse("0.8"));
                wordDoc.Tables[1].Range.Font.Size = 10;
                wordDoc.Tables[1].Range.Font.Name = "宋体";

                //设置表格样式
                wordDoc.Tables[1].Borders[Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                wordDoc.Tables[1].Borders[Word.WdBorderType.wdBorderLeft].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
                wordDoc.Tables[1].Borders[Word.WdBorderType.wdBorderLeft].Color     = Word.WdColor.wdColorAutomatic;
                wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐

                //第5行显示
                wordDoc.Tables[1].Cell(1, 5).Merge(wordDoc.Tables[1].Cell(5, 6));
                //第6行显示
                wordDoc.Tables[1].Cell(6, 5).Merge(wordDoc.Tables[1].Cell(6, 6));
                //第9行显示
                wordDoc.Tables[1].Cell(9, 4).Merge(wordDoc.Tables[1].Cell(9, 6));
                //第12行显示
                wordDoc.Tables[1].Cell(12, 2).Merge(wordDoc.Tables[1].Cell(12, 6));
                //第13行显示
                wordDoc.Tables[1].Cell(13, 2).Merge(wordDoc.Tables[1].Cell(13, 6));
                //第14行显示
                wordDoc.Tables[1].Cell(14, 2).Merge(wordDoc.Tables[1].Cell(14, 6));

                //第1行赋值
                wordDoc.Tables[1].Cell(1, 1).Range.Text = "职工编号:";
                wordDoc.Tables[1].Cell(1, 2).Range.Text = MyDS_Grid.Rows[i].Cells[0].Value.ToString();
                wordDoc.Tables[1].Cell(1, 3).Range.Text = "职工姓名:";
                wordDoc.Tables[1].Cell(1, 4).Range.Text = MyDS_Grid.Rows[i].Cells[1].Value.ToString();

                //插入图片

                if (p1 == 0)
                {
                    string FileName         = @"C:\22.bmp";//图片所在路径
                    object LinkToFile       = false;
                    object SaveWithDocument = true;
                    object Anchor           = wordDoc.Tables[1].Cell(1, 5).Range; //指定图片插入的区域
                    //将图片插入到单元格中
                    wordDoc.Tables[1].Cell(1, 5).Range.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                }
                p1 = 0;

                //第2行赋值
                wordDoc.Tables[1].Cell(2, 1).Range.Text = "民族类别:";
                wordDoc.Tables[1].Cell(2, 2).Range.Text = MyDS_Grid.Rows[i].Cells[2].Value.ToString();
                wordDoc.Tables[1].Cell(2, 3).Range.Text = "出生日期:";
                try
                {
                    wordDoc.Tables[1].Cell(2, 4).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Rows[i].Cells[3].Value).ToShortDateString());
                }
                catch { wordDoc.Tables[1].Cell(2, 4).Range.Text = ""; }
                //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][3]);
                //第3行赋值
                wordDoc.Tables[1].Cell(3, 1).Range.Text = "年龄:";
                wordDoc.Tables[1].Cell(3, 2).Range.Text = Convert.ToString(MyDS_Grid.Rows[i].Cells[4].Value.ToString());
                wordDoc.Tables[1].Cell(3, 3).Range.Text = "文化程序:";
                wordDoc.Tables[1].Cell(3, 4).Range.Text = MyDS_Grid.Rows[i].Cells[5].Value.ToString();
                //第4行赋值
                wordDoc.Tables[1].Cell(4, 1).Range.Text = "婚姻:";
                wordDoc.Tables[1].Cell(4, 2).Range.Text = MyDS_Grid.Rows[i].Cells[6].Value.ToString().ToString();
                wordDoc.Tables[1].Cell(4, 3).Range.Text = "性别:";
                wordDoc.Tables[1].Cell(4, 4).Range.Text = MyDS_Grid.Rows[i].Cells[7].Value.ToString();
                //第5行赋值
                wordDoc.Tables[1].Cell(5, 1).Range.Text = "政治面貌:";
                wordDoc.Tables[1].Cell(5, 2).Range.Text = MyDS_Grid.Rows[i].Cells[8].Value.ToString();
                wordDoc.Tables[1].Cell(5, 3).Range.Text = "单位工作时间:";
                try
                {
                    wordDoc.Tables[1].Cell(5, 4).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Rows[i].Cells[10].Value).ToShortDateString());
                }
                catch { wordDoc.Tables[1].Cell(5, 4).Range.Text = ""; }
                //第6行赋值
                wordDoc.Tables[1].Cell(6, 1).Range.Text = "籍贯:";
                wordDoc.Tables[1].Cell(6, 2).Range.Text = MyDS_Grid.Rows[i].Cells[24].Value.ToString();
                wordDoc.Tables[1].Cell(6, 3).Range.Text = MyDS_Grid.Rows[i].Cells[25].Value.ToString();
                wordDoc.Tables[1].Cell(6, 4).Range.Text = "身份证:";
                wordDoc.Tables[1].Cell(6, 5).Range.Text = MyDS_Grid.Rows[i].Cells[9].Value.ToString();
                //第7行赋值
                wordDoc.Tables[1].Cell(7, 1).Range.Text = "工龄:";
                wordDoc.Tables[1].Cell(7, 2).Range.Text = Convert.ToString(MyDS_Grid.Rows[i].Cells[11].Value);
                wordDoc.Tables[1].Cell(7, 3).Range.Text = "职工类别:";
                wordDoc.Tables[1].Cell(7, 4).Range.Text = MyDS_Grid.Rows[i].Cells[12].Value.ToString();
                wordDoc.Tables[1].Cell(7, 5).Range.Text = "职务类别:";
                wordDoc.Tables[1].Cell(7, 6).Range.Text = MyDS_Grid.Rows[i].Cells[13].Value.ToString();
                //第8行赋值
                wordDoc.Tables[1].Cell(8, 1).Range.Text = "工资类别:";
                wordDoc.Tables[1].Cell(8, 2).Range.Text = MyDS_Grid.Rows[i].Cells[14].Value.ToString();
                wordDoc.Tables[1].Cell(8, 3).Range.Text = "部门类别:";
                wordDoc.Tables[1].Cell(8, 4).Range.Text = MyDS_Grid.Rows[i].Cells[15].Value.ToString();
                wordDoc.Tables[1].Cell(8, 5).Range.Text = "职称类别:";
                wordDoc.Tables[1].Cell(8, 6).Range.Text = MyDS_Grid.Rows[i].Cells[16].Value.ToString();
                //第9行赋值
                wordDoc.Tables[1].Cell(9, 1).Range.Text = "月工资:";
                wordDoc.Tables[1].Cell(9, 2).Range.Text = Convert.ToString(MyDS_Grid.Rows[i].Cells[26].Value);
                wordDoc.Tables[1].Cell(9, 3).Range.Text = "银行帐号:";
                wordDoc.Tables[1].Cell(9, 4).Range.Text = MyDS_Grid.Rows[i].Cells[27].Value.ToString();
                //第10行赋值
                wordDoc.Tables[1].Cell(10, 1).Range.Text = "合同起始日期:";
                try
                {
                    wordDoc.Tables[1].Cell(10, 2).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Rows[i].Cells[28].Value).ToShortDateString());
                }
                catch { wordDoc.Tables[1].Cell(10, 2).Range.Text = ""; }
                //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][28]);
                wordDoc.Tables[1].Cell(10, 3).Range.Text = "合同结束日期:";
                try
                {
                    wordDoc.Tables[1].Cell(10, 4).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Rows[i].Cells[29].Value).ToShortDateString());
                }
                catch { wordDoc.Tables[1].Cell(10, 4).Range.Text = ""; }
                //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][29]);
                wordDoc.Tables[1].Cell(10, 5).Range.Text = "合同年限:";
                wordDoc.Tables[1].Cell(10, 6).Range.Text = Convert.ToString(MyDS_Grid.Rows[i].Cells[30].Value);
                //第11行赋值
                wordDoc.Tables[1].Cell(11, 1).Range.Text = "电话:";
                wordDoc.Tables[1].Cell(11, 2).Range.Text = MyDS_Grid.Rows[i].Cells[17].Value.ToString();
                wordDoc.Tables[1].Cell(11, 3).Range.Text = "手机:";
                wordDoc.Tables[1].Cell(11, 4).Range.Text = MyDS_Grid.Rows[i].Cells[18].Value.ToString();
                wordDoc.Tables[1].Cell(11, 5).Range.Text = "毕业时间:";
                try
                {
                    wordDoc.Tables[1].Cell(11, 6).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Rows[i].Cells[21].Value).ToShortDateString());
                }
                catch { wordDoc.Tables[1].Cell(11, 6).Range.Text = ""; }
                //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][21]);
                //第12行赋值
                wordDoc.Tables[1].Cell(12, 1).Range.Text = "毕业学校:";
                wordDoc.Tables[1].Cell(12, 2).Range.Text = MyDS_Grid.Rows[i].Cells[19].Value.ToString();
                //第13行赋值
                wordDoc.Tables[1].Cell(13, 1).Range.Text = "主修专业:";
                wordDoc.Tables[1].Cell(13, 2).Range.Text = MyDS_Grid.Rows[i].Cells[20].Value.ToString();
                //第14行赋值
                wordDoc.Tables[1].Cell(14, 1).Range.Text = "家庭地址:";
                wordDoc.Tables[1].Cell(14, 2).Range.Text = MyDS_Grid.Rows[i].Cells[22].Value.ToString();

                wordDoc.Range(ref start, ref end).InsertParagraphAfter();                                                       //插入回车
                wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //设置字体局中
            }
        }
Example #21
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="ClientID"></param>
        /// <param name="ClientDocSetID"></param>
        public DocumentGeneration(int ClientID, int ClientDocSetID, IOutputMessage UIoutput = null,
                                  string OverrideDocuments = null)
        {
            if (overrideDocuments == null)
            {
                overrideDocuments = "N";
            }

            // Assign to internal variables
            //
            // iconMessage = IconMessage;

            // Set private attributes
            clientID          = ClientID;
            clientDocSetID    = ClientDocSetID;
            uioutput          = UIoutput;
            overrideDocuments = OverrideDocuments;

            // Instantiate Word
            //
            vkFalse = false;

            vkWordApp = new Word.Application();

            // Make it not visible
            vkWordApp.Visible = false;

            vkExcelApp = new Excel.Application();

            // Make it not visible
            vkExcelApp.Visible = false;

            // Get Metadata for client

            clientMetadata = new ReportMetadataList();

            // Daniel 31/12/2011
            //
            // clientMetadata.ListMetadataForClient(clientID);
            // The intention is to always use the full set of variables.
            // There is need to use all in order to replace the tags not used.
            //
            clientMetadata.ListDefault();

            ts = new List <WordDocumentTasks.TagStructure>();

            // Load variables/ metadata into memory
            //
            #region ClientMetadata
            foreach (ReportMetadata metadata in clientMetadata.reportMetadataList)
            {
                // Add client ID
                metadata.ClientUID = this.clientID;

                // Retrieve value for the field selected
                //
                string value = metadata.GetValue();

                // If the field is not enabled, the program has to replace the value with spaces.
                // 01-Jan-2012 - No longer necessary.
                // All the variables have to be used

                // var valueOfTag = metadata.Enabled == 'Y' ? value : string.Empty;

                // Set to the value. If value is null, set to spaces.
                var valueOfTag = string.IsNullOrEmpty(value) ? string.Empty : value;

                // When the field is an image and it is not enable, do not include the "No image" icon in the list
                //
                //if (metadata.InformationType == Utils.InformationType.IMAGE && metadata.Enabled == 'N')
                //    continue;

                // If the field is an image but it has no value, no need to include.
                // Regular fields must be included because they need to be replaced.
                // Images uses bookmarks, no need to be replace. It is not displayed in the document.
                //
                if (metadata.InformationType == Utils.InformationType.IMAGE)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        continue;
                    }
                }

                // Add label before value to print.
                //
                if (metadata.UseAsLabel == 'Y')
                {
                    valueOfTag = metadata.Description + " " + valueOfTag;
                }

                ts.Add(new WordDocumentTasks.TagStructure()
                {
                    TagType  = metadata.InformationType,
                    Tag      = metadata.FieldCode,
                    TagValue = valueOfTag
                });
            }
            #endregion ClientMetadata

            // Get Client Document Set Details
            // To get the source and destination folders
            cds = new ClientDocumentSet();
            cds.Get(clientID, clientDocSetID);

            fileprocessedcount  = 0;
            valueForProgressBar = 0;
            startTime           = System.DateTime.Now.ToString();
        }
        private void butPrint_Click(object sender, System.EventArgs e)
        {
            if (listLetters.SelectedIndex == -1)
            {
                MsgBox.Show(this, "Please select a letter first.");
                return;
            }
            LetterMerge letterCur    = ListForCat[listLetters.SelectedIndex];
            string      templateFile = PrefB.GetString("LetterMergePath") + letterCur.TemplateName;
            string      dataFile     = PrefB.GetString("LetterMergePath") + letterCur.DataFileName;

            if (!File.Exists(templateFile))
            {
                MsgBox.Show(this, "Template file does not exist.");
                return;
            }
            PrintDocument pd = new PrintDocument();

            if (!Printers.SetPrinter(pd, PrintSituation.Default))
            {
                return;
            }
            if (!CreateDataFile(dataFile, letterCur))
            {
                return;
            }
            Word.MailMerge wrdMailMerge;
            //Create an instance of Word.
            Word.Application WrdApp = LetterMerges.WordApp;
            //Open a document.
            Object oName = templateFile;

            wrdDoc = WrdApp.Documents.Open(ref oName, 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);
            wrdDoc.Select();
            wrdMailMerge = wrdDoc.MailMerge;
            //Attach the data file.
            wrdDoc.MailMerge.OpenDataSource(dataFile, 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 oMissing);
            wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToPrinter;
            WrdApp.ActivePrinter     = pd.PrinterSettings.PrinterName;
            wrdMailMerge.Execute(ref oFalse);
            //Close the original form document since just one record.
            wrdDoc.Saved = true;
            wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);
            //At this point, Word remains open with no documents.
            WrdApp.WindowState = Word.WdWindowState.wdWindowStateMinimize;
            wrdMailMerge       = null;
            wrdDoc             = null;
            Commlog CommlogCur = new Commlog();

            CommlogCur.CommDateTime   = DateTime.Now;
            CommlogCur.CommType       = CommItemType.Misc;
            CommlogCur.Mode_          = CommItemMode.Mail;
            CommlogCur.SentOrReceived = CommSentOrReceived.Sent;
            CommlogCur.PatNum         = PatCur.PatNum;
            CommlogCur.Note           = "Letter sent: " + letterCur.Description + ". ";
            Commlogs.Insert(CommlogCur);
            DialogResult = DialogResult.OK;
        }
Example #23
0
        public void InsertTitle(string title, string level)
        {
            object missing = System.Reflection.Missing.Value;
            Word._Application app = new Word.Application();
            object path = RandomPath;
            Word.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            doc.Activate();
            Word.Range range = doc.Paragraphs.Last.Range;//定位到段尾
            //range.InsertParagraphAfter();

            range.Text = level + "." + title;
            range.Font.Italic = 1;
            range.Font.Color = Word.WdColor.wdColorBlue;

            //object styleName = "标题 3";
            //range.set_Style(ref styleName);
            doc.SaveAs(ref path, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            app.Quit(ref missing, ref missing, ref missing);
            InsertFile(path.ToString());
        }
 public void close()
 {
     this._wordApplication = null;
     this._wordDocument    = null;
 }
Example #25
0
        /// <summary>
        /// Run Word Automation
        /// </summary>
        public override void Run()
        {
            if (FileName.Length == 0)
            {
                throw new Exception("Property of FileName hasn't be initialized");
            }
            if (Plate == null)
            {
                throw new Exception("Property of Plate hasn't be initialized");
            }
            Word.Application objWord = new Word.Application();
            if (objWord == null)
            {
                throw new Exception("Word could not be started. Check that your office installation and project references are correct");
            }
            objWord.Visible = false;
            objWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
            object objMiss = Missing.Value;
            object strfile = FileName;
            Word.Document objDocument = objWord.Documents.Open(ref strfile, ref objMiss, ref objMiss, ref objMiss
                , ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss
                , ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);
            Word.Row objRow = null;
            Log.StartLog(FileName + ".log", "Word Plate");

            try
            {
                this.ProgressCount = objDocument.Sentences.Count;
                for (int i = 1; i <= objDocument.Sentences.Count; i++)
                {
                    this.ProgressInfo = i - 1;
                    this.TagInfo = string.Format("Process Line:{0}/{1}", i.ToString(), objDocument.Sentences.Count.ToString());
                    if (!objDocument.Sentences[i].Text.EndsWith("\a"))
                    {
                        string newtext = ProcessTag(objDocument.Sentences[i].Text);
                        if (string.Compare(objDocument.Sentences[i].Text, newtext) != 0)
                        {
                            objDocument.Sentences[i].Text = newtext;
                        }
                    }
                }

                for (int i = 1; i <= objDocument.Tables.Count; i++)
                {
                    this.TagInfo = string.Format("Process Table:{0}/{1}", i.ToString(), objDocument.Tables.Count.ToString());
                    this.ProgressInfo = 0;
                    this.ProgressCount = objDocument.Tables[i].Rows.Count;
                    ArrayList listValue = new ArrayList();
                    objDocument.Tables[i].Rows.Add(ref objMiss);//新增一个空行,最后会删除
                    int rowindex = 1;
                    while (rowindex < objDocument.Tables[i].Rows.Count)
                    {
                        this.ProgressInfo++;
                        int dsmaxcount = int.MaxValue;
                        objRow = objDocument.Tables[i].Rows[rowindex];
                        object[] objRowVallue = new object[objRow.Cells.Count];
                        for (int j = 1; j <= objRow.Cells.Count; j++)
                        {
                            objRowVallue[j - 1] = objRow.Cells[j].Range.Text.TrimEnd(new char[] { '\r', '\a'});
                            string strvalue = objRowVallue[j - 1].ToString().Trim();
                            if (strvalue.StartsWith("$") && strvalue.Length > 1)
                            {
                                strvalue = strvalue.Substring(1);
                                int dscount = GetDataSourceRowCount(ref strvalue);
                                if (dscount >= 0)
                                {
                                    objRowVallue[j - 1] = strvalue;
                                    dsmaxcount = Math.Min(dsmaxcount, dscount);
                                }
                            }
                        }
                        if (dsmaxcount == int.MaxValue)
                        {
                            rowindex++;
                            CopyRow(1, objRowVallue, listValue);
                        }
                        else
                        {
                            rowindex += dsmaxcount;
                            CopyRow(dsmaxcount, objRowVallue, listValue);
                            objRow.Range.Copy();
                            CopyFormat(objRow.Next.Range, dsmaxcount);
                            objRow.Delete();
                        }
                    }
                    objDocument.Tables[i].Rows.Last.Delete();

                    for (int j = 1; j <= objDocument.Tables[i].Rows.Count; j++)
                    {
                        for (int k = 1; k <= objDocument.Tables[i].Columns.Count; k++)
                        {
                            objDocument.Tables[i].Cell(j, k).Range.Text = ((object[])listValue[j - 1])[k - 1].ToString().TrimEnd("\r\a".ToCharArray());
                        }
                    }
                }
                this.TagInfo = "Process Finished";
                this.ProgressInfo = this.ProgressCount;

                objDocument.Save();
            }
            catch (Exception e)
            {
                Log.WriteExceptionInfo(e);
                throw;
            }
            finally
            {
                Log.EndLog();
                ((Word._Application)objWord).Quit(ref objMiss, ref objMiss, ref objMiss);
                if (objRow != null)
                {
                    Marshal.ReleaseComObject(objRow);
                }
                Marshal.ReleaseComObject(objDocument);
                Marshal.ReleaseComObject(objWord);

                objRow = null;
                objDocument = null;
                objWord = null;
                objMiss = null;

                GC.Collect();
            }
        }
Example #26
0
        public void ExportData(DataGridView srcDgv, string fileName)           //导出数据,传入一个datagridview和一个文件路径
        {
            string type = fileName.Substring(fileName.IndexOf(".") + 1);       //获得数据类型

            if (type.Equals("xls", StringComparison.CurrentCultureIgnoreCase)) //Excel文档
            {
                Excel.Application excel = new Excel.Application();
                try
                {
                    excel.DisplayAlerts = false;
                    excel.Workbooks.Add(true);
                    excel.Visible = false;

                    for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
                    {
                        excel.Cells[2, i + 1] = srcDgv.Columns[i].HeaderText;
                    }

                    for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
                    {
                        for (int j = 0; j < srcDgv.Columns.Count; j++)
                        {
                            if (srcDgv[j, i].ValueType.ToString() == "System.Byte[]")
                            {
                                excel.Cells[i + 3, j + 1] = "System.Byte[]";
                            }
                            else
                            {
                                excel.Cells[i + 3, j + 1] = srcDgv[j, i].Value;
                            }
                        }
                    }

                    excel.Workbooks[1].SaveCopyAs(fileName);//保存
                }
                finally
                {
                    excel.Quit();
                }
                return;
            }
            //保存Word文件
            if (type.Equals("doc", StringComparison.CurrentCultureIgnoreCase))
            {
                object           path     = fileName;
                Object           none     = System.Reflection.Missing.Value;
                Word.Application wordApp  = new Word.Application();
                Word.Document    document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
                //建立表格
                Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count + 1, srcDgv.Columns.Count, ref none, ref none);
                try
                {
                    for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
                    {
                        table.Cell(1, i + 1).Range.Text = srcDgv.Columns[i].HeaderText;
                    }

                    for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
                    {
                        for (int j = 0; j < srcDgv.Columns.Count; j++)
                        {
                            string a = srcDgv[j, i].ValueType.ToString();
                            if (a == "System.Byte[]")
                            {
                                PictureBox   pp  = new PictureBox();
                                byte[]       pic = (byte[])(srcDgv[j, i].Value); //将数据库中的图片转换成二进制流
                                MemoryStream ms  = new MemoryStream(pic);        //将字节数组存入到二进制流中
                                pp.Image = Image.FromStream(ms);                 //二进制流Image控件中显示
                                pp.Image.Save(@"C:\22.bmp");                     //将图片存入到指定的路径
                                object aaa = table.Cell(i + 2, j + 1).Range;
                                wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                                wordApp.Selection.InlineShapes.AddPicture(@"C:\22.bmp", ref none, ref none, ref aaa);
                                pp.Dispose();
                            }
                            else
                            {
                                table.Cell(i + 2, j + 1).Range.Text = srcDgv[j, i].Value.ToString();
                            }
                        }
                    }
                    document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                    document.Close(ref none, ref none, ref none);
                    if (File.Exists(@"C:\22.bmp"))
                    {
                        File.Delete(@"C:\22.bmp");
                    }
                }
                finally
                {
                    wordApp.Quit(ref none, ref none, ref none);
                }
            }
        }
        /// <summary>
        /// 动态创建table到word
        /// </summary>
        protected void CreateTableToExcel()
        {
            Word.Application app = null;
            Word.Document    doc = null;
            try
            {
                //构造数据
                List <Student> datas = new List <Student>();
                datas.Add(new Student {
                    Leader = "小李", Name = "张三", Score = 498, StuClass = "一班"
                });
                datas.Add(new Student {
                    Leader = "陈飞", Name = "李四", Score = 354, StuClass = "二班"
                });
                datas.Add(new Student {
                    Leader = "陈飞", Name = "小红", Score = 502, StuClass = "二班"
                });
                datas.Add(new Student {
                    Leader = "王林", Name = "丁爽", Score = 566, StuClass = "三班"
                });
                var cate = datas.GroupBy(s => s.StuClass);

                int    rows     = cate.Count() + 1; //表格行数加1是为了标题栏
                int    cols     = 5;                //表格列数
                object oMissing = System.Reflection.Missing.Value;
                app = new Word.Application();       //创建word应用程序
                doc = app.Documents.Add();          //添加一个word文档

                //输出大标题加粗加大字号水平居中
                app.Selection.Font.Bold = 700;
                app.Selection.Font.Size = 16;
                app.Selection.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                app.Selection.Text = "班级成绩统计单";

                //换行添加表格
                object line = Word.WdUnits.wdLine;
                app.Selection.MoveDown(ref line, oMissing, oMissing);
                app.Selection.TypeParagraph();//换行
                Word.Range range = app.Selection.Range;
                Word.Table table = app.Selection.Tables.Add(range, rows, cols, ref oMissing, ref oMissing);

                //设置表格的字体大小粗细
                table.Range.Font.Size = 10;
                table.Range.Font.Bold = 0;

                //设置表格标题
                int rowIndex = 1;
                table.Cell(rowIndex, 1).Range.Text = "班级";
                table.Cell(rowIndex, 2).Range.Text = "姓名";
                table.Cell(rowIndex, 3).Range.Text = "成绩";
                table.Cell(rowIndex, 4).Range.Text = "人数";
                table.Cell(rowIndex, 5).Range.Text = "班主任";

                //循环数据创建数据行
                rowIndex++;
                foreach (var i in cate)
                {
                    table.Cell(rowIndex, 1).Range.Text = i.Key;                //班级
                    table.Cell(rowIndex, 4).Range.Text = i.Count().ToString(); //人数
                    table.Cell(rowIndex, 5).Range.Text = i.First().Leader;     //班主任
                    table.Cell(rowIndex, 2).Split(i.Count(), 1);               //分割名字单元格
                    table.Cell(rowIndex, 3).Split(i.Count(), 1);               //分割成绩单元格

                    //对表格中的班级、姓名,成绩单元格设置上下居中
                    table.Cell(rowIndex, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    table.Cell(rowIndex, 4).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    table.Cell(rowIndex, 5).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                    //构建姓名,成绩数据
                    foreach (var x in i)
                    {
                        table.Cell(rowIndex, 2).Range.Text = x.Name;
                        table.Cell(rowIndex, 3).Range.Text = x.Score.ToString();
                        rowIndex++;
                    }
                }

                //导出到文件
                string newFile       = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";
                string physicNewFile = Server.MapPath(newFile);
                doc.SaveAs(physicNewFile,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭文档
                }
                if (app != null)
                {
                    app.Quit();//退出应用程序
                }
            }
        }
Example #28
0
        /// <summary>
        /// The function used to debug in Com mode
        /// </summary>
        /// <param name="filename">Name of file</param>
        /// <returns>The result of debug</returns>
        public bool DebugCom(string filename)
        {
            bool blsuccess = true;
            if (plate is ExcelPlate)
            {
                Excel.Application objExcel = new Excel.Application();
                if (objExcel == null)
                {
                    AddRow(dataGridViewDebug, "EXCEL could not be started. Check that your office installation and project references are correct"
                        , string.Empty, "error");
                    return false;
                }
                objExcel.Visible = false;
                objExcel.DisplayAlerts = false;
                object objMiss = System.Reflection.Missing.Value;
                Excel.Workbook objWorkBook = objExcel.Workbooks.Open(filename, objMiss, objMiss, objMiss
                    , objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss, objMiss);
                Excel.Sheets objWorkSheets = objWorkBook.Worksheets;
                Excel.Worksheet objWorkSheet = null;
                Excel.Range objRange = null;
                try
                {
                    for (int i = 1; i <= objWorkSheets.Count; i++)
                    {
                        objWorkSheet = (Excel.Worksheet)objWorkSheets[i];
                        int rowcount = objWorkSheet.UsedRange.Rows.Count;
                        int columncount = objWorkSheet.UsedRange.Columns.Count;
                        objRange = objWorkSheet.UsedRange;
                        if (objRange.Cells.Count == 1)
                        {
                            objRange = objRange.get_Resize(1, 2);
                        }
                        object[,] objValue = (object[,])objRange.get_Value(objMiss);
                        for (int j = 1; j <= rowcount; j++)
                        {
                            for (int k = 1; k <= columncount; k++)
                            {
                                if (objValue[j, k] is string)
                                {
                                    string strtext = objValue[j, k].ToString();
                                    if (strtext.StartsWith("$") && strtext.Length > 1)
                                    {
                                        object[] objret = DebugDetail(plate, strtext.Substring(1));
                                        if ((int)objret[0] == 1)
                                        {
                                            AddRow(dataGridViewDebug, objret[1].ToString(), strtext, objret[2].ToString());
                                            blsuccess = false;
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format("Debug encounter unexpected error:\n{0}{1}", e.Message, (e.InnerException != null ? "\n" + e.InnerException.Message : string.Empty))
                        , "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    objExcel.Quit();
                    Marshal.ReleaseComObject(objRange);
                    Marshal.ReleaseComObject(objWorkSheet);
                    Marshal.ReleaseComObject(objWorkSheets);
                    Marshal.ReleaseComObject(objWorkBook);
                    Marshal.ReleaseComObject(objExcel);

                    objRange = null;
                    objWorkSheet = null;
                    objWorkSheets = null;
                    objWorkBook = null;
                    objExcel = null;
                    objMiss = null;

                    GC.Collect();
                }
            }
            else if (plate is WordPlate)
            {
                Word.Application objWord = new Word.Application();
                if (objWord == null)
                {
                    AddRow(dataGridViewDebug, "Word could not be started. Check that your office installation and project references are correct"
                        , string.Empty, "error");
                    return false;
                }
                objWord.Visible = false;
                objWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
                object objMiss = System.Reflection.Missing.Value;
                object strfile = filename;
                Word.Document objDocument = objWord.Documents.Open(ref strfile, ref objMiss, ref objMiss, ref objMiss
                    , ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss
                    , ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);
                try
                {
                    for (int i = 1; i <= objDocument.Sentences.Count; i++)
                    {
                        string[] arrtext = objDocument.Sentences[i].Text.Split(' ');
                        foreach (string str in arrtext)
                        {
                            if (str.StartsWith("$") && str.Length > 1)
                            {
                                object[] objret = DebugDetail(plate, str.Substring(1));
                                if ((int)objret[0] == 1)
                                {
                                    AddRow(dataGridViewDebug, objret[1].ToString(), str, objret[2].ToString());
                                    blsuccess = false;
                                }
                            }
                        }
                        SetProgress(toolStripProgressBar, ((i - 1) * 100 / objDocument.Sentences.Count));
                    }
                    for (int i = 1; i <= objDocument.Tables.Count; i++)
                    {
                        for (int j = 1; j <= objDocument.Tables[i].Rows.Count; j++)
                        {
                            for (int k = 1; k <= objDocument.Tables[i].Columns.Count; k++)
                            {
                                string strtext = objDocument.Tables[i].Cell(j, k).Range.Text.Trim();
                                if (strtext.StartsWith("$") && strtext.Length > 1)
                                {
                                    object[] objret = DebugDetail(plate, strtext.Substring(1));
                                    if ((int)objret[0] == 1)
                                    {
                                        AddRow(dataGridViewDebug, objret[1].ToString(), strtext, objret[2].ToString());
                                        blsuccess = false;
                                    }
                                }
                            }
                            SetProgress(toolStripProgressBar, ((j - 1) * 100 / objDocument.Tables[i].Rows.Count));
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format("Debug encounter unexpected error:\n{0}{1}", e.Message, (e.InnerException != null ? "\n" + e.InnerException.Message : string.Empty))
                        , "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    ((Word._Application)objWord).Quit(ref objMiss, ref objMiss, ref objMiss);
                    Marshal.ReleaseComObject(objDocument);
                    Marshal.ReleaseComObject(objWord);

                    objDocument = null;
                    objWord = null;
                    objMiss = null;

                    GC.Collect();
                }
            }
            return blsuccess;
        }