/*Setting up a printable invoice for the required Customer
         */
        public void print()
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            Microsoft.Office.Interop.Word.Document doc = app.Documents.Add("E:/CarRentalSystem/Invoice.docx");

            doc.Variables["Name"].Value = lbl_Forename.Text + " " + lbl_Surname.Text;

            doc.Variables["Address"].Value = lbl_Address.Text;

            doc.Variables["Town"].Value = lbl_Town.Text;

            doc.Variables["County"].Value = lbl_County.Text;

            doc.Variables["Phone_No"].Value = lbl_Phone.Text;

            doc.Variables["Date"].Value = lbl_Date.Text;

            doc.Variables["Balance"].Value = lbl_Acc_Balance.Text;

            doc.Variables["Id"].Value =  lbl_Customer_Id.Text;
            doc.Fields.Update();

            doc.SaveAs2("E:/CarRentalSystem/Invoice.docx2");

            doc.PrintOut();

            doc.Close();

            app.Quit();
        }
Exemple #2
0
        public static void ConvertXMLToPDF(object xmlFilename, object pdfFileName)
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue    = true;
            Object oFalse   = false;

            oWord         = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            try
            {
                File.Delete(pdfFileName.ToString());
            }
            catch (Exception)
            {
                oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            }

            Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref xmlFilename, 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);

            object oFmt = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;

            doc.SaveAs(ref pdfFileName, ref oFmt, 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);


            CaseDocument.ReleaseComObject(oFmt);
            CaseDocument.ReleaseComObject(doc);
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            CaseDocument.ReleaseComObject(oWord);
        }
Exemple #3
0
        public FileInfo convertDoc2Pdf(FileInfo documentToConvert)
        {
            var appWord = new Microsoft.Office.Interop.Word.Application();

            if (documentToConvert.Extension == ".pdf" && documentToConvert.Name != coverPageFileName)
            {
                // If it's already a PDF, just copy it to the working dir
                documentToConvert.CopyTo(Application.StartupPath + "\\" + documentToConvert.Name, true);
                return(new FileInfo(Application.StartupPath + "\\" + documentToConvert.Name));
            }
            else if (appWord.Documents != null)
            {
                try
                {
                    var      wordDocument = appWord.Documents.Open(documentToConvert.FullName);
                    FileInfo pdfDocName   = new FileInfo(Application.StartupPath + "\\" + documentToConvert.Name + ".pdf");

                    if (wordDocument != null)
                    {
                        wordDocument.SaveAs2(pdfDocName.FullName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
                        wordDocument.Close();
                        appWord.Quit();
                        return(pdfDocName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            appWord.Quit();
            return(null);
        }
Exemple #4
0
        /// <summary>把Word文件转换成为PDF格式文件</summary>   
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool WordToHtml(string sourcePath, string targetPath)
        {
            bool result = false;

            if (File.Exists(sourcePath))
            {
                object oMissing = System.Reflection.Missing.Value;
                object oTrue    = true;
                object oFalse   = false;

                Microsoft.Office.Interop.Word._Application oWord    = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word._Document    oWordDoc = new Microsoft.Office.Interop.Word.Document();

                oWord.Visible = false;
                object openFormat = Microsoft.Office.Interop.Word.WdOpenFormat.wdOpenFormatAuto;
                object openName   = sourcePath;

                try
                {
                    oWordDoc = oWord.Documents.Open(ref openName, ref oMissing, ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref openFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                }
                catch (Exception e)
                {
                    Console.WriteLine("读取Word文档时发生异常");
                    oWord.Quit(ref oTrue, ref oMissing, ref oMissing);
                    return(false);
                }

                object saveFileName = targetPath;
                object saveFormat   = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML;

                oWordDoc.SaveAs(ref saveFileName, ref saveFormat, ref oMissing, ref oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                oWordDoc.Close(ref oTrue, ref oMissing, ref oMissing);
                oWord.Quit(ref oTrue, ref oMissing, ref oMissing);

                Encoding enc = Encoding.GetEncoding("GB2312");
                string   s   = File.ReadAllText(targetPath, enc);
                s = s.Replace("position:absolute;", "");
                File.WriteAllText(targetPath, s, enc);

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                return(true);
            }
            return(false);
        }
Exemple #5
0
 private void button1_Click(object sender, EventArgs e)
 {
     using (OpenFileDialog ofd = new OpenFileDialog()
     {
         ValidateNames = true, Multiselect = false, Filter = "Word 97-2003|*.doc|Word Document|*.docx"
     })
     {
         if (ofd.ShowDialog() == DialogResult.OK)
         {
             object readOnly = false;
             object visible  = true;
             object save     = false;
             object fileName = ofd.FileName;
             object docType  = 0;
             object missing  = Type.Missing;
             Microsoft.Office.Interop.Word._Document    document;
             Microsoft.Office.Interop.Word._Application application = new Microsoft.Office.Interop.Word.Application()
             {
                 Visible = false
             };
             document = application.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing, ref missing, ref visible, ref missing, ref missing, ref missing, ref missing);
             document.ActiveWindow.Selection.WholeStory();
             document.ActiveWindow.Selection.Copy();
             IDataObject dataObject = Clipboard.GetDataObject();
             richTextBox1.Rtf = dataObject.GetData(DataFormats.Rtf).ToString();
             application.Quit(ref missing, ref missing, ref missing);
         }
     }
 }
Exemple #6
0
        private void btnCreateResume_Click(object sender, EventArgs e)
        {
            try
            {
                wordApp = new Microsoft.Office.Interop.Word.Application {
                    Visible = true
                };
                if (chbResume.Checked)
                {
                    ExportPdfFile(txtResumePath.Text);
                }
                if (chbCoverLetter.Checked)
                {
                    ExportPdfFile(txtCoverLetterPath.Text);
                }
                if (chbCertificates.Checked)
                {
                    ExportPdfFile(txtCetrficatesPath.Text);
                }

                wordApp.Quit();
                releaseObject(wordApp);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #7
0
 public async void startListTexToWord(string pathFooter, string FormFile, List <string> listpath, string apppath, string StartProof, List <string> liststr, bool?All, bool?HevaHoac, bool?ColorOne, bool?BoldOne, bool?ItalicOne, bool?UnderLineTwo, bool?HghtlightTwo, bool?ColorTwo, bool?ColorThree, bool?RunTexToWord)
 {
     await System.Threading.Tasks.Task.Run(() =>
     {
         foreach (string path in listpath)
         {
             try
             {
                 string fileName = System.IO.Path.GetFileNameWithoutExtension(path);
                 //DateTime time = DateTime.Now;
                 //string TimeName = time.ToString("h.mm.ss");
                 string pathTex   = Directory.GetCurrentDirectory() + @"\LuuFile" + @"\" + fileName + @".tex";
                 string pathDoc   = Directory.GetCurrentDirectory() + @"\LuuFile" + @"\" + fileName + @".docx";
                 var app          = new Application();
                 app.Visible      = true;
                 WordToTex change = new WordToTex();
                 change.startWordToTex(app, pathFooter, FormFile, path, pathTex, pathDoc, StartProof, liststr, All, HevaHoac, ColorOne, BoldOne, ItalicOne, UnderLineTwo, HghtlightTwo, ColorTwo, ColorThree, RunTexToWord);
                 FolderSaveFile.Text = Directory.GetCurrentDirectory() + @"\LuuFile";
                 System.Windows.Forms.MessageBoxEx.Show("Chuyển thành công file" + fileName + ", file được lưu trong thư mục LuuFile", 2000);
                 app.Quit();
             }
             catch
             {
             }
         }
     });
 }
Exemple #8
0
        public override void RunCommand(object sender)
        {
            var         engine       = (IAutomationEngineInstance)sender;
            var         wordObject   = v_InstanceName.GetAppInstance(engine);
            Application wordInstance = (Application)wordObject;
            bool        saveOnExit;

            if (v_WordSaveOnExit == "Yes")
            {
                saveOnExit = true;
            }
            else
            {
                saveOnExit = false;
            }

            //check if document exists and save
            if (wordInstance.Documents.Count >= 1)
            {
                wordInstance.ActiveDocument.Close(saveOnExit);
            }

            //close word
            wordInstance.Quit();

            //remove instance
            v_InstanceName.RemoveAppInstance(engine);
        }
Exemple #9
0
        public void PrintReport()
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue    = true;
            Object oFalse   = false;

            oWord         = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            string activePrinter = oWord.ActivePrinter;

            if (string.IsNullOrEmpty(this.m_PrinterName) == false)
            {
                oWord.ActivePrinter = m_PrinterName;
            }

            Object oFile = this.m_ReportSaveFileName;

            Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref oFile, ref oMissing, ref oTrue,
                                                                              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);

            doc.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterMiddleBin;

            doc.PrintOut(ref oFalse, ref oMissing, ref oMissing, ref oMissing,
                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oFalse,
                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            oWord.ActivePrinter = activePrinter;
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
        }
Exemple #10
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] mmkey = Encoding.Unicode.GetBytes(textBox3.Text);
                var    mtwM  = new MyTwofishManagedTransform(mmkey);

                if (checkBox2.Checked)
                {
                    string extension = Path.GetExtension(decryptPath);
                    if (extension == ".txt")
                    {
                        string str = File.ReadAllText(decryptPath);
                        decryptedText = Encoding.Unicode.GetBytes(str);
                    }
                    else
                    {
                        Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
                        Microsoft.Office.Interop.Word.Document    document    = application.Documents.Open(decryptPath);
                        decryptedText = Encoding.Unicode.GetBytes(document.Content.Text);

                        application.Quit();
                    }
                }
                else
                {
                    decryptedText = Encoding.Unicode.GetBytes(textBox1.Text);
                }

                encryptedText = mtwM.Encrypt(decryptedText, 0, decryptedText.Count());
                if (checkBox1.Checked)
                {
                    string extension = Path.GetExtension(encryptPath);
                    if (extension == ".txt")
                    {
                        File.WriteAllText(encryptPath, Encoding.Unicode.GetString(encryptedText));
                    }
                    else
                    {
                        Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                        Microsoft.Office.Interop.Word.Document    doc = app.Documents.Open(encryptPath);
                        doc.Content.Text = Encoding.Unicode.GetString(encryptedText);
                        doc.Save();
                        app.Quit();
                    }
                }
                else
                {
                    textBox2.Text = Encoding.Unicode.GetString(encryptedText);
                }
                MessageBox.Show("Encrypted text is writed!");
            }
            catch (ArgumentOutOfRangeException eq)
            {
                MessageBox.Show("Invalid input text");
            }
            catch (Exception eq) {
                MessageBox.Show("Error! =(");
            }
        }
Exemple #11
0
        public static void PrintWordDoc(YellowstonePathology.Business.OrderIdParser orderIdParser)
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue    = true;
            Object oFalse   = false;
            Object oCopies  = 1;

            oWord = new Microsoft.Office.Interop.Word.Application();
            string currentPrinter = oWord.ActivePrinter;

            oWord.Visible = false;

            Object oFile = CaseDocument.GetCaseFileNameDoc(orderIdParser);

            Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref oFile, 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);

            doc.PrintOut(ref oFalse, ref oMissing, ref oMissing, ref oMissing,
                         ref oMissing, ref oMissing, ref oMissing, ref oCopies, ref oMissing, ref oMissing, ref oFalse,
                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            CaseDocument.ReleaseComObject(doc);
            oWord.ActivePrinter = currentPrinter;
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            CaseDocument.ReleaseComObject(oWord);
        }
        public static void SaveDocAsXPS(string fileName)
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue = true;
            Object oFalse = false;

            oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            string currentPrinter = oWord.ActivePrinter;
            oWord.ActivePrinter = "Microsoft XPS Document Writer";

            Object docFileName = fileName;
            Object xpsFileName = fileName.Replace(".doc", ".xps");

            Object fileFormat = "wdFormatDocument";

            if (System.IO.File.Exists(docFileName.ToString()) == true)
            {
                Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref docFileName, 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);

                object oOutputFile = xpsFileName;
                doc.PrintOut(ref oFalse, ref oFalse, ref oMissing, ref oOutputFile, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            }

            oWord.ActivePrinter = currentPrinter;
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
        }
        public MedicalModel AddFromFileClass(object path)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss = System.Reflection.Missing.Value;

            object readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            string allText = docs.Content.Text;

            string[] needTxt = allText.Split(new char[] { ' ', '\n', '\r' });

            MedicalModel md = new MedicalModel
            {
                Complaints     = tS.GetDataFromDoc("Жалобы:", "Anamnes:", needTxt),
                Anamnes        = tS.GetDataFromDoc("Anamnes:", "StatusPraesens:", needTxt),
                StatusPraesens = tS.GetDataFromDoc("StatusPraesens:", "LocalStatus:", needTxt),
                LocalStatus    = tS.GetDataFromDoc("LocalStatus:", "Diagnos:", needTxt),
                Diagnos        = tS.GetDataFromDoc("Diagnos:", "Рекомендации:", needTxt)
            };

            docs.Close();
            word.Quit();
            return(md);
        }// doc
        public MedicalModel AddFromFileDbFile(object path)// doc doctemplateservice - заменить
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss = System.Reflection.Missing.Value;

            object readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            string allText = docs.Content.Text;

            string[] needTxt = allText.Split(new char[] { ' ', '\n', '\r' });

            MedicalModel md = new MedicalModel
            {
                Complaints     = tS.GetDataFromDoc("Жалобы:", "Анамнез:", needTxt),
                Anamnes        = tS.GetDataFromDoc("Анамнез:", "ОбщийСтатус:", needTxt),
                StatusPraesens = tS.GetDataFromDoc("ОбщийСтатус:", "МестныйСтатус:", needTxt),
                LocalStatus    = tS.GetDataFromDoc("МестныйСтатус:", "ПредварительныйДиагноз:", needTxt),
                Diagnos        = tS.GetDataFromDoc("ПредварительныйДиагноз:", "Рекомендации:", needTxt)
            };

            docs.Close();
            word.Quit();
            return(md);
        }
        public string ReadMsword(string filePath)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

            try
            {
                object miss = System.Reflection.Missing.Value;
                object path = filePath;
                //lbWordDocs.Items.Add(filePath);
                //rtbox.Text()
                object readOnly = false;
                Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                docs.ActiveWindow.Selection.WholeStory();
                docs.ActiveWindow.Selection.Copy();
                data = Clipboard.GetDataObject();
                //rtbox.Text = (string)(data.GetData(DataFormats.Text));
                docs.Close(ref miss, ref miss, ref miss);
                word.Quit(ref miss, ref miss, ref miss);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(word);
            }

            //return (data.GetData(DataFormats.Text).ToString());
            return(data.GetData(DataFormats.Text).ToString());
        }
        private string[] readDocx(string path)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss       = System.Reflection.Missing.Value;
            object pathObject = path;
            //object path2 = @"C:\Users\SA02- Frederik\Documents\Case05PigLatin\testInputFiles\InputText.txt";
            object readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref pathObject, ref miss, ref readOnly, ref miss, ref miss,
                                                                              ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            string totalText = "";

            //the whole document
            for (int i = 0; i < docs.Paragraphs.Count; i++)
            {
                //Determine the beginning of an entire paragraph and intercept the table name
                //Get the column name
                //......
                totalText += docs.Paragraphs[i + 1].Range.Text.ToString();
            }
            //Console.Write(totalText);
            docs.Close();
            word.Quit();
            string[] ret;

            if (_myFileType != ".txt")
            {
                ret = formatOddFileLayout(totalText);
            }
            else
            {
                ret = totalText.Split(_splitter, StringSplitOptions.None);
            }
            return(ret);
        }
Exemple #17
0
        private void DökümanHazırla()
        {
            var application = new Microsoft.Office.Interop.Word.Application();
            var document    = new Microsoft.Office.Interop.Word.Document();

            application.Visible = false;
            document            = application.Documents.Add(path);

            foreach (Microsoft.Office.Interop.Word.Field field in document.Fields)
            {
                if (field.Code.Text.Contains("isAdi"))
                {
                    field.Select();
                    application.Selection.TypeText(HerkezeAçıkİhaleHizmetAlımıİdariŞartName.isAdi);
                }
                else if (field.Code.Text.Contains("kayıtno"))
                {
                    field.Select();
                    application.Selection.TypeText(HerkezeAçıkİhaleHizmetAlımıİdariŞartName.kayıtno);
                }
            }

            document.SaveAs2(path1);
            document.Close();
            application.Quit();
            richEditControl1.LoadDocument(path1);
        }
Exemple #18
0
        private void button8_Click(object sender, EventArgs e)
        {
            dataGridView3.DataSource = Base.customersWithAdvance(!textBox10.Text.Equals("") ? textBox10.Text : "0");

            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = app.Documents.Open(Application.StartupPath.ToString() + "\\goodCustomersMore0.docx");
            object missing = System.Reflection.Missing.Value;
            string sum     = "                                               Customers who have money on the bill! \n\n";

            try
            {
                string[] array = wateBase.getBaseContent("SELECT * FROM customers WHERE SUMMERY < " + (!textBox10.Text.Equals("")?textBox10.Text:"0"));
                for (int i = 0; i < array.Length; i++)
                {
                    string a = array[i];
                    sum += "" + a + "\n";
                }
                doc.Content.Text = sum;
                doc.Save();
                doc.Close(ref missing);
                app.Quit(ref missing);
                MessageBox.Show("File successfully created\n" + Application.StartupPath.ToString());
            }
            catch (Exception)
            {
                MessageBox.Show("Imposible to create file");
            }
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        fileName = FileUpload1.PostedFile.FileName;
        myfullPath = Server.MapPath("Files/" + fileName);
        FileUpload1.SaveAs(Server.MapPath("Files/" + fileName));
        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        object miss = System.Reflection.Missing.Value;

        object path = Server.MapPath("Files/" + fileName);
        object readOnly = true;
        Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
        string totaltext = "";
        for (int i = 0; i < docs.Paragraphs.Count; i++)
        {
            totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
        }

        PreviewTheoryTextBox.Text = totaltext;

        //kratao to onoma tou arxeiou doc se label pou den fainetai
        LabelToKeepFileName.Text = fileName;
        docs.Close();
        word.Quit();
        FileUpload1.Visible = false;
    }
Exemple #20
0
 private bool OpenDocument(string docName, int pid)
 {
     bool bSuccess = false;
     Microsoft.Office.Interop.Word.Application tWord;
     DateTime sTime;
     DateTime eTime;
     try
     {
         tWord = new Microsoft.Office.Interop.Word.Application();
         sTime = DateTime.Now;
         wordObj = new Microsoft.Office.Interop.Word.Application();
         eTime = DateTime.Now;
         tWord.Quit(false);
         Marshal.ReleaseComObject(tWord);
         tWord = null;
         wordObj.Visible = false;
         pid = GETPID(sTime, eTime);
         //now do stuff
         wordObj.Documents.OpenNoRepairDialog(docName);
         //other code
         if (wordObj != null)
         {
             wordObj.Quit(false);
             Marshal.ReleaseComObject(wordObj);
             wordObj = null;
         }
         bSuccess = true;
     }
     catch
     { }
     return bSuccess;
 }
Exemple #21
0
 private void button2_Click(object sender, EventArgs e)
 {
     saveFileDialog1.Filter       = "Microsoft Word document(*.docx)|*.docx";
     saveFileDialog1.AddExtension = true;
     saveFileDialog1.ShowDialog();
     if (saveFileDialog1.FileName != "")
     {
         try
         {
             string[] mas = new string[5];
             mas = saveFileDialog1.FileName.Split('.');
             if (mas[1] == "docx" || mas[1] == "doc")
             {
                 Microsoft.Office.Interop.Word._Application app = new Microsoft.Office.Interop.Word.Application();
                 Microsoft.Office.Interop.Word.Document     doc = app.Documents.Add();
                 doc.Paragraphs[1].Range.Text = doc_content;
                 Clipboard.SetImage(pictureBox1.Image);
                 doc.Paragraphs[doc.Paragraphs.Count].Range.Paste();
                 app.Visible = false;
                 doc.SaveAs2(saveFileDialog1.FileName);
                 doc.Close();
                 app.Quit();
                 MessageBox.Show("Файл сохранен!", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
             }
             else
             {
                 MessageBox.Show("Недопустимый тип файла!", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
         }
         catch (Exception exc)
         {
             MessageBox.Show(exc.Message.ToString(), exc.Source.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
    public string Print(Stream wordDocStream)
    {
        // copy our stream to a local file
        var tempFile = Path.GetTempFileName();

        using (var file = File.Create(tempFile))
        {
            wordDocStream.CopyTo(file);
        }

        // start word
        var wordApp = new Microsoft.Office.Interop.Word.Application();

        // setup printer
        wordApp.ActivePrinter = "Canon LBP3010/LBP3018/LBP3050";
        // open, collect data, print and close
        var doc = wordApp.Documents.Open(tempFile);

        doc.PrintOut();
        var res = doc.Words.Count;

        doc.Close(false);

        // quit word
        wordApp.Quit(false);
        // delete temp file
        File.Delete(tempFile);
        return(String.Format("{0} words", res));
    }
Exemple #23
0
 // деструктор
 public void Close()
 {
     //SaveDictionary();
     WordApp.Quit();
     WordApp = null;
     Log.Write("words Закрыли очередную копию MS Word");
 }
Exemple #24
0
        private static void ConvertWord(Microsoft.Office.Interop.Word.WdSaveFormat format, string fileName, string sourceFile)
        {
            Microsoft.Office.Interop.Word.Document    wordDoc = null;
            Microsoft.Office.Interop.Word.Application word    = null;

            try
            {
                word = new Microsoft.Office.Interop.Word.Application
                {
                    Visible = false
                };
                wordDoc = word.Documents.Open(sourceFile, false);

                wordDoc.SaveAs2(FileName: fileName, FileFormat: format);
                wordDoc.Close();
                word.Quit();
            }
            catch (Exception ex)
            {
                try
                {
                    wordDoc?.Close();
                    word?.Quit();
                }
                catch { }

                throw;
            }
        }
Exemple #25
0
 private void btnRead_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
         object miss = System.Reflection.Missing.Value;
         //object path = @"C:\TEXT\Cauhoi.docx";
         string filename = @"C:\TEXT\dapan.txt";
         object path     = txtPath.Text;
         object readOnly = true;
         Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
         string totaltext = "";
         for (int i = 6; i < docs.Paragraphs.Count; i += 5)
         {
             //totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
             totaltext += docs.Paragraphs[i + 1].Range.Text;
             //MessageBox.Show(totaltext);
         }
         //Console.WriteLine(totaltext);
         bll.WriteToText(totaltext, filename);
         docs.Close();
         word.Quit();
         MessageBox.Show("OK ", "Mess", MessageBoxButton.OK, MessageBoxImage.Information);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error + " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Exemple #26
0
        private void btn_SaveDocument_Click(object sender, RoutedEventArgs e)
        {
            forms.SaveFileDialog save = new forms.SaveFileDialog();

            save.DefaultExt = ".doc";

            if (save.ShowDialog() == forms.DialogResult.OK)
            {
                document_address = save.FileName;
                document.SaveToFile(document_address);

                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                app.Visible = false;
                Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(document_address);
                Microsoft.Office.Interop.Word.Range    r   = doc.Content;
                r.Find.ClearFormatting();
                r.Find.Execute(FindText: "Evaluation Warning: The document was created with Spire.Doc for .NET.", ReplaceWith: "");
                doc.SaveAs(document_address);

                doc.Close();
                app.Quit();

                MessageBox.Show("Документ успешно сохранен");
            }
        }
Exemple #27
0
        static void word2pdf(string inputPath, string outputPath)
        {
            if (!File.Exists(inputPath))
            {
                throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
            }

            try
            {
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

                app.Documents.Open(
                    inputPath,
                    // Confirm Conversion
                    Microsoft.Office.Core.MsoTriState.msoFalse,
                    // Read Only
                    Microsoft.Office.Core.MsoTriState.msoTrue)
                .SaveAs(
                    outputPath,
                    Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
                app.Quit();
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
            }
        }
        public static void SaveDocAsXPS(string fileName)
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue    = true;
            Object oFalse   = false;

            oWord         = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            string currentPrinter = oWord.ActivePrinter;

            oWord.ActivePrinter = "Microsoft XPS Document Writer";

            Object docFileName = fileName;
            Object xpsFileName = fileName.Replace(".doc", ".xps");

            Object fileFormat = "wdFormatDocument";

            if (System.IO.File.Exists(docFileName.ToString()) == true)
            {
                Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref docFileName, 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);

                object oOutputFile = xpsFileName;
                doc.PrintOut(ref oFalse, ref oFalse, ref oMissing, ref oOutputFile, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                             ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            }

            oWord.ActivePrinter = currentPrinter;
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
        }
Exemple #29
0
        // General idea is based on: https://stackoverflow.com/a/7937590/700926
        static void Main()
        {
            // Open a doc file
            var wordApplication = new Application();
            var document        = wordApplication.Documents.Open(@"C:\Users\Username\Documents\document.docx");

            // Load the image to compare against.
            var bitmapToCompareAgainst = new Bitmap(@"C:\Users\Username\Documents\image.png");

            // For each inline shape, do a comparison
            // By inspection you can see that the first inline shape have index 1 ( and not zero as one might expect )
            for (var i = 1; i <= wordApplication.ActiveDocument.InlineShapes.Count; i++)
            {
                // closure
                // http://confluence.jetbrains.net/display/ReSharper/Access+to+modified+closure
                var inlineShapeId = i;
                // parameterized thread start
                // https://stackoverflow.com/a/1195915/700926
                var thread = new Thread(() => CompareInlineShapeAndBitmap(inlineShapeId, bitmapToCompareAgainst, wordApplication));
                // STA is needed in order to access the clipboard
                // https://stackoverflow.com/a/518724/700926
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();
            }
            // Close word
            wordApplication.Quit();
            Console.ReadLine();
        }
Exemple #30
0
        protected void download_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            if (fileUpload.HasFile)
            {
                try
                {
                    sb.AppendFormat(" Uploading file: {0}", fileUpload.FileName);

                    string pathToFile = System.Reflection.Assembly.GetExecutingAssembly().Location + fileUpload.FileName;

                    fileUpload.SaveAs(pathToFile);

                    //Showing the file information
                    sb.AppendFormat("\n Save As: {0}", fileUpload.PostedFile.FileName);
                    sb.AppendFormat("\n File type: {0}", fileUpload.PostedFile.ContentType);
                    sb.AppendFormat("\n File length: {0}", fileUpload.PostedFile.ContentLength);
                    sb.AppendFormat("\n File name: {0}", fileUpload.PostedFile.FileName);

                    if (fileUpload.PostedFile.ContentType.ToString().ToLower() == "text/plain")
                    {
                        textbox.Text = File.ReadAllText(pathToFile, Encoding.Default);
                    }
                    else if (fileUpload.PostedFile.ContentType.ToString().ToLower() == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || fileUpload.PostedFile.ContentType.ToString().ToLower() == "doc")
                    {
                        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                        object path = pathToFile;
                        Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path);
                        string text = "";

                        text = docs.Content.Text;

                        docs.Close();
                        word.Quit();

                        while (text[0] == ' ')
                        {
                            text.Remove(0, 1);
                        }

                        textbox.Text = text;
                    }
                    else
                    {
                        textbox.Text = fileUpload.PostedFile.ContentType.ToString().ToLower();
                    }
                }
                catch (Exception ex)
                {
                    sb.Append("\n Error \n");
                    sb.AppendFormat("Unable to save file \n {0}", ex.Message);
                    textbox.Text = sb.ToString();
                }
            }
            else
            {
                lblmessage.Text = sb.ToString();
            }
        }
Exemple #31
0
        public int getpage(object file)
        {
            try
            {
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                object nullobj = System.Reflection.Missing.Value;

                Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(
                    ref file, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj);
                doc.ActiveWindow.Selection.WholeStory();
                doc.ActiveWindow.Selection.Copy();
                IDataObject data = Clipboard.GetDataObject();

                // get number of pages
                Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
                int pages = doc.ComputeStatistics(stat, Type.Missing);

                //string text = data.GetData(DataFormats.Text).ToString();  //获取具体内容,此项目不需要

                doc.Close(ref nullobj, ref nullobj, ref nullobj);
                app.Quit(ref nullobj, ref nullobj, ref nullobj);


                return(pages);
            }
            catch (Exception ex)
            {
                ex.ToString();
                return(0);
            }
        }
Exemple #32
0
        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            try
            {
                if (!this.disposed)
                {
                    // If disposing equals true, dispose all managed
                    // and unmanaged resources.
                    if (disposing)
                    {
                        // Dispose managed resources.
                    }
                    oWordDoc.Close();
                    oWordDoc = null;
                    oWord.Quit(true);
                    oWord = null;
                    // Release unmanaged resources. If disposing is false,
                    // only the following code is executed.

                    // Note that this is not thread safe.
                    // Another thread could start disposing the object
                    // after the managed resources are disposed,
                    // but before the disposed flag is set to true.
                    // If thread safety is necessary, it must be
                    // implemented by the client.
                }
                disposed = true;
            }
            catch (Exception)
            {
            }
        }
Exemple #33
0
        Node Word_Veri_Al(object adres, bool kelimeayir)
        {
            Node NodeWord = null;

            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            object readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref adres, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            if (kelimeayir)
            {
                for (int i = 0; i < docs.Paragraphs.Count; i++)//Yakin eşleşmede kelime kelime NodeWord'e ekliyor.
                {
                    NodeWord = ekle(NodeWord, Kelime_Ayir(docs.Paragraphs[i + 1].Range.Text.ToString()));
                }
            }
            else
            {
                for (int i = 0; i < docs.Paragraphs.Count; i++)//Tam eşleşmede satir satir NodeWord'e ekliyor.
                {
                    NodeWord = ekle(NodeWord, docs.Paragraphs[i + 1].Range.Text.ToString());
                }
            }
            docs.Close(); //Sayfayi kapatiyor.
            word.Quit();  //Programi komple kapatiyor.
            return(NodeWord);
        }
Exemple #34
0
        static void Main(string[] args)
        {
            //using Word = Microsoft.Office.Interop.Word;

            object fileName = Path.Combine(@"D:\VS2010Workspace\WordDocReplaceTest\WordDocReplaceTest\bin\Release", "TestDoc.docx");
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application { Visible = false };

            Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref fileName, ReadOnly: false, Visible: true);

            aDoc.Activate();

            Microsoft.Office.Interop.Word.Find fnd = wordApp.ActiveWindow.Selection.Find;

            fnd.ClearFormatting();
            fnd.Replacement.ClearFormatting();
            fnd.Forward = true;
            fnd.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;

            fnd.Text = "{替换前内容}";
            fnd.Replacement.Text = "替换后内容-updated";

            fnd.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            aDoc.Save();

            aDoc.Close(ref missing, ref missing, ref missing);
            wordApp.Quit(ref missing, ref missing, ref missing);
        }
Exemple #35
0
        void OpenFile(string filepath, int selectionstart)
        {
            cache["lastdir"] = Path.GetDirectoryName(filepath);
            string fileext = Path.GetExtension(filepath).ToLower();
            if (fileext == ".doc" || fileext == ".docx")
            {
                object oMissing = System.Reflection.Missing.Value;
                object isReadOnly = true;
                Microsoft.Office.Interop.Word._Application oWord;
                Microsoft.Office.Interop.Word._Document oDoc;

                oWord = new Microsoft.Office.Interop.Word.Application();
                oWord.Visible = false;
                object fileName = filepath;
                oDoc = oWord.Documents.Open(ref fileName,
                ref oMissing, ref isReadOnly, 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);

                this.rtbxMain.Text = oDoc.Content.Text;
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                if (MessageBox.Show("转换为RTF文档并重新打开?", "转换格式", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string newrtfpath = filepath + ".rtf";
                    this.rtbxMain.SaveFile(newrtfpath, RichTextBoxStreamType.RichText);
                    MessageBox.Show("转换为rtf成功.\r\n保存位置:" + newrtfpath, "转换格式");
                    OpenFile(newrtfpath, selectionstart);
                    return;
                }
            }
            else
            {
                FileStream fs = File.Open(filepath, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs, Encoding.Default, true);

                if (fileext == ".rtf")
                {
                    this.rtbxMain.Rtf = sr.ReadToEnd();
                    this.rtbxMain.Font = new Font("微软雅黑", 14f);
                }
                else
                {
                    rtbxMain.Text = sr.ReadToEnd();
                }
                sr.Close();
                fs.Close();
                fs.Dispose();
                sr.Dispose();
            }
            rtbxMain.SelectionStart = selectionstart;
            currentfilepath = filepath;
            this.Text = Path.GetFileNameWithoutExtension(currentfilepath);
            this.Icon = ((System.Drawing.Icon)(new System.ComponentModel.ComponentResourceManager(typeof(MainForm)).GetObject("$this.Icon")));
            tsmiReplaceWindowsTitle.Text = "隐藏标题";
            this.tsmiCurrentFilename.Text = this.Text;
            this.notifyIcon1.Text = this.Text;
        }
Exemple #36
0
 private void btn_Read_Click(object sender, EventArgs e)
 {
     Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();//实例化Word对象
     Microsoft.Office.Interop.Word.Table table;//声明Word表格对象
     int P_int_TableCount = 0, P_int_Row = 0, P_int_Column = 0;//定义3个变量,分别用来存储表格数量、表格中的行数、列数
     string P_str_Content;//存储Word表格的单元格内容
     object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
     string[] P_str_Names = txt_Word.Text.Split(',');//存储所有选择的Word文件名
     object P_obj_Name;//存储遍历到的Word文件名
     Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//实例化Excel对象
     //打开指定的Excel文件
     Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Open(txt_Excel.Text, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
     Microsoft.Office.Interop.Excel.Worksheet newWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add(missing, missing, missing, missing);//创建新工作表
     for (int i = 0; i < P_str_Names.Length - 1; i++)//遍历所有选择Word文件名
     {
         P_obj_Name = P_str_Names[i];//记录遍历到的Word文件名
         //打开Word文档
         Microsoft.Office.Interop.Word.Document document = word.Documents.Open(ref P_obj_Name, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
         P_int_TableCount = document.Tables.Count;//获取Word文档中表格的数量
         if (P_int_TableCount > 0)//判断表格数量是否大于0
         {
             for (int j = 1; j <= P_int_TableCount; j++)//遍历所有表格
             {
                 table = document.Tables[j];//记录遍历到的表格
                 P_int_Row = table.Rows.Count;//获取表格行数
                 P_int_Column = table.Columns.Count;//获取表格列数
                 for (int row = 1; row <= P_int_Row; row++)//遍历表格中的行
                 {
                     for (int column = 1; column <= P_int_Column; column++)//遍历表格中的列
                     {
                         P_str_Content = table.Cell(row, column).Range.Text;//获取遍历到的单元格内容
                         newWorksheet.Cells[i + row, column] = P_str_Content.Substring(0, P_str_Content.Length - 2);//将遍历到的单元格内容添加到Excel单元格中
                     }
                 }
             }
         }
         else
         {
             if (P_int_Row == 0)//判断前面是否已经填充过表格
                 newWorksheet.Cells[i + P_int_Row + 1, 1] = document.Content.Text;//直接将Word文档内容添加到工作表中
             else
                 newWorksheet.Cells[i + P_int_Row, 1] = document.Content.Text;//直接将Word文档内容添加到工作表中
         }
         document.Close(ref missing, ref missing, ref missing);//关闭Word文档
     }
     excel.Application.DisplayAlerts = false;//不显示提示对话框
     workbook.Save();//保存工作表
     workbook.Close(false, missing, missing);//关闭工作表
     word.Quit(ref missing, ref missing, ref missing);//退出Word应用程序
     MessageBox.Show("已经成功将多个Word文档的内容合并到了Excel的同一个数据表中!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
        public void CreateDocument()
        {
            string filePath = Path.GetTempFileName() + ".docx";
            try
            {
                //Create an instance for word app
                winword = new Microsoft.Office.Interop.Word.Application();

                //Set animation status for word application
                //winword. ShowAnimation = false;

                //Set status for word application is to be visible or not.
                winword.Visible = false;

                //Create a new document
                document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                this.PrintTree(ClasificacionSingleton.Clasificacion, 0);

                foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                {
                    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdGray50;
                    footerRange.Font.Size = 12;
                    footerRange.Text = DateTimeUtilities.ToLongDateFormat(DateTime.Now);
                }

                //Save the document
                object filename = filePath;
                document.SaveAs2(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                MessageBox.Show("Estructura generada satisfactoriamente!");

                System.Diagnostics.Process.Start(filePath);
            }
            catch (Exception ex)
            {
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                ErrorUtilities.SetNewErrorMessage(ex, methodName + " Exception,PdfTreeStructure", "MateriasSGA");
            }
        }
        public static string GetText(string filePath)
        {
            var rangeText = "ERROR: Failed to get text";

            var assembly = Assembly.GetExecutingAssembly();
            var binPath = System.IO.Path.GetDirectoryName(assembly.Location);

            var inputFile = Path.Combine(binPath, filePath);

            //  create & define filename object with temp.doc
            object inputDocFilename = inputFile;

            if (File.Exists((string)inputDocFilename))
            {
                object readOnly = false;
                object isVisible = false;

                //  create missing object
                object missing = Missing.Value;

                //  create Word application object
                var wordApp = new Microsoft.Office.Interop.Word.Application();

                wordApp.Visible = false;

                var inputDocument = wordApp.Documents.Open(ref inputDocFilename, ref missing,
                        ref readOnly, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref isVisible, ref missing, ref missing,
                        ref missing, ref missing);

                inputDocument.Activate();

                rangeText = inputDocument.Range().Text;

                inputDocument.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);

                wordApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
            }

            return rangeText;
        }
Exemple #39
0
 public void GetFileCount(string path,out int FileCount)
 {
     FileCount = 1;
     object tempFileName = path;
     FileInfo fi = new FileInfo(path);
     string astdt = fi.Extension;
     object strFileName = fi.Name;
     object flg = false;
     object oMissing = System.Reflection.Missing.Value;
     switch (astdt.ToLower())
     {
         case ".doc":
         case ".docx":
             astdt = "pdf";
             Microsoft.Office.Interop.Word._Application oWord;
             Microsoft.Office.Interop.Word._Document oDoc;
             oWord = new Microsoft.Office.Interop.Word.Application();
             //oWord.Visible = true;
             oDoc = oWord.Documents.Open(ref tempFileName,
             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);
             try
             {
                 // 计算Word文档页数
                 Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
                 FileCount = oDoc.ComputeStatistics(stat, ref oMissing);
                 return;
             }
             catch (Exception ex)
             {
                 if (oDoc == null) XLog.XTrace.WriteLine(ex.Message);
                 throw (ex);
             }
             finally
             {
                 oDoc.Close(ref flg, ref oMissing, ref oMissing);
                 oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
             }
         default:
             break;
     }
 }
Exemple #40
0
        public void CreateWord(String HtmlFile, string fileWord)
        {
            object filename1 = HtmlFile;

            object oMissing = System.Reflection.Missing.Value;

            object oFalse = false;

            Microsoft.Office.Interop.Word.Application oWord = new
            Microsoft.Office.Interop.Word.Application();

            Microsoft.Office.Interop.Word.Document oDoc = new
            Microsoft.Office.Interop.Word.Document();

            oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref
            oMissing, ref oMissing);

            oWord.Visible = false;

            oDoc = oWord.Documents.Open(ref filename1, 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);

            filename1 = fileWord;

            object fileFormat =
            Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;

            oDoc.SaveAs(ref filename1, ref fileFormat, 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);

            oDoc.Close(ref oFalse, ref oMissing, ref oMissing);

            oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
        }
Exemple #41
0
        /// <summary>
        /// ファイルをPDF形式で保存
        /// </summary>
        public override void SavePdf()
        {
            Microsoft.Office.Interop.Word.Application word = null;
            Microsoft.Office.Interop.Word.Documents docs = null;
            Microsoft.Office.Interop.Word.Document d = null;

            try
            {
                //ファイルを取得
                object file = this.GetAbsolutePath();
                word = new Microsoft.Office.Interop.Word.Application();
                docs = word.Documents;
                d = docs.Open(file);

                d.ExportAsFixedFormat(this.GetPdfPath(),
                    Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF,
                    false,
                    Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
                    Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument);

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
            finally
            {
                if (d != null)
                {
                    d.Close();
                }
                if (word != null)
                {
                    word.Quit();
                }
            }
        }
Exemple #42
0
        /// <summary>
        /// The metod convert from DOC to RTF
        /// </summary>
        /// <param name="Source"> The source doc file </param>
        /// <returns> The target file path </returns>
        public static string ConvertDOCtoRTF(string sSource)
        {
            //Creating the instance of Word Application
            Microsoft.Office.Interop.Word.Application newApp = new Microsoft.Office.Interop.Word.Application();

            // specifying the Source & Target file names
            object Source = sSource;
            object Target = Path.GetDirectoryName(sSource) + "\\" + Path.GetFileNameWithoutExtension(sSource) + ".TXT";

            // Use for the parameter whose type are not known or
            // say Missing
            object Unknown = Type.Missing;

            // 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);

            // Specifying the format in which you want the output file
            object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatText;

            //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);

            // for closing the application
            newApp.Quit(ref Unknown, ref Unknown, ref Unknown);

            return (Target.ToString());
        }
        public void DoIt()
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            app.Visible = false;

            int errors = 0;
            if (this.TextBoxSpell.Text.Length > 0)
            {
                object template = Type.Missing;
                object newTemplate = Type.Missing;
                object documentType = Type.Missing;
                object visible = true;

                Microsoft.Office.Interop.Word._Document doc1 = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);
                doc1.Words.First.InsertBefore(this.TextBoxSpell.Text);
                Microsoft.Office.Interop.Word.ProofreadingErrors spellErrorsColl = doc1.SpellingErrors;
                errors = spellErrorsColl.Count;

                object optional = Type.Missing;

                app.ActiveWindow.Activate();

                doc1.CheckSpelling(
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional,
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);

                object first = 0;
                object last = doc1.Characters.Count - 1;
                this.TextBoxSpell.Text = doc1.Range(ref first, ref last).Text;
            }

            object saveChanges = false;
            object originalFormat = Type.Missing;
            object routeDocument = Type.Missing;

            app.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
        }
Exemple #44
0
        public void PrintEnvelope(string line1, string line2, string line3)
        {
            line1 += "\n\n";
            line2 += "\n\n";
            line3 += "\n\n";

            oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            object oAddress = line1 + line2 + line3;

            doc.Envelope.PrintOut(ref oMissing, ref oAddress, 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, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            while (oWord.BackgroundPrintingStatus.ToString() == "1")
            {
                //do nothing while waiting for printer to get moving
            }
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
        }
        private void btSaveAs_Click(object sender, EventArgs e)
        {
            sfFatigueResults.FileName = this.lbDescription.Text;
            if (sfFatigueResults.ShowDialog() == DialogResult.OK)
            {
                string path = System.IO.Directory.GetCurrentDirectory() + "\\";
                string selectedExtension = FilterExtensions[sfFatigueResults.FilterIndex - 1];
                switch (selectedExtension)
                {
                    case "*.docx":
                        File.WriteAllText("./fatigueResults.html", htmlFile.ToString() + htmlFileClose.ToString());
                        var wordx = new Microsoft.Office.Interop.Word.Application();
                        wordx.Visible = false;
                        var wordDocx = wordx.Documents.Open(FileName: path + "fatigueResults.html", ReadOnly: false);
                        Microsoft.Office.Interop.Word.Range rng = wordDocx.Range();
                        object lastPosition = rng.StoryLength - 1;
                        rng = wordDocx.Range(ref lastPosition, ref lastPosition);
                        rng.Select();
                        wordDocx.Paragraphs.Add();
                        lastPosition = rng.StoryLength - 1;
                        rng = wordDocx.Range(ref lastPosition, ref lastPosition);
                        rng.Select();
                        rng.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        if (File.Exists(this.lbPictureDetail.Text))
                        {
                            var image = wordDocx.InlineShapes.AddPicture(this.lbPictureDetail.Text, false, true, rng);
                            Image figuraDetalhe = Image.FromFile(this.lbPictureDetail.Text);
                            image.Width = figuraDetalhe.Width * 72 / 96;
                            image.Height = figuraDetalhe.Height * 72 / 96;
                        }
                        wordDocx.SaveAs2(FileName: sfFatigueResults.FileName, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument);
                        wordDocx.Close(false);
                        wordx.Quit(false);
                        File.Delete("./fatigueResults.html");
                        break;
                    case "*.doc":
                        File.WriteAllText("./fatigueResults.html", htmlFile.ToString() + htmlFileClose.ToString());
                        var word = new Microsoft.Office.Interop.Word.Application();
                        word.Visible = false;
                        var wordDoc = word.Documents.Open(FileName: path + "fatigueResults.html", ReadOnly: false);
                        Microsoft.Office.Interop.Word.Range range = wordDoc.Range();
                        object endPosistion = range.StoryLength - 1;
                        rng = wordDoc.Range(ref endPosistion, ref endPosistion);
                        rng.Select();
                        wordDoc.Paragraphs.Add();
                        endPosistion = rng.StoryLength - 1;
                        rng = wordDoc.Range(ref endPosistion, ref endPosistion);
                        rng.Select();
                        rng.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        if (File.Exists(this.lbPictureDetail.Text))
                        {
                            var image = wordDoc.InlineShapes.AddPicture(this.lbPictureDetail.Text, false, true, rng);
                            Image figuraDetalhe = Image.FromFile(this.lbPictureDetail.Text);
                            image.Width = figuraDetalhe.Width * 72 / 96;
                            image.Height = figuraDetalhe.Height * 72 / 96;
                        }
                        wordDoc.SaveAs2(FileName: sfFatigueResults.FileName, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument);
                        wordDoc.Close(false);
                        word.Quit(false);
                        File.Delete("./fatigueResults.html");
                        break;
                    case "*.html": // OK
                        //converte imagem arquivo PNG para base64 para HTML arquivo unico
                        try { 
                            Image pictureDetail = Image.FromFile(this.lbPictureDetail.Text);

                            string figuraDetalheBase64 = "";

                            if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(pictureDetail.RawFormat))
                            {
                                figuraDetalheBase64 = @"data:image/jpg;base64," + ImageToBase64(pictureDetail, System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                            else if (System.Drawing.Imaging.ImageFormat.Png.Equals(pictureDetail.RawFormat))
                            {
                                figuraDetalheBase64 = @"data:image/png;base64," + ImageToBase64(pictureDetail, System.Drawing.Imaging.ImageFormat.Png);
                            }
                            else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(pictureDetail.RawFormat))
                            {
                                figuraDetalheBase64 = @"data:image/gif;base64," + ImageToBase64(pictureDetail, System.Drawing.Imaging.ImageFormat.Gif);
                            }
                            else if (System.Drawing.Imaging.ImageFormat.Bmp.Equals(pictureDetail.RawFormat))
                            {
                                figuraDetalheBase64 = @"data:image/bmp;base64," + ImageToBase64(pictureDetail, System.Drawing.Imaging.ImageFormat.Bmp);
                            }

                            this.htmlFileImage.Replace(this.lbPictureDetail.Text, figuraDetalheBase64);
                        } catch {
                            // do nothing
                        }
                        File.WriteAllText("./fatigueResults.html", htmlFile.ToString()+htmlFileImage.ToString()+htmlFileClose.ToString());
                        File.Copy("./fatigueResults.html", sfFatigueResults.FileName, true);
                        File.Delete("./fatigueResults.html");
                        break;
                    case "*.pdf":
                        File.WriteAllText("./fatigueResults.html", htmlFile.ToString() + htmlFileImage.ToString() + htmlFileClose.ToString());
                        var wordPdf = new Microsoft.Office.Interop.Word.Application();
                        wordPdf.Visible = false;
                        var wordDocPdf = wordPdf.Documents.Open(FileName: path + "fatigueResults.html", ReadOnly: false);
                        wordDocPdf.SaveAs2(FileName: sfFatigueResults.FileName, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
                        wordDocPdf.Close(false);
                        wordPdf.Quit(false);
                        File.Delete("./fatigueResults.html");
                        break;
                }
                File.Delete("./fatigueResults.html");

            }
        }
Exemple #46
0
    /*-------------------------word转化----------------------------------------------------------*/
    private static void WordToHtmlFile(string WordFilePath)
    {
        Microsoft.Office.Interop.Word.Application newApp = new Microsoft.Office.Interop.Word.Application();
        // 指定原文件和目标文件
        object Source = WordFilePath;
        string SaveHtmlPath = WordFilePath.Substring(0, WordFilePath.Length - 3) + "html";
        object Target = SaveHtmlPath;

        // 缺省参数
        object Unknown = Type.Missing;

        //为了保险,只读方式打开
        object readOnly = true;

        // 打开doc文件
        Microsoft.Office.Interop.Word.Document doc = newApp.Documents.Open(ref Source, ref Unknown,
        ref readOnly, 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);

        // 指定另存为格式(rtf)
        object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
        // 转换格式
        doc.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);

        // 关闭文档和Word程序
        doc.Close(ref Unknown, ref Unknown, ref Unknown);
        newApp.Quit(ref Unknown, ref Unknown, ref Unknown);
    }
        private void btn_CreateDirctToWord_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfd_Form = new SaveFileDialog();
                //设置文件类型
                sfd_Form.Filter = "Word(*.docx)|*.docx|Word(*.doc)|*.doc|All files(*.*)|*.*";

                //设置默认文件类型显示顺序
                sfd_Form.FilterIndex = 3;

                //保存对话框是否记忆上次打开的目录
                sfd_Form.RestoreDirectory = true;

                if (sfd_Form.ShowDialog() == DialogResult.OK)
                {
                    this.progressBar1.Visible = true;
                    for (int progressValue = 0; progressValue < 80; progressValue += 10)
                    {
                        System.Threading.Thread.Sleep(100);
                        progressBar1.Value = progressValue;

                    }

                    //获取所有的表名并除去字典表
                    string[] dbTableNames = SqlOperation.GetAllTableName();//数据库所有的表名
                    List<string> tableNames = new List<string>();//除去字典表的表名
                    foreach (string tableName in dbTableNames)
                    {
                        if (tableName != "tb_dict")
                        {
                            tableNames.Add(tableName);
                        }
                    }
                    //查询每张表所对应的字典表数据
                    List<System.Data.DataTable> listDtDicts = new List<System.Data.DataTable>();//储存所有表所对应的字典表

                    //获取字典表
                    foreach (string tableName in tableNames)
                    {
                        string sqlselectDict = "select * from tb_dict where TableName = '" + tableName + "'";
                        System.Data.DataTable dt = SqlOperation.SelectData(sqlselectDict);
                        listDtDicts.Add(dt);

                    }

                    Microsoft.Office.Interop.Word._Application app = new Microsoft.Office.Interop.Word.Application();//创建word应用程序
                    Microsoft.Office.Interop.Word._Document doc = app.Documents.Add();//添加一个word文档
                    object oMissing = System.Reflection.Missing.Value;

                    for (int tableIndex = 0; tableIndex < listDtDicts.Count; tableIndex++)
                    {
                        System.Data.DataTable dt = listDtDicts[tableIndex];
                        int rows = dt.Rows.Count + 1;//表格行数加1是为了标题栏
                        int cols = dt.Columns.Count;//表格列数

                        //输出大标题加粗加大字号水平居中
                        app.Selection.Font.Bold = 700;
                        app.Selection.Font.Size = 16;
                        app.Selection.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        app.Selection.Text = tableNames[tableIndex].ToString() + "字典表";

                        //换行添加表格
                        object line = Microsoft.Office.Interop.Word.WdUnits.wdLine;
                        app.Selection.MoveDown(ref line, oMissing, oMissing);
                        app.Selection.TypeParagraph();//换行

                        Microsoft.Office.Interop.Word.Range range = app.Selection.Range;
                        Microsoft.Office.Interop.Word.Table table = app.Selection.Tables.Add(range, rows, cols, ref oMissing, ref oMissing);

                        //设置表格的字体大小粗细
                        table.Range.Font.Size = 10;
                        table.Range.Font.Bold = 0;
                        //设置表格边框
                        table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

                        //设置表格标题
                        for (int field = 0; field < cols; field++)
                        {
                            //注意Word下标从一开始
                            table.Cell(1, field + 1).Range.Text = dt.Columns[field].ColumnName;
                        }

                        //循环数据创建数据行
                        for (int row = 0; row < dt.Rows.Count; row++)
                        {
                            for (int column = 0; column < cols; column++)
                            {
                                //对单元格设置上下居中
                                table.Cell(row + 2, column + 1).VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                                //写入数据
                                if (column == 0)
                                {
                                    table.Cell(row + 2, column + 1).Range.Text = (row + 1).ToString();
                                }
                                else
                                {
                                    table.Cell(row + 2, column + 1).Range.Text = dt.Rows[row][column].ToString();
                                }
                            }

                        }
                        //object WdStory = Microsoft.Office.Interop.Word.WdUnits.wdLine;
                        //app.Selection.EndKey(ref WdStory, ref oMissing);
                        object count = rows + 2;
                        object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;
                        app.Selection.MoveDown(ref WdLine, ref count, ref oMissing);//移动焦点
                        app.Selection.TypeParagraph();
                    }
                    //导出到文件
                    string filePath = sfd_Form.FileName.ToString();
                    doc.SaveAs(filePath,
                    oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                    oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

                    doc.Close();//关闭文档
                    app.Quit();//退出应用程序
                    this.progressBar1.Value = 100;
                    MessageBox.Show("导出成功!", "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.progressBar1.Visible = false;
                    this.progressBar1.Value = 30;
                }
            }
            catch (Exception ex)
            {

            }
        }
Exemple #48
0
 private void btn_Read_Click(object sender, EventArgs e)
 {
     object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
     string[] P_str_Names = txt_Excel.Text.Split(',');//存储所有选择的Excel文件名
     object P_obj_Name;//存储遍历到的Excel文件名
     Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();//实例化Word对象
     if (txt_Word.Text.EndsWith("\\"))//判断路径是否以\结尾
         P_obj_WordName = txt_Word.Text + DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc";//记录Word文件路径及名称
     else
         P_obj_WordName = txt_Word.Text + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc";//记录Word文件路径及名称
     Microsoft.Office.Interop.Word.Table table;//声明Word表格对象
     Microsoft.Office.Interop.Word.Document document = new Microsoft.Office.Interop.Word.Document();//声明Word文档对象
     document = word.Documents.Add(ref missing, ref missing, ref missing, ref missing);//新建Word文档
     Microsoft.Office.Interop.Word.Range range ;//声明范围对象
     int P_int_Rows = 0, P_int_Columns = 0;//存储工作表中数据的行数和列数
     object P_obj_start = 0, P_obj_end = 0;//分别记录创建表格的开始和结束范围
     object P_obj_Range = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd;//定义要合并的范围位置
     for (int i = 0; i < P_str_Names.Length - 1; i++)//遍历所有选择的Excel文件名
     {
         P_obj_Name = P_str_Names[i];//记录遍历到的Excel文件名
         List<string> P_list_SheetName = CBoxBind(P_obj_Name.ToString());//获取指定Excel中的所有工作表
         for (int j = 0; j < P_list_SheetName.Count; j++)//遍历所有工作表
         {
             range = document.Range(ref missing, ref missing);//获取Word范围
             range.InsertAfter(P_obj_Name + "——" + P_list_SheetName[j] + "工作表");//插入文本
             range.Font.Name = "宋体";//设置字体
             range.Font.Size = 10;//设置字体大小
             DataSet myds = CBoxShowCount(P_obj_Name.ToString(), P_list_SheetName[j]);//获取工作表中的所有数据
             P_int_Rows = myds.Tables[0].Rows.Count;//记录工作表的行数
             P_int_Columns = myds.Tables[0].Columns.Count;//记录工作表的列数
             range.Collapse(ref P_obj_Range);//合并范围
             if (P_int_Rows > 0 && P_int_Columns > 0)//判断如果工作表中有记录
             {
                 //在指定范围处添加一个指定行数和列数的表格
                 table = range.Tables.Add(range, P_int_Rows, P_int_Columns, ref missing, ref missing);
                 for (int r = 0; r < P_int_Rows; r++)//遍历行
                 {
                     for (int c = 0; c < P_int_Columns; c++)//遍历列
                     {
                         table.Cell(r + 1, c + 1).Range.InsertAfter(myds.Tables[0].Rows[r][c].ToString());//将遍历到的数据添加到Word表格中
                     }
                 }
             }
             object P_obj_Format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;//定义Word文档的保存格式
             word.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;//设置保存时不显示对话框
             //保存Word文档
             document.SaveAs(ref P_obj_WordName, ref P_obj_Format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
         }
     }
     document.Close(ref missing, ref missing, ref missing);//关闭Word文档
     word.Quit(ref missing, ref missing, ref missing);//退出Word应用程序
     MessageBox.Show("已经成功将多个Excel文件的内容读取到了一个Word文档中!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
Exemple #49
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         /* if (catalogsComboBox.SelectedIndex == 1)
           {*/
         col = 0;
         if (DialogResult.OK == saveFileDialog1.ShowDialog())
         {
             Microsoft.Office.Interop.Word.Application wdApp = new Microsoft.Office.Interop.Word.Application();
             Microsoft.Office.Interop.Word.Document wdDoc = new Microsoft.Office.Interop.Word.Document();
             wdDoc = wdApp.Documents.Add();
             Microsoft.Office.Interop.Word.Range rang = wdDoc.Range();
             wdDoc.SpellingChecked = false;
             wdDoc.ShowSpellingErrors = false;
             wdApp.Selection.Font.Name = "Times New Roman";
             wdApp.Selection.Font.Size = 12;
             wdApp.ActiveDocument.Select();
             string CommandText = "select * from `ads_paper`.`catalogitems` order by idcatalogItems";
             string Connect = "Database=" + dbname + ";Data Source=" + server + ";User Id=" + dbuser + ";Password="******";Port=" + dbPort;
             MySqlConnection myConnection = new MySqlConnection(Connect);
             MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
             myConnection.Open(); //Устанавливаем соединение с базой данных.
             MySqlDataReader MyDataReader;
             bool state = false;
             MyDataReader = myCommand.ExecuteReader();
             int[] catID = new int[5];
             int parentID;
             int real;
             int sum;
             while (MyDataReader.Read())
             {
                 catID[0] = MyDataReader.GetInt32(0);
                 catID[1] = MyDataReader.GetInt32(2);
                 catID[2] = MyDataReader.GetInt32(3);
                 catID[3] = MyDataReader.GetInt32(4);
                 catID[4] = MyDataReader.GetInt32(5);
                 string name = MyDataReader.GetString(1); //Получаем строку
                 //parentID = MyDataReader.GetInt32(6);
                 //real = MyDataReader.GetInt32(7);
                 //sum = MyDataReader.GetInt32(8);
                 if (checkCount(catID))
                 {
                     wdApp.Selection.TypeParagraph();
                     if (catID[2] == 0)
                     {
                         wdApp.Selection.TypeText("@@" + catID[1].ToString());
                         wdApp.Selection.TypeParagraph();
                         wdApp.Selection.TypeParagraph();
                         wdApp.Selection.TypeText(name);
                         wdApp.Selection.TypeParagraph();
                         wdApp.Selection.TypeParagraph();
                     }
                     else if (catID[3] == 0)
                     {
                         if (catID[1] == 1 || catID[1] == 4 || catID[1] == 5 || catID[1] == 11 || catID[1] == 18)
                         {
                             wdApp.Selection.TypeText("-" + catID[1].ToString() + "." + catID[2].ToString() + "-");
                             wdApp.Selection.TypeParagraph();
                         }
                         else
                         {
                             wdApp.Selection.TypeText(catID[1].ToString() + "." + catID[2].ToString());
                         }
                         wdApp.Selection.TypeText(" " + name);
                         wdApp.Selection.TypeParagraph();
                         state = true;
                     }
                     else
                     {
                         wdApp.Selection.TypeText(name);
                         wdApp.Selection.TypeParagraph();
                         wdApp.Selection.TypeParagraph();
                         state = false;
                     }
                     PrintAdsOB(catID, ref wdApp);
                 }
             }
             MyDataReader.Close();
             myConnection.Close();
             ReplaceTextWord(ref wdApp, "  ", " ");
             wdApp.ActiveDocument.SaveAs(saveFileDialog1.FileName + ".doc");
             wdDoc.Close();
             //wdApp.Documents.Close();
             wdApp.Quit();
             MessageBox.Show("Выгрузка завершена, выгружено: " + col.ToString() + " объявлений");
         }
     }
     catch (Exception except)
     {
         MessageBox.Show(except.Message);
     }
 }
        public static void ProcessingDocument(DirectoryInfo dir)
        {
            String[] fileName = dir.GetFiles().Select(fi => fi.Name).FirstOrDefault(name => name != "Thumbs.db").Split('.');
            string folderName = ResultFolder + OutputFolder;
            string pathString = System.IO.Path.Combine(folderName, fileName[0]);
            string fileNam2 = fileName[0] + ".docx";
            string targetPath = pathString;

            try
            {
                //Create an instance for word app
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

                //Set status for word application is to be visible or not.
                winword.Visible = false;

                //Create a missing variable for missing value
                object missing = System.Reflection.Missing.Value;

                //Create a new document
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                object styleHeading1 = "Heading 1";
                para1.Range.set_Style(ref styleHeading1);
                para1.Range.Text = "Extract Vocabulary from ppt";
                para1.Range.InsertParagraphAfter();
                try
                {
                    Application powerPoint = new Application();
                    String inputFile = ResultFolder + InputFolder + fileName[0] + "." + fileName[1];
                    powerPoint.Visible = MsoTriState.msoTrue;
                    powerPoint.WindowState = PpWindowState.ppWindowMinimized;
                    Presentations oPresSet = powerPoint.Presentations;
                    _Presentation oPres = oPresSet.Open(inputFile, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);

                    int rows = 0;
                    for (int i = 0; i < oPres.Slides.Count; i++)
                    {
                        var str = oPres.Slides[i + 1].NotesPage.Shapes[2].TextFrame.TextRange.Text;
                        int ii = str.IndexOf("SOURCES:");
                        if (str != "" && ii != -1)
                        {
                            rows++;
                        }
                    }

                    Microsoft.Office.Interop.Word.Table firstTable = document.Tables.Add(para1.Range, rows, 3, ref missing, ref missing);
                    firstTable.Borders.Enable = 1;
                    String[] heading = { "#", "File Name", "Source" };
                    int k = 0;

                    String changeName = "00";
                    String newName = "01";
                    String docFileName = "";
                    int row = 0;
                    for (int i = 0; i < oPres.Slides.Count; i++)
                    {
                        var str = oPres.Slides[i + 1].NotesPage.Shapes[2].TextFrame.TextRange.Text;
                        int ii = str.IndexOf("SOURCES:");
                        String substr = "";
                        if (str.Contains("#framechain") || str.Contains("#frame"))
                        {
                            if (ii > 0)
                            {
                                substr = str.Replace(str.Substring(0, ii) + "SOURCES:", "");

                                if (str.Contains("#framechain"))
                                {
                                    if (Convert.ToInt32(changeName) < 5)
                                        changeName = "0" + (Convert.ToInt32(changeName) + 5).ToString();
                                    else changeName = (Convert.ToInt32(changeName) + 5).ToString();

                                    newName = "01";
                                }
                                if (str.Contains("#frame"))
                                {
                                    docFileName = fileName[0] + "-" + changeName + "-" + newName;
                                    if (Convert.ToInt32(newName) < 9)
                                        newName = "0" + (Convert.ToInt32(newName) + 1).ToString();
                                    else newName = (Convert.ToInt32(newName) + 1).ToString();
                                }

                                // Microsoft.Office.Interop.Word.Table firstTable1 = document.Tables.Add(para1.Range, 1, 3, ref missing, ref missing);
                                //firstTable1.Borders.Enable = 1;
                                var r = firstTable.Rows[row + 1];
                                row++;
                                foreach (Microsoft.Office.Interop.Word.Cell cell in r.Cells)
                                {
                                    if (cell.RowIndex == 1)
                                    {
                                        //cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
                                        cell.Range.Text = heading[k++];
                                        cell.Range.Font.Bold = 1;
                                        cell.Range.Font.Name = "verdana";
                                        cell.Range.Font.Size = 10;
                                        //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;
                                        cell.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
                                        //Center alignment for the Header cells
                                        cell.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                                        cell.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                                    }
                                    else
                                    {
                                        if (cell.ColumnIndex == 1)
                                        {
                                            cell.Range.Text = newName;
                                        }
                                        else if (cell.ColumnIndex == 2)
                                        {
                                            cell.Range.Text = docFileName;
                                        }
                                        else if (cell.ColumnIndex == 3)
                                        {
                                            cell.Range.Text = substr;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    firstTable.AutoFormat();
                    powerPoint.Quit();
                }
                catch (Exception e)
                {
                    //var errors = e.Message;
                    //Console.WriteLine("Opss...Error : " + errors);
                    //Console.ReadKey();
                    //throw;
                }
                //Save the document
                object filename = System.IO.Path.Combine(targetPath, fileNam2);
                document.SaveAs2(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
            }
            catch (Exception e)
            {
                //var errors = e.Message;
                //Console.WriteLine("Opss...Error : " + errors);
                //Console.ReadKey();
                //throw;
            }
        }
        private bool Save_FileDoc1()
        {
            try
            {
                var application = new Microsoft.Office.Interop.Word.Application();
                var document = new Microsoft.Office.Interop.Word.Document();
                document = application.Documents.Add(Template: Server.MapPath("/File/Template/templateHDDV.doc"));

                application.Visible = true;

                foreach (Microsoft.Office.Interop.Word.Field field in document.Fields)
                {
                    if (field.Code.Text.Contains("MerPos01"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPos02"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPos03"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPos04"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPos05"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerName"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerAddress"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPhone"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerTaxCode"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerEmail"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerRepresent"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPosition"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerBeginM"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerDeadlineInt"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerDeadlineString"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerCostTitle01"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerCostTitle02"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerCostDetail"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                }
                document.SaveAs(FileName: String.Format(Server.MapPath("/File/WordFile/HopDongDVKeToan_Code_{0}.doc"), 123));

                document.Close();
                application.Quit();

                return true;
            }
            catch (Exception) { throw; return false; }
        }
Exemple #52
0
        string GetTextFromWordFile(string path)
        {
            Office.Word._Application appWord = null;
            Office.Word._Document docWord = null;

            Object filename = path;
            Object ConfirmConversions = Missing.Value;
            Object ReadOnly = true;
            Object AddToRecentFiles = Missing.Value;
            Object PasswordDocument = Missing.Value;
            Object PasswordTemplate = Missing.Value;
            Object Revert = Missing.Value;
            Object WritePasswordDocument = Missing.Value;
            Object WritePasswordTemplate = Missing.Value;
            Object Format = Missing.Value;
            Object Encoding = Missing.Value;
            Object Visible = false;

            Object saveChanges = false;
            Object originalFormat = null;
            Object routeDoc = null;

            appWord = new Office.Word.Application();
            appWord.Visible = false;
            docWord = appWord.Documents.Open2000(ref filename, ref ConfirmConversions, ref ReadOnly,
                              ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
                              ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate,
                              ref Format, ref Encoding, ref Visible);
            if (docWord.ProtectionType == Office.Word.WdProtectionType.wdNoProtection)
            {
                docWord.ActiveWindow.Selection.WholeStory();
                docWord.ActiveWindow.Selection.Copy();
                GetClipboardContent();
            }
            else
            {
                curr_clpbrd_content = "";
            }
            appWord.ActiveDocument.Close(ref saveChanges, ref originalFormat, ref routeDoc);
            appWord.Quit(ref saveChanges, ref originalFormat, ref routeDoc);

            return curr_clpbrd_content;
        }
        public string ReadDocx(object path)
        {
            try
            {

                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                object miss = System.Reflection.Missing.Value;
                object readOnly = true;
                Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                string totaltext = "";
                for (int i = 0; i < docs.Paragraphs.Count; i++)
                {
                    totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
                }
                docs.Close();
                word.Quit();
                return totaltext;
            }
            catch (System.Exception objException)
            {
                // Log the exception
                return "";
            }
        }
        private void print()
        {
            object FileName = AppDomain.CurrentDomain.BaseDirectory + "\\" + templatePath;//
            object saveAs = printPath;
            object password = "******";
            object noPassword = "";
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            wordApp.Options.set_DefaultFilePath(0, AppDomain.CurrentDomain.BaseDirectory);
            Microsoft.Office.Interop.Word.Document aDoc = null;
            object readOnly = true;
            object isVisible = false;
            wordApp.Visible = false;
            aDoc = wordApp.Documents.Open(ref FileName, ref missing, ref readOnly, ref missing, ref password,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible,
                 ref missing, ref missing, ref missing, ref missing);
            aDoc.Activate();

            FindindReplace(wordApp, "<name>", comboBoxTitle.Text + " " + textPatientName.Text);
            if (comboBoxTitle.Text == "Baby")
                FindindReplace(wordApp, "<age>", textAge.Text + " years " + textMonth.Text + " months");
            else
                FindindReplace(wordApp, "<age>", textAge.Text + " years ");
            FindindReplace(wordApp, "<gender>", comboBoxGender.Text);
            FindindReplace(wordApp, "<rep>", textReportNo.Text);
            FindindReplace(wordApp, "<ward>", textWardNo.Text);
            FindindReplace(wordApp, "<bht>", textBhtNo.Text);
            for (int i = 0; i < speciLables.Count; i++)
            {
                if (i < speciLables.Count - 1)
                    FindindReplace(wordApp, "<specimen>", "Specimen " + (i + 1) + "\t: " + speciTexts.ElementAt(i).Text + "\n<specimen>");
                else
                {
                    if (speciLables.Count == 1)
                        FindindReplace(wordApp, "<specimen>", "Specimen\t: " + speciTexts.ElementAt(i).Text);
                    else
                        FindindReplace(wordApp, "<specimen>", "Specimen " + (i + 1) + "\t: " + speciTexts.ElementAt(i).Text);
                }
            }
            if (textClinicalDetails.Text=="")                                   //**
                FindindReplace(wordApp, "<clinical>", replaceNewLines(""));    //**
            else                                                              //**
                FindindReplace(wordApp, "<clinical>", replaceNewLines("\n\nClinical Details	: " + textClinicalDetails.Text));//**
            FindindReplace(wordApp, "<macro>", replaceNewLines(textMacroscopy.Text));
            FindindReplace(wordApp, "<micro>", replaceNewLines(textMicroscopy.Text));
            FindindReplace(wordApp, "<con>", replaceNewLines(textConclusion.Text));
            String dates = "";
            if (printReqD)
            {
                dates += "\nRequested on : " + datePicker1.SelectedDate.Value.Date.Day + " / " + datePicker1.SelectedDate.Value.Date.Month + " / " + datePicker1.SelectedDate.Value.Date.Date.Year + "\t";
            }
            if (printTestedD)
            {
                dates += "Tested on : " + datePicker2.SelectedDate.Value.Date.Day + " / " + datePicker2.SelectedDate.Value.Date.Month + " / " + datePicker2.SelectedDate.Value.Date.Date.Year;
            }
            FindindReplace(wordApp, "<dates>", dates);
               // FindindReplace(wordApp, "<date>", datePicker2.SelectedDate.Value.Date.Day + " / " + datePicker2.SelectedDate.Value.Date.Month + " / " + datePicker2.SelectedDate.Value.Date.Date.Year);
            //FindindReplace(wordApp, "<reqdate>", datePicker1.SelectedDate.Value.Date.Day + " / " + datePicker1.SelectedDate.Value.Date.Month + " / " + datePicker1.SelectedDate.Value.Date.Date.Year);//**
            FindindReplace(wordApp, "<printdate>", DateTime.Today.Date.Day + " / " + DateTime.Today.Date.Month + " / " + DateTime.Today.Date.Year);//**

            aDoc.SaveAs(ref saveAs, ref missing, ref missing, ref noPassword, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            wordApp.Quit();

            ProcessStartInfo info = new ProcessStartInfo(saveAs.ToString());

            info.Verb = "Print";

            info.CreateNoWindow = true;

            info.WindowStyle = ProcessWindowStyle.Hidden;

            Process.Start(info);
        }
Exemple #55
0
        public static void SaveXMLAsPDF(YellowstonePathology.Business.OrderIdParser orderIdParser)
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue = true;
            Object oFalse = false;

            oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            Object xmlFileName = YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser) + orderIdParser.ReportNo + ".xml";
            Object docFileName = YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser) + orderIdParser.ReportNo + ".pdf";

            try
            {
                File.Delete(docFileName.ToString());
            }
            catch (Exception)
            {
                //System.Windows.MessageBox.Show("This file is locked and cannot be published at this time: " + reportNo);
                oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            }

            //Object fileFormat = "wdFormatPDF";

            Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref xmlFileName, 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);

            object oFmt = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;

            doc.SaveAs(ref docFileName, ref oFmt, 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);

            CaseDocument.ReleaseComObject(oFmt);
            CaseDocument.ReleaseComObject(doc);
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            CaseDocument.ReleaseComObject(oWord);
        }
Exemple #56
0
        public static int WriteTiffPages(YellowstonePathology.Business.OrderIdParser orderIdParser, long reportDistributionLogId)
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue = true;
            Object oFalse = false;

            oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = true;

            string currentPrinter = oWord.ActivePrinter;
            oWord.ActivePrinter = "Microsoft Office Document Image Writer";

            Object docFileName = YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser) + orderIdParser.ReportNo + ".doc";
            Object fileFormat = "wdFormatDocument";

            Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref docFileName, 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);

            object oOutputFile;
            object oPages;
            object oRange = Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintRangeOfPages;

            int pages = doc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages, ref oTrue);
            for (int i = 1; i <= pages; i++)
            {
                oPages = i.ToString();
                oOutputFile = YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser) + @"Centricity\" + reportDistributionLogId.ToString() + "." + i.ToString().PadLeft(3, '0');
                doc.PrintOut(ref oFalse, ref oFalse, ref oRange, ref oOutputFile, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oPages, ref oMissing,
                    ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            }

            oWord.ActivePrinter = currentPrinter;

            CaseDocument.ReleaseComObject(oRange);
            CaseDocument.ReleaseComObject(doc);
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            CaseDocument.ReleaseComObject(oWord);

            return pages;
        }
Exemple #57
0
        public static void SaveXMLAsDoc(YellowstonePathology.Business.OrderIdParser orderIdParser)
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue = true;
            Object oFalse = false;

            oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            Object xmlFileName = YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser) + orderIdParser.ReportNo + ".xml";
            Object docFileName = YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser) + orderIdParser.ReportNo + ".doc";

            try
            {
                File.Delete(docFileName.ToString());
            }
            catch (Exception)
            {
                oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            }

            Object fileFormat = "wdFormatDocument";

            Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref xmlFileName, 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);

            object oFmt = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;

            doc.SaveAs(ref docFileName, ref oFmt, 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);

            CaseDocument.ReleaseComObject(oFmt);
            CaseDocument.ReleaseComObject(doc);
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            CaseDocument.ReleaseComObject(oWord);
        }
Exemple #58
0
        public static void SaveXMLAsDocFromFileName(string fileName)
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue = true;
            Object oFalse = false;

            oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            Object xmlFileName = fileName;
            Object docFileName = fileName.ToUpper().Replace("XML", "DOC");

            try
            {
                File.Delete(docFileName.ToString());
            }
            catch (Exception)
            {
                //System.Windows.MessageBox.Show("This file is locked and cannot be published at this time: " + reportNo);
                oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            }

            Object fileFormat = "wdFormatDocument";

            Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref xmlFileName, 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);

            object oFmt = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;

            doc.SaveAs(ref docFileName, ref oFmt, 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);

            CaseDocument.ReleaseComObject(oFmt);
            CaseDocument.ReleaseComObject(doc);
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
            CaseDocument.ReleaseComObject(oWord);
        }
Exemple #59
0
        public void TestCleanToWithWordApp()
        {
			Microsoft.Office.Interop.Word._Application app = new Microsoft.Office.Interop.Word.Application();

            try
            {
                AppCountMonitor monitor = new AppCountMonitor("winword");
                string testDoc = TestUtils.TestFileUtils.MakeRootPathAbsolute(@"Projects\Workshare.API\Workshare.API.Tests\TestDocs\test.docx");
                using (TempFile tf = new TempFile(testDoc))
                {
                    using (TempFile dest = new TempFile())
                    {
                        File.Delete(dest.FilePath);
                        string initialHash = tf.MD5Sum;
                        IOfficeCleaner c = new OfficeCleaner();
                        c.CleanFileTo(tf.FilePath, dest.FilePath, app);
                        Assert.IsTrue(File.Exists(dest.FilePath), "We expected the dest file to be created");
                        string newHash = dest.MD5Sum;
                        Assert.AreNotEqual(initialHash, newHash, "We expected the Cleanion to change the file contents");
                    }
                }
                Assert.IsFalse(monitor.SeenMoreInstances(), "Additional instances of WinWord were created during the test run - that means it didn't use the provided instance");
            }
            finally
            {
                object oFalse = false;
                app.Quit(ref oFalse, ref oFalse, ref oFalse);
				Marshal.ReleaseComObject(app);

            }
        }
Exemple #60
0
        private void btnUpload_Click(object sender, EventArgs e)
        {
            OpenFileDialog od = new OpenFileDialog();
            od.Filter = "Word Documents|*.docx|All Files|*.*";

            if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtFirstName.Text = "";
                txtLastName.Text = "";
                cboCategory.Text = "";
                cboPhoneNumber.Text = "";
                cboEmail.Text = "";
                txtJobTitle.Text = "";
                txtCompany.Text = "";
                txtCityState.Text = "";
                lstAdditionalFiles.Items.Clear();
                txtNote.Text = "";
                txtAdditionalFile.Text = "";

                Cursor = Cursors.WaitCursor;
                try
                {
                    //System.Diagnostics.Process.Start("app.exe", od.FileName);

                    Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                    object miss = System.Reflection.Missing.Value;
                    object enc = Microsoft.Office.Core.MsoEncoding.msoEncodingEUCJapanese;
                    object path = od.FileName; //@"C:\Users\Administrator\Desktop\Les Tolbert.docx";
                    object readOnly = true;
                    Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss,
                        ref miss, ref miss, ref miss, ref miss, ref miss, ref enc, ref miss, ref miss, ref miss, ref miss, ref miss);
                    string totaltext = "";
                    for (int i = 0; i < docs.Paragraphs.Count; i++)
                    {
                        totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();

                        Console.WriteLine(totaltext);
                    }
                    //System.IO.File.WriteAllText("tmp.txt", totaltext);
                    txtContents.Text = totaltext;
                    lstAdditionalFiles.Items.Add(od.FileName, true);

                    GetEmail(totaltext);
                    GetPhoneNumbers(totaltext);

                    string fullname = txtContents.Lines[1].Trim();
                    string[] names = fullname.Split(' ');
                    txtFirstName.Text = names[0];
                    txtLastName.Text = names[1];

                    //txtPhoneNumber.Text = txtContents.Lines[2];

                    txtCityState.Text = txtContents.Lines[3];

                    foreach (string item in txtContents.Lines)
                    {
                        if (item.ToLower().Contains("company"))
                        {
                            string cname = item.Substring(item.IndexOf("company") + 1, item.Length);
                            txtCompany.Text = cname;
                            break;
                        }
                    }

                    foreach (string item in txtContents.Lines)
                    {
                        if (item.ToLower().Contains("job title"))
                        {
                            string cname = item.Substring(item.IndexOf("job title") + 1, item.Length);
                            txtJobTitle.Text = cname;
                            break;
                        }
                    }

                    //txtAdditionalFile.Text = od.FileName;

                    // Console.WriteLine(totaltext);
                    docs.Close();
                    word.Quit();

                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                Cursor = Cursors.Default;
                //txtContents.Text = System.IO.File.ReadAllText("tmp.txt");
            }
        }