Exemplo n.º 1
0
        //Chuyển file doc sang rtf để đọc
        //path là lưu đường dấn
        private static void DocToRtf(string filePath)
        {
            //Creating the instance of Word Application
            if (chuyendoiRTF != null)
            {
                chuyendoiRTF(null, EventArgs.Empty);
            }
            Microsoft.Office.Interop.Word.Application newApp = new Microsoft.Office.Interop.Word.Application();
            object Unknown = Type.Missing;

            if (XPath.IsEqualExt(filePath, new string[] { ".doc", ".docx" }))
            {
                try
                {
                    //lấy địa chỉ file word
                    object Source = filePath;
                    //địa chỉ file rtf tạo ra tạm
                    object Target = XPath.pathfile_rft;
                    //nếu file tồn tại thì xóa đi
                    if (File.Exists(Target.ToString()))
                    {
                        File.Delete(Target.ToString());
                    }
                    // Use for the parameter whose type are not known or
                    // say 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.wdFormatRTF;
                    //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);
                }
                catch (Exception)
                {
                }
                finally
                {
                    // for closing the application
                    newApp.Quit(ref Unknown, ref Unknown, ref Unknown);
                }
            }
            else
            {
                return;
            }
        }
Exemplo n.º 2
0
        public void createWord(string saved_path, bool newSmry)
        {
            word_app = createWordApp();
            this.insertBookmark(saved_doc_list);
            object strFileName = saved_path;

            //MessageBox.Show(strFileName.ToString());
            if (System.IO.File.Exists((string)strFileName))
            {
                System.IO.File.Delete((string)strFileName);
            }
            Object Nothing = System.Reflection.Missing.Value;

            word_wrt = word_app.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            object oStyleName = Word.WdBuiltinStyle.wdStyleBodyText;  //"Heading 1";

            word_wrt.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            word_wrt.Paragraphs.Last.Range.set_Style(ref oStyleName);
            string strContent = "Schlüsselwörter \r";

            word_wrt.Paragraphs.Last.Range.Font.Size = 14;
            word_wrt.Paragraphs.Last.Range.Font.Bold = 1;
            word_wrt.Paragraphs.Last.Range.Text      = strContent;

            this.writeSammary();

            //将WordDoc文档对象的内容保存为DOC文档
            word_wrt.SaveAs(ref strFileName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //关闭WordDoc文档对象
            word_wrt.Close(ref Nothing, ref Nothing, ref Nothing);


//Test code ##
            this.buildTOC(saved_path, newSmry);
//Test code ##


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

            word_app  = null;
            word_show = null;
        }
Exemplo n.º 3
0
        private bool WordToPDF(string inePath, string outputPath)
        {
            bool result = false;

            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Word.Document document = null;
            try
            {
                application.Visible = false;
                document            = application.Documents.Open(inePath);
                document.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF);
                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = false;
            }
            finally
            {
                document.Close();
                application.Quit();
            }
            return(result);
        }
Exemplo n.º 4
0
 /// <summary>
 /// 保存
 /// </summary>
 public void SaveAs()
 {
     //文件保存
     document.SaveAs(ref FileName, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing);
     document.Close(ref Missing, ref Missing, ref Missing);
     app.Quit(ref Missing, ref Missing, ref Missing);
 }
Exemplo n.º 5
0
        //public void LeerPDF()
        //{
        //    Word2Pdf objWorPdf = new Word2Pdf();
        //    string backfolder1 = "D:\\DocTmp\\";
        //    string strFileName = "tmp.docx";
        //    object FromLocation = backfolder1 + "\\" + strFileName;
        //    string FileExtension = Path.GetExtension(strFileName);
        //    string ChangeExtension = strFileName.Replace(FileExtension, ".pdf");
        //    if (FileExtension == ".doc" || FileExtension == ".docx")
        //    {
        //        object ToLocation = backfolder1 + "\\" + ChangeExtension;
        //        objWorPdf.InputLocation = FromLocation;
        //        objWorPdf.OutputLocation = ToLocation;
        //        objWorPdf.Word2PdfCOnversion();
        //    }
        //}

        public void LeerPDF()
        {
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

            wordApp.Visible = false;

            // file from
            object filename = Server.MapPath("DocTmp/tmp.doc"); // input

            // file to
            object newFileName = Server.MapPath("DocTmp/tmp.pdf"); // output
            object missing     = System.Type.Missing;

            // open document
            Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,
                                                                                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                                                                ref missing, ref missing, ref missing);

            // formt to save the file, this case PDF
            object formatoArquivo = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;

            // save file
            doc.SaveAs(ref newFileName, ref formatoArquivo, ref missing, ref missing, ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

            doc.Close(ref missing, ref missing, ref missing);

            wordApp.Quit(ref missing, ref missing, ref missing);

            string script = "<script languaje='javascript'> ";

            script += "mostrarFichero('DocTmp/tmp.pdf') ";
            script += "</script>" + Environment.NewLine;
            Page.RegisterStartupScript("mostrarFichero", script);
        }
Exemplo n.º 6
0
        //pega todas as linhas menos as com titulo informado
        public string DocReaderGetAllButTitle(string fileLocation, string headingText)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            object path     = fileLocation;
            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);
            string totaltext = "";
            int    paraCount = docs.Paragraphs.Count;

            for (int i = 1; i <= paraCount; i++)
            {
                if (docs.Paragraphs[i].Range.Text.ToString().TrimEnd('\r').ToUpper() != headingText.ToUpper())
                {
                    totaltext += " \r\n " + HttpUtility.HtmlDecode(docs.Paragraphs[i].Range.Text.ToString());
                }
            }

            if (totaltext == "")
            {
                totaltext = "No such data found!";
            }

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

            return(totaltext);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Reads a Word document and places the words into a StringBuilder.
        /// </summary>
        /// <param name="filePath">The path to the document.</param>
        /// <returns>Returns a StringBuilder with the content of the document.</returns>
        public static StringBuilder ReadWordDocument(string filePath)
        {
            if (Path.GetExtension(filePath) == ".doc" ||
                Path.GetExtension(filePath) == ".docx")
            {
                Microsoft.Office.Interop.Word.Application a = new Microsoft.Office.Interop.Word.Application();
                Word.Document doc = a.Documents.Open(filePath);

                int wordCount = doc.Words.Count;

                StringBuilder content = new StringBuilder();

                for (int i = 1; i <= wordCount; i++)
                {
                    string text = doc.Words[i].Text;
                }

                a.Quit();

                return(content);
            }

            else
            {
                Console.WriteLine(filePath + " does not have a valid Word extension.");
                return(null);
            }
        }
Exemplo n.º 8
0
        public void savedoc()
        {
            string         loc  = "";
            SaveFileDialog open = new SaveFileDialog();

            if (open.ShowDialog() == DialogResult.OK)
            {
                loc = open.FileName;
            }

            try
            {
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
                winword.Visible = false;
                object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                document.Content.Document.Content.Text = inputTextBox.Text + Environment.NewLine;
                object filename = loc;
                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("DOC file is saved");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error :" + ex.Message);
            }
        }
Exemplo n.º 9
0
        public void processWord(string saved_path, bool newSmry)
        {
            word_app = createWordApp();
            this.insertBookmark(saved_doc_list);
            object strFileName = saved_path;
            Object Nothing     = System.Reflection.Missing.Value;
            object readOnly    = false;
            object isVisible   = false;

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

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

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

            word_app  = null;
            word_show = null;
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            // Open XML Method
            object fileName = @"OpenXmlTest.docx";

            using (WordprocessingDocument myDocument = WordprocessingDocument.Open(fileName.ToString(), true))
            {
                var textbox = myDocument.MainDocumentPart.Document.Descendants <TextBoxContent>().First();
                Console.WriteLine(textbox.InnerText);
            }

            // Office Interop Method
            object missing   = System.Reflection.Missing.Value;
            object readOnly  = false;
            object isVisible = true;

            Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
            object firstShape    = 1;
            string textFrameText = wordApp.ActiveDocument.Shapes.get_Item(ref firstShape).TextFrame.TextRange.Text;

            wordApp.Quit(ref missing, ref missing, ref missing);

            Console.WriteLine(textFrameText);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Exemplo n.º 11
0
        public void AddFromFile(ref TextBox textbox)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            object path     = @"C:\Users\Husia\Documents\test.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 miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            string allText = docs.Content.Text;

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

            for (int i = 0; i < needTxt.Length; i++)
            {
                if (ok)
                {
                    mytxt += " " + needTxt[i];
                }
                if (needTxt[i].ToLower() == "анамнез")
                {
                    ok = true;
                }
                if (needTxt[i] == "статус")
                {
                    ok = false;
                }
            }
            textbox.Text = mytxt;
            docs.Close();
            word.Quit();
        } //нет ссылок
Exemplo n.º 12
0
    private void Merge()
    {
        System.Diagnostics.Stopwatch oTime = new System.Diagnostics.Stopwatch();
        oTime.Start();

        //建立一个空word用以存放合并后的文件
        string filename = @"C:\DFS\" + SharedData.excelFile.Substring(SharedData.excelFile.LastIndexOf("\\") + 1,
            (SharedData.excelFile.LastIndexOf(".") - SharedData.excelFile.LastIndexOf("\\") - 1)) + ".doc";
        object Nothing = System.Reflection.Missing.Value;
        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
        wordDoc.SpellingChecked = false;
        wordDoc.ShowSpellingErrors = false;


        Log.RecordLog("新建空白" + filename + "成功!等待合并word文档!");
        SharedData.fileName = filename;

        wordDoc.SaveAs2(filename);
        wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
        wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

        //合并各个word文件
        wordDocumentMerger merger = new wordDocumentMerger();
        merger.InsertMerge(groupName);

        oTime.Stop();
        long time = oTime.ElapsedMilliseconds;
        Log.RecordLog(@"word合并完成,最终生成文件为 " + SharedData.fileName + " 耗时:" + (time / 1000).ToString() + "秒!");
        //MessageBox.Show("word合并完成,耗时:" + (time / 1000).ToString() + "秒!");
    }
Exemplo n.º 13
0
        } //нет ссылок

        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     = GetDataFromDoc("Жалобы:", "Anamnes:", needTxt),
                Anamnes        = GetDataFromDoc("Anamnes:", "StatusPraesens:", needTxt),
                StatusPraesens = GetDataFromDoc("StatusPraesens:", "LocalStatus:", needTxt),
                LocalStatus    = GetDataFromDoc("LocalStatus:", "Diagnos:", needTxt),
                Diagnos        = GetDataFromDoc("Diagnos:", "Рекомендации:", needTxt)
            };

            docs.Close();
            word.Quit();
            return(md);
        }// doc
        private static void GerarArquivoPdf(string caminhoDoc, string caminhoPDF)
        {
            try
            {
                // Abrir Aplicacao Word
                Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

                // Arquivo de Origem
                object filename = caminhoDoc;

                object newFileName = caminhoPDF;

                object missing = System.Type.Missing;

                // Abrir documento
                Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,
                                                                                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                                                                    ref missing, ref missing, ref missing);

                // Formato para Salvar o Arquivo – Destino  - No caso, PDF
                object formatoArquivo = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;

                // Salvar Arquivo
                doc.SaveAs(ref newFileName, ref formatoArquivo, 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);

                // Não salvar alterações no arquivo original
                object salvarAlteracoesArqOriginal = false;
                wordApp.Quit(ref salvarAlteracoesArqOriginal, ref missing, ref missing);
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 15
0
        }// 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     = GetDataFromDoc("Жалобы:", "Анамнез:", needTxt),
                Anamnes        = GetDataFromDoc("Анамнез:", "ОбщийСтатус:", needTxt),
                StatusPraesens = GetDataFromDoc("ОбщийСтатус:", "МестныйСтатус:", needTxt),
                LocalStatus    = GetDataFromDoc("МестныйСтатус:", "ПредварительныйДиагноз:", needTxt),
                Diagnos        = GetDataFromDoc("ПредварительныйДиагноз:", "Рекомендации:", needTxt)
            };

            docs.Close();
            word.Quit();
            return(md);
        }
Exemplo n.º 16
0
        /// <summary>
        /// 转换word 成PDF文档
        /// </summary>
        /// <param name="_lstrInputFile">原文件路径</param>
        /// <param name="_lstrOutFile">pdf文件输出路径</param>
        /// <returns>true 成功</returns>
        public static bool ConvertWordToPdf(string _lstrInputFile, string _lstrOutFile)
        {
            Microsoft.Office.Interop.Word.Application application = null;
            Word.Document document = null;
            try
            {
                application         = new Microsoft.Office.Interop.Word.Application();
                application.Visible = false;
                document            = application.Documents.Open(_lstrInputFile);
                document.ExportAsFixedFormat(_lstrOutFile, Word.WdExportFormat.wdExportFormatPDF);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                }
                if (application != null)
                {
                    application.Quit();
                }
            }
        }
Exemplo n.º 17
0
        static void InsertText()
        {
            // Создаём объект word
            Microsoft.Office.Interop.Word._Application OneWord = new Microsoft.Office.Interop.Word.Application();


            OneWord.WindowState = Word.WdWindowState.wdWindowStateNormal;

            // Создаем документ
            var OneDoc = OneWord.Documents.Add();

            for (int i = 1; i <= 100; i++)
            {
                OneDoc.Content.InsertAfter($"tested {i}\n");
                if (i % 2 == 0)
                {
                    OneWord.ActiveDocument.Characters.Last.Select();
                    OneWord.Selection.Collapse();

                    OneWord.Selection.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);
                }
            }

            // Выходим и закрываем
            OneDoc.SaveAs2(@"D:\SaveDocFile.docx");
            OneDoc.Close();
            OneWord.Quit();
        }
Exemplo n.º 18
0
        static void InsertTextOnShtat()
        {
            using (shtatDB db = new shtatDB())
            {
                var items = db.shtat49289_.ToList();

                // Создаём объект word
                Microsoft.Office.Interop.Word._Application OneWord = new Microsoft.Office.Interop.Word.Application();


                OneWord.WindowState = Word.WdWindowState.wdWindowStateNormal;

                // Создаем документ
                var OneDoc = OneWord.Documents.Add();


                foreach (var item in items)
                {
                    OneDoc.Content.InsertAfter($"{item.family} {item.name} {item.surname}, {item.birth}\n");
                }

                // Выходим и закрываем
                OneDoc.SaveAs2(@"D:\shtat49289.docx");
                OneDoc.Close();
                OneWord.Quit();
            }
        }
Exemplo n.º 19
0
        private void wordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog2.Filter           = "doc files (*.doc)|*.doc|All files (*.*)|*.*";
            saveFileDialog2.FilterIndex      = 2;
            saveFileDialog2.RestoreDirectory = true;

            if (saveFileDialog2.ShowDialog() == DialogResult.OK)
            {
                Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
                Object        missing = Type.Missing;
                Word.Document word1   = application.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                //object text = "tesfsdfkslghsdgjh";
                //word1.Paragraphs[1].Range.InsertParagraphAfter();
                //word1.Paragraphs[1].Range.Text = "asaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                //word1.Footnotes.Location = Word.WdFootnoteLocation.wdBeneathText;
                //word1.Footnotes.NumberStyle = Word.WdNoteNumberStyle.wdNoteNumberStyleLowercaseRoman;
                //word1.Footnotes.Add(word1.Paragraphs[1].Range.Words[2].Characters[2], ref missing, ref text);
                Microsoft.Office.Interop.Word.Document doc   = application.ActiveDocument;
                Microsoft.Office.Interop.Word.Range    range = doc.Paragraphs[doc.Paragraphs.Count].Range;
                dataSetTemp = dbw1.ReadMetricsByReport(listView2.Items[listView2.SelectedIndices[0]].Text);
                doc.Tables.Add(range, dataSetTemp.Tables[0].Rows.Count + 1, 6, ref missing, ref missing);
                doc.Tables[1].Cell(1, 1).Range.Text = "NAME metric";
                doc.Tables[1].Cell(1, 2).Range.Text = "MIN value";
                doc.Tables[1].Cell(1, 3).Range.Text = "CUR value";
                doc.Tables[1].Cell(1, 4).Range.Text = "MAX value";
                doc.Tables[1].Cell(1, 5).Range.Text = "VALUE";
                doc.Tables[1].Cell(1, 6).Range.Text = "RATE";
                for (int i = 0; i < dataSetTemp.Tables[0].Rows.Count; i++)
                {
                    dataSetTemp1 = dbw1.ReadInfoMetricByReportMetric(listView2.Items[listView2.SelectedIndices[0]].Text, dataSetTemp.Tables[0].Rows[i].ItemArray[0].ToString());
                    doc.Tables[1].Cell(i + 2, 1).Range.Text = dataSetTemp.Tables[0].Rows[i].ItemArray[0].ToString();
                    doc.Tables[1].Cell(i + 2, 2).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[2].ToString();
                    doc.Tables[1].Cell(i + 2, 3).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[0].ToString();
                    doc.Tables[1].Cell(i + 2, 4).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[3].ToString();
                    doc.Tables[1].Cell(i + 2, 5).Range.Text = Double.Parse(dataSetTemp1.Tables[0].Rows[0].ItemArray[4].ToString()).ToString("F5");
                    doc.Tables[1].Cell(i + 2, 6).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[5].ToString();
                }
                doc.Tables[1].Columns.AutoFit();
                Word.Border[] borders = new Word.Border[6];
                Word.Table    tbl     = doc.Tables[doc.Tables.Count];
                borders[0] = tbl.Borders[Word.WdBorderType.wdBorderLeft];
                borders[1] = tbl.Borders[Word.WdBorderType.wdBorderRight];
                borders[2] = tbl.Borders[Word.WdBorderType.wdBorderTop];
                borders[3] = tbl.Borders[Word.WdBorderType.wdBorderBottom];
                borders[4] = tbl.Borders[Word.WdBorderType.wdBorderHorizontal];
                borders[5] = tbl.Borders[Word.WdBorderType.wdBorderVertical];
                foreach (Word.Border border in borders)
                {
                    border.LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    border.Color     = Word.WdColor.wdColorBlack;
                }
                application.Documents[word1].SaveAs(saveFileDialog2.FileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                application.Quit();
                string info = "Doc file saved at\n" + saveFileDialog2.FileName;
                MessageBox.Show(this, info, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 20
0
        /*
         * Creates a pdf copy of the word file
         * pdfFileName: Path and file name of the PDF file with the extension address on the desktop
         * pdfInFolder: Path and file name of the pdf file in the Folder
         */
        public void convertToPDF()
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            wordDoc = app.Documents.Open(fileToConvert, ReadOnly: true);
            wordDoc.ExportAsFixedFormat(saveToPath, WdExportFormat.wdExportFormatPDF);

            wordDoc.Close(WdSaveOptions.wdDoNotSaveChanges);
            app.Quit();
        }
Exemplo n.º 21
0
        private void addPages(string docLoc, Word.Table oTable)
        {
            Microsoft.Office.Interop.Word.Application word = null;
            word = new Microsoft.Office.Interop.Word.Application();

            object inputFile          = docLoc;
            object confirmConversions = false;
            object readOnly           = true;
            object visible            = false;
            object missing            = Type.Missing;

            // Open the document...
            Microsoft.Office.Interop.Word.Document tempDoc = null;
            tempDoc = word.Documents.Open(
                ref inputFile, ref confirmConversions, 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);
            tempDoc.Activate();

            string           tempPageString       = "";
            string           tempPageRevisionText = "";
            string           tempPageDateText     = "";
            List <multiLOEP> pageMultiLOEP        = new List <multiLOEP>();

            for (int i = 1; i <= GetPageNumber(tempDoc); i++)
            {
                tempPageString       = getString(tempDoc, "edocs_Page" + i + "_page");
                tempPageRevisionText = getString(tempDoc, "edocs_Page" + tempPageString + "_rev");
                tempPageDateText     = getString(tempDoc, "edocs_Page" + tempPageString + "_date");
                if (pageMultiLOEP.Count == 0)
                {
                    pageMultiLOEP.Add(new multiLOEP(tempPageString, tempPageRevisionText, tempPageDateText));
                }
                else if (pageMultiLOEP[pageMultiLOEP.Count - 1].rev != tempPageRevisionText)
                {
                    if (addRows(oTable.Rows[oTable.Rows.Count], pageMultiLOEP[pageMultiLOEP.Count - 1]))
                    {
                        oTable.Rows.Add();
                    }
                    pageMultiLOEP.Add(new multiLOEP(tempPageString, tempPageRevisionText, tempPageDateText));
                }
                else
                {
                    pageMultiLOEP[pageMultiLOEP.Count - 1].endPage = tempPageString;
                }
            }
            addRows(oTable.Rows[oTable.Rows.Count], pageMultiLOEP[pageMultiLOEP.Count - 1]);
            tempDoc.Close(null, null, null);
            word.Quit(null, null, null);
            word = null;
            GC.Collect();
            System.Diagnostics.Debug.WriteLine("Finish Multi");
        }
Exemplo n.º 22
0
        private void BtxExport_Copy_Click(object sender, RoutedEventArgs e)
        {
            var wordApp      = new Microsoft.Office.Interop.Word.Application();
            var wordDocument = wordApp.Documents.Open(@"G:\G;chromesaves\FileIfCorrect.docx");

            wordDocument.ExportAsFixedFormat(@"G:\G;chromesaves\FileIfCorrect.pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);

            wordDocument.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges,
                               Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat,
                               false); //Close document

            wordApp.Quit();
        }
Exemplo n.º 23
0
        /// <summary>
        /// 读取表格中的文本。
        /// 对于doc文件中的表格,读出的结果是去除掉了网格线,内容按行读取。
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ParseWord(string filePath)
        {
            object readOnly = true;
            object missing  = System.Reflection.Missing.Value;
            object fileName = filePath;

            Microsoft.Office.Interop.Word._Application wordapp = new Microsoft.Office.Interop.Word.Application();
            Word._Document doc  = wordapp.Documents.Open(ref fileName);
            string         text = doc.Content.Text;

            doc.Close();
            wordapp.Quit();
            return(text);
        }
        protected string GetTextFromWord()
        {
            Object filename              = fileName;
            Object confirmConversions    = Type.Missing;
            Object readOnly              = true;
            Object addToRecentFiles      = Type.Missing;
            Object passwordDocument      = Type.Missing;
            Object passwordTemplate      = Type.Missing;
            Object revert                = Type.Missing;
            Object writePasswordDocument = Type.Missing;
            Object writePasswordTemplate = Type.Missing;
            Object format                = Type.Missing;
            Object encoding              = Type.Missing;
            Object visible               = Type.Missing;
            Object openConflictDocument  = Type.Missing;
            Object openAndRepair         = Type.Missing;
            Object documentDirection     = Type.Missing;
            Object noEncodingDialog      = Type.Missing;

            Word.Application Progr = new Microsoft.Office.Interop.Word.Application();
            Progr.Documents.Open(ref filename,
                                 ref confirmConversions,
                                 ref readOnly,
                                 ref addToRecentFiles,
                                 ref passwordDocument,
                                 ref passwordTemplate,
                                 ref revert,
                                 ref writePasswordDocument,
                                 ref writePasswordTemplate,
                                 ref format,
                                 ref encoding,
                                 ref visible,
                                 ref openConflictDocument,
                                 ref openAndRepair,
                                 ref documentDirection,
                                 ref noEncodingDialog);
            Word.Document Doc = new Microsoft.Office.Interop.Word.Document();
            Doc = Progr.Documents.Application.ActiveDocument;
            object start = 0;
            object stop  = Doc.Characters.Count;

            Word.Range Rng    = Doc.Range(ref start, ref stop);
            string     Result = Rng.Text;
            object     sch    = Type.Missing;
            object     aq     = Type.Missing;
            object     ab     = Type.Missing;

            Progr.Quit(ref sch, ref aq, ref ab);
            return(Result);
        }
Exemplo n.º 25
0
        //open document file
        public void opendoc()
        {
            string plainn = "";
            string fn;

            fn = textBox1.Text;
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            object path     = fn;
            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);

            for (int p = 0; p < docs.Paragraphs.Count; p++)
            {
                plainn += docs.Paragraphs[p + 1].Range.Text.ToString();
            }
            docs.Close();
            word.Quit();
            string key    = tbbx.Text;
            string cipher = decrypt(plainn);

            string         loc  = "";
            SaveFileDialog open = new SaveFileDialog();

            if (open.ShowDialog() == DialogResult.OK)
            {
                loc = open.FileName;
            }

            try
            {
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
                winword.Visible = false;
                object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                document.Content.Document.Content.Text = cipher + Environment.NewLine;
                object filename = loc;
                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 ex)
            {
                MessageBox.Show("Error :" + ex.Message);
            }
        }
Exemplo n.º 26
0
        public void changeTextForContracts(object templateForNewCompanyContract, string[] data)
        {
            //now create word file into template and fill data
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            //load document
            Microsoft.Office.Interop.Word.Document doc = null;

            object missing = Type.Missing;

            doc = app.Documents.Open(templateForNewCompanyContract, missing, missing);
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();

            string[] tmpForData = new string[12];
            tmpForData = data;

            app.Selection.Find.Execute("<PlCompanyName>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[0], 2);
            app.Selection.Find.Execute("<PlCompanyNIP>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[1], 2);
            app.Selection.Find.Execute("<PlCompanyDIC>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[2], 2);
            app.Selection.Find.Execute("<PlCompanyRepresentant>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[3], 2);


            app.Selection.Find.Execute("<newCompanyName>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[4], 2);
            app.Selection.Find.Execute("<newCompanyAdress>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[5], 2);
            app.Selection.Find.Execute("<newCompanyIC>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[6], 2);
            app.Selection.Find.Execute("<newCompanyRepresentant>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[7], 2);
            app.Selection.Find.Execute("<newCompanyTypeOfWork>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[8], 2);
            app.Selection.Find.Execute("<newCompanyDate>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[9], 2);

            app.Selection.Find.Execute("<PlCompanyKRS>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[10], 2);

            app.Selection.Find.Execute("<newCompanyTypeOfWorkPl>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[11], 2);

            Random rand = new Random();
            int    ddd;

            ddd = rand.Next();


            object FilePathForContractCz = (object)"Y:\\Legalizace\\Fresh L\\!!!Contracts\\" + tmpForData[1] + "_" + ddd + "Smlouva.docx";

            doc.SaveAs2(FilePathForContractCz, missing, missing, missing);

            MessageBox.Show("Files Are Created!");
            doc.Close(false, missing, missing);
            app.Quit(false, false, false);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
        }
Exemplo n.º 27
0
        } //DocTemplateService

        public void AddToTemplateFirstDoc(MedicalModel model)// DocTemplateService
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            word.Visible = false;
            var document = word.Documents.Open($"C:\\Users\\Husia\\Documents\\Pacients\\{model.Name}\\{model.Name}первичный.docx");

            ReplaceWords("{name}", model.Name, document);
            ReplaceWords("{Anamnes}", model.Anamnes, document);
            ReplaceWords("{StatusPraesens}", model.StatusPraesens, document);
            ReplaceWords("{LocalStatus}", model.LocalStatus, document);
            ReplaceWords("{Diagnos}", model.Diagnos, document);
            document.Save();
            document.Close();
            word.Quit();
        }
Exemplo n.º 28
0
        public void oku()
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            object path     = dosyaAdi;
            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);
            for (int i = 0; i < docs.Paragraphs.Count; i++)
            {
                totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
            }
            docs.Close();
            word.Quit();
        }
Exemplo n.º 29
0
        //合并生成的word文件
        private void FileMerge()
        {
            System.Diagnostics.Stopwatch oTime = new System.Diagnostics.Stopwatch();
            oTime.Start();

            //建立一个空word用以存放合并后的文件
            string filename = "";

            if (SharedData.AREATYPE == 3)//地方
            {
                filename = @"C:\DFS\国家重点科技基础条件资源调查数据汇编(地方).doc";
            }
            else if (SharedData.AREATYPE == 2)//中央
            {
                filename = @"C:\DFS\国家重点科技基础条件资源调查数据汇编(中央).doc";
            }
            else//全国
            {
                filename = @"C:\DFS\国家重点科技基础条件资源调查数据汇编(全国).doc";
            }

            object Nothing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            Log.RecordLog("新建空白" + filename + "成功!等待合并word文档!");
            SharedData.fileName = filename;

            wordDoc.SaveAs2(filename);
            wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

            //合并各个word文件
            wordDocumentMerger merger   = new wordDocumentMerger();
            List <string>      fileList = new List <string>();

            fileList = GetFileList();
            merger.InsertMerge(fileList);

            oTime.Stop();
            long time = oTime.ElapsedMilliseconds;

            Log.RecordLog(@"word合并完成,最终生成文件为 " + SharedData.fileName + " 耗时:" + (time / 1000).ToString() + "秒!");
        }
        /// <summary>
        /// 导出Word 的方法
        /// </summary>
        private void tslExport_Word()
        {
            SaveFileDialog sfile = new SaveFileDialog();

            sfile.AddExtension = true;
            sfile.DefaultExt   = ".doc";
            sfile.Filter       = "(*.doc)|*.doc";
            sfile.FileName     = "理文检测系统质检数据统计Word报表" + DateTime.Now.ToShortDateString();
            if (sfile.ShowDialog() == DialogResult.OK)
            {
                object path = sfile.FileName;
                Object none = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application wordApp  = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
                //建立表格
                Microsoft.Office.Interop.Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, dgvCarStatisticsQC.Rows.Count + 1, dgvCarStatisticsQC.Columns.Count, ref none, ref none);
                try
                {
                    for (int i = 0; i < dgvCarStatisticsQC.Columns.Count; i++)//设置标题
                    {
                        table.Cell(0, i + 1).Range.Text = dgvCarStatisticsQC.Columns[i].HeaderText;
                    }
                    for (int i = 1; i < dgvCarStatisticsQC.Rows.Count; i++)//填充数据
                    {
                        for (int j = 0; j < dgvCarStatisticsQC.Columns.Count; j++)
                        {
                            //table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            if (dgvCarStatisticsQC[j, i - 1].Value != null)
                            {
                                table.Cell(i + 1, j + 1).Range.Text = dgvCarStatisticsQC[j, i - 1].Value.ToString();
                            }
                        }
                    }
                    document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                    document.Close(ref none, ref none, ref none);
                    MessageBox.Show("导出数据成功!");
                }

                finally
                {
                    wordApp.Quit(ref none, ref none, ref none);
                }
            }
        }
Exemplo n.º 31
0
        public ResultType_enum Learn(string docPath, out int productAddedCount, out int productRepeatCount, out int productMergeCount, out string message)
        {
            productAddedCount = 0;
            productRepeatCount = 0;
            productMergeCount = 0;
            try
            {
                isWork = true;
                message = "";

                // Проверка пути документа
                if (!File.Exists(docPath))
                {
                    message = "Документа по пути <" + docPath + "> не существует";
                    return ResultType_enum.Error;
                }

                //Создаём новый Word.Application
                Word.Application application = new Microsoft.Office.Interop.Word.Application();

                //Загружаем документ
                Microsoft.Office.Interop.Word.Document doc = null;

                object fileName = docPath;
                object falseValue = false;
                object trueValue = true;
                object missing = Type.Missing;

                doc = application.Documents.Open(ref fileName, ref missing, ref trueValue,
                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);

                // Ищем таблицу с данными
                Microsoft.Office.Interop.Word.Table tbl = null;
                try
                {
                    tbl = application.ActiveDocument.Tables[1];
                }
                catch
                {
                    message = "В документе не найдена таблица для обучения";
                    return ResultType_enum.Error;
                }
                if (tbl == null)
                {
                    message = "В документе не найдена таблица для обучения";
                    return ResultType_enum.Error;
                }
                if (tbl.Columns.Count != 6)
                {
                    message = "Количество столбцов таблицы не совпадает со спецификацией";
                    return ResultType_enum.Error;
                }

                //DocumentDbContext dc = new DocumentDbContext();
                // Заполняем продукты
                var r = mvm.dc.Rubrics.FirstOrDefault(m => m.Name.ToLower() == "--без рубрики--");
                var t = mvm.dc.Templates.FirstOrDefault(m => m.Name.ToLower() == "свобода");

                // Новый обход документа
                Product product = null;
                Property property = null;
                Word.Cell cell = tbl.Cell(4, 1);
                while (cell != null) {
                    try
                    {
                        string cellValue = cell.Range.Text.Trim();

                        switch (cell.ColumnIndex) {
                            case (2):
                                // Название (--ПЕРВОЕ ЗНАЧЕНИЕ--)
                                product = new Product();
                                product.Name = Globals.DeleteNandSpaces(Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue)));
                                property = new Property();
                                break;
                            case (5):
                                // Торговая марка
                                if (product == null) break;
                                product.TradeMark = Globals.DeleteNandSpaces(Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue)));
                                break;
                            case (3):
                                // Требования заказчика
                                ParamValue pv = new ParamValue();
                                property.ParamValues.Add(pv);

                                pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требования заказчика" && m.Template.Name.ToLower() == "свобода");
                                pv.Property = property;
                                pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue));
                                break;
                            case (4):
                                // Требования участника
                                pv = new ParamValue();
                                property.ParamValues.Add(pv);

                                pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требования участника" && m.Template.Name.ToLower() == "свобода");
                                pv.Property = property;
                                pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue));
                                break;
                            case (6):
                                // Сертификация (--ПОСЛЕДНЕЕ ЗНАЧЕНИЕ--)
                                pv = new ParamValue();
                                property.ParamValues.Add(pv);

                                pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Сертификация" && m.Template.Name.ToLower() == "свобода");
                                pv.Property = property;
                                pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue));

                                // Добавляем к продукту значения, шаблон, рубрику
                                if ((property.ParamValues.ElementAt(0).Value != "") &&
                                    ((property.ParamValues.ElementAt(1).Value != "")) &&
                                    ((property.ParamValues.ElementAt(2).Value != "")))
                                {
                                    product.Properties.Add(property);
                                }

                                // Проверка на повтор
                                // Если совпали название и товарный знак и значения по всем атрибутам, то это ПОВТОР
                                // Если совпали название и товарный знак и значений по данному шаблону нет (или пусты), то это СЛИЯНИЕ
                                // Если совпали название и товарный знак и значения НЕ совпали, то это НОВЫЙ ПРОДУКТ
                                IEnumerable<Product> repeatProducts = mvm.dc.Products.Where(m => (m.Name == product.Name && m.TradeMark == product.TradeMark));
                                if (repeatProducts.Count() > 0) {
                                    // Изначально проверим на повтор
                                    foreach (Product repeatProduct in repeatProducts)
                                    {
                                        // Шаблон
                                        var repeatTemplate = product.Templates.FirstOrDefault(m => m.Name.Trim().ToLower() == "свобода");
                                        if (repeatTemplate == null) continue;

                                        // Свойства продукта по шаблону
                                        IEnumerable<Property> repeatProperties = product.Properties.SelectMany(m => m.ParamValues.Where(p => repeatTemplate.Param.Contains(p.Param))).Select(f => f.Property).Distinct();
                                        if (repeatProperties.Count() != 3) continue;

                                        foreach (Property repeatProperty in repeatProperties) {

                                        }

                                    }

                                    if (repeatProducts.Count() > 1)
                                    {

                                    }
                                }

                                /*if (repeatProduct != null)
                                {
                                    if (repeatProduct.Templates.FirstOrDefault(m => m.Name.Trim().ToLower() == "свобода") == null)
                                    {
                                        product = repeatProduct;
                                    }
                                    else
                                    {
                                        productRepeatCount++;
                                        continue;
                                    }
                                }*/

                                product.Rubric = r;
                                mvm.dc.Products.Add(product);
                                productAddedCount++;
                                t.Products.Add(product);

                                mvm.dc.SaveChanges();
                                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    mvm.TemplateCollection.FirstOrDefault(m => m.Name.ToLower() == "свобода").Products.Add(product);
                                }));

                                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    mvm.ProductCollection.Add(product);
                                }));

                                break;
                            default:
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        break;
                    }
                    finally {
                        cell = cell.Next;
                    }
                }

                /*for (int i = 4; i <= tbl.Rows.Count; i++)
                {
                    if (!isWork) break;
                    Product product = new Product();

                    // Название продукта
                    product.Name = Globals.DeleteNandSpaces(Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 2).Range.Text.Trim())));
                    product.TradeMark = Globals.DeleteNandSpaces(Globals.CleanWordCell(tbl.Cell(i, 5).Range.Text.Trim()));

                    if (product.Name == "") continue;

                    // Проверить на повтор
                    Product repeatProduct = mvm.dc.Products.FirstOrDefault(m => (m.Name == product.Name && m.TradeMark == product.TradeMark));
                    if (repeatProduct != null)
                    {
                        if (repeatProduct.Templates.FirstOrDefault(m => m.Name.Trim().ToLower() == "свобода") == null)
                        {
                            product = repeatProduct;
                        }
                        else
                        {
                            productRepeatCount++;
                            continue;
                        }
                    }

                    // Проверка заполнения атрибутов строки
                    if ((Globals.CleanWordCell(tbl.Cell(i, 3).Range.Text.Trim()) == "") &&
                        (Globals.CleanWordCell(tbl.Cell(i, 4).Range.Text.Trim()) == "") &&
                        (Globals.CleanWordCell(tbl.Cell(i, 6).Range.Text.Trim())) == "")
                    {
                        continue;
                    }

                    // У данного шаблона одно свойство
                    Property property = new Property();

                    try
                    {
                        // Требования заказчика
                        ParamValue pv = new ParamValue();
                        property.ParamValues.Add(pv);

                        pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требования заказчика" && m.Template.Name.ToLower() == "свобода");
                        pv.Property = property;
                        pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 3).Range.Text.Trim()));

                        // Требования участника
                        pv = new ParamValue();
                        property.ParamValues.Add(pv);

                        pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требования участника" && m.Template.Name.ToLower() == "свобода");
                        pv.Property = property;
                        pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 4).Range.Text.Trim()));

                        // Сертификация
                        pv = new ParamValue();
                        property.ParamValues.Add(pv);

                        pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Сертификация" && m.Template.Name.ToLower() == "свобода");
                        pv.Property = property;
                        pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 6).Range.Text.Trim()));

                        // Добавляем к продукту значения, шаблон, рубрику
                        product.Properties.Add(property);
                    }
                    catch {
                        string sss = "";
                        continue;
                    }

                    product.Rubric = r;
                    mvm.dc.Products.Add(product);
                    productAddedCount++;
                    t.Products.Add(product);

                    mvm.dc.SaveChanges();

                    try
                    {
                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            mvm.TemplateCollection.FirstOrDefault(m => m.Name.ToLower() == "свобода").Products.Add(product);
                        }));
                    }
                    catch { }

                    try
                    {
                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            mvm.ProductCollection.Add(product);
                        }));
                    }
                    catch
                    {

                    }

                }*/

                // Закрываем приложение
                application.Quit(ref missing, ref missing, ref missing);
                application = null;

                return ResultType_enum.Done;
            }

            catch (Exception ex)
            {
                message = ex.Message + '\n' + ex.StackTrace;
                return ResultType_enum.Error;
            }
            finally
            {
                isWork = false;
            }
        }
Exemplo n.º 32
0
        public void processWord(string saved_path, bool newSmry)
        {
            word_app = createWordApp();
            this.insertBookmark(saved_doc_list);
            object strFileName = saved_path;
            Object Nothing = System.Reflection.Missing.Value;
            object readOnly = false;
            object isVisible = false;

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

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

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

            word_app = null;
            word_show = null;
        }
Exemplo n.º 33
0
        public ResultType_enum Learn(string docPath, out int productAddedCount, out int productRepeatCount, out int productMergeCount, out string message)
        {
            productAddedCount = 0;
            productRepeatCount = 0;
            productMergeCount = 0;
            try
            {
                isWork = true;
                message = "";

                // Проверка пути документа
                if (!File.Exists(docPath))
                {
                    message = "Документа по пути <" + docPath + "> не существует";
                    return ResultType_enum.Error;
                }

                //Создаём новый Word.Application
                Word.Application application = new Microsoft.Office.Interop.Word.Application();

                //Загружаем документ
                Microsoft.Office.Interop.Word.Document doc = null;

                object fileName = docPath;
                object falseValue = false;
                object trueValue = true;
                object missing = Type.Missing;

                doc = application.Documents.Open(ref fileName, ref missing, ref trueValue,
                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);

                // Ищем таблицу с данными
                Microsoft.Office.Interop.Word.Table tbl = null;
                try
                {
                    tbl = application.ActiveDocument.Tables[1];
                }
                catch
                {
                    message = "В документе не найдена таблица для обучения";
                    return ResultType_enum.Error;
                }
                if (tbl == null)
                {
                    message = "В документе не найдена таблица для обучения";
                    return ResultType_enum.Error;
                }
                if (tbl.Columns.Count != 8)
                {
                    message = "Количество столбцов таблицы не совпадает со спецификацией";
                    return ResultType_enum.Error;
                }

                // Заполняем продукты
                Product product = null;
                Property property = null;

                bool isNewProduct = false;
                string productName = "";

                var r = mvm.dc.Rubrics.FirstOrDefault(m => m.Name.ToLower() == "--без рубрики--");
                var t = mvm.dc.Templates.FirstOrDefault(m => m.Name.ToLower() == "форма 2");
                for (int i = 4; i <= tbl.Rows.Count; i++)
                {
                    // Название продукта
                    try
                    {
                        /*tbl.Cell(i, 2).Select();
                        Word.Selection sel = application.Selection;
                        bool sss = sel.IsEndOfRowMark;
                        int ss = sel.Rows.Count;*/
                        //sel.MoveDown();
                        Word.Cell ddd = tbl.Cell(i, 2).Next;

                        if ((Globals.CleanWordCell(tbl.Cell(i, 2).Range.Text.Trim()) == productName) ||
                            (Globals.CleanWordCell(tbl.Cell(i, 2).Range.Text.Trim()) == ""))
                        {
                            isNewProduct = false;
                        }
                        else
                        {
                            isNewProduct = true;
                            productName = Globals.CleanWordCell(tbl.Cell(i, 2).Range.Text.Trim());
                        }

                    }
                    catch (Exception ex)
                    {
                        isNewProduct = false;
                    }

                    if (isNewProduct)
                    {
                        if (!isWork) break;
                        product = new Product();
                        product.Name = productName;
                        try
                        {
                            product.TradeMark = Globals.CleanWordCell(tbl.Cell(i, 3).Range.Text.Trim());
                        }
                        catch
                        {
                            product.TradeMark = "";
                        }

                        // Проверить на повтор
                        Product repeatProduct = mvm.dc.Products.FirstOrDefault(m => (m.Name == product.Name && m.TradeMark == product.TradeMark));
                        if (repeatProduct != null)
                        {
                            if (repeatProduct.Templates.FirstOrDefault(m => m.Name.Trim().ToLower() == "форма 2") == null)
                            {
                                product = repeatProduct;
                            }
                            else
                            {
                                productRepeatCount++;
                                continue;
                            }
                        }
                        else
                        {
                            product.Rubric = r;
                            mvm.dc.Products.Add(product);
                            t.Products.Add(product);
                            productAddedCount++;
                            mvm.dc.SaveChanges();
                            try
                            {
                                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    mvm.ProductCollection.Add(product);
                                }));
                            }
                            catch { }

                        }

                        product.Templates.Add(mvm.dc.Templates.FirstOrDefault(m => m.Name.ToLower() == "форма 2"));
                        try
                        {
                            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                            {
                                mvm.TemplateCollection.FirstOrDefault(m => m.Name.ToLower() == "форма 2").Products.Add(product);
                            }));
                        }
                        catch { }

                        //mvm.TemplateCollection = new ObservableCollection<Template>(mvm.dc.Templates);

                    }

                    // Добавляем свойство
                    property = new Property();
                    product.Properties.Add(property);

                    try
                    {
                        // Требуемый параметр
                        ParamValue pv = new ParamValue();
                        property.ParamValues.Add(pv);

                        pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требуемый параметр" && m.Template.Name.ToLower() == "форма 2");
                        pv.Property = property;
                        pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 4).Range.Text.Trim()));

                        // Требуемое значение
                        pv = new ParamValue();
                        property.ParamValues.Add(pv);

                        pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требуемое значение" && m.Template.Name.ToLower() == "форма 2");
                        pv.Property = property;
                        pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 5).Range.Text.Trim()));

                        // Значение, предлагаемое участником
                        pv = new ParamValue();
                        property.ParamValues.Add(pv);

                        pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Значение, предлагаемое участником" && m.Template.Name.ToLower() == "форма 2");
                        pv.Property = property;
                        try
                        {
                            pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 6).Range.Text.Trim()));
                        }
                        catch
                        {
                            pv.Value = "";
                        }

                        // Единица измерения
                        pv = new ParamValue();
                        property.ParamValues.Add(pv);

                        pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Единица измерения" && m.Template.Name.ToLower() == "форма 2");
                        pv.Property = property;
                        pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 7).Range.Text.Trim()));

                        // Сертификация
                        pv = new ParamValue();
                        property.ParamValues.Add(pv);

                        pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Сертификация" && m.Template.Name.ToLower() == "форма 2");
                        pv.Property = property;
                        try
                        {
                            pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 8).Range.Text.Trim()));
                        }
                        catch
                        {
                            pv.Value = "";
                        }
                    }
                    catch (Exception ex) {
                        string sss = "";
                    }
                }

                // Закрываем приложение
                application.Quit(ref missing, ref missing, ref missing);
                application = null;

                return ResultType_enum.Done;

                // Заносим продукты в БД
                //return dbEngineDocs.SetProducts(DocTemplate.Template_2, products, out productAddedCount, out productRepeatCount, out message);
            }
            catch (Exception ex)
            {
                message = ex.Message + '\n' + ex.StackTrace;
                return ResultType_enum.Error;
            }
            finally {
                isWork = false;
            }
        }
Exemplo n.º 34
0
        public void createWord(string saved_path, bool newSmry)
        {
            word_app = createWordApp();
            this.insertBookmark(saved_doc_list);
            object strFileName = saved_path;
            //MessageBox.Show(strFileName.ToString());
            if (System.IO.File.Exists((string)strFileName))
                System.IO.File.Delete((string)strFileName);
            Object Nothing = System.Reflection.Missing.Value;

            word_wrt = word_app.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            object oStyleName = Word.WdBuiltinStyle.wdStyleBodyText;  //"Heading 1";
            word_wrt.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            word_wrt.Paragraphs.Last.Range.set_Style(ref oStyleName);
            string strContent = "Schlüsselwörter \r";
            word_wrt.Paragraphs.Last.Range.Font.Size = 14;
            word_wrt.Paragraphs.Last.Range.Font.Bold = 1;
            word_wrt.Paragraphs.Last.Range.Text = strContent;

            this.writeSammary();

            //将WordDoc文档对象的内容保存为DOC文档
            word_wrt.SaveAs(ref strFileName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //关闭WordDoc文档对象
            word_wrt.Close(ref Nothing, ref Nothing, ref Nothing);

            //Test code ##
            this.buildTOC(saved_path, newSmry);
            //Test code ##

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

            word_app = null;
            word_show = null;
        }
Exemplo n.º 35
0
        private void PerformBuildRequirements()
        {
            _excel = new Excel.Application();
            _word = new Word.Application();
            _word.Visible = true;
            _excel.Visible = true;

            this.BeginInvoke(
                        new Action<Form1>(s =>
                        {
                            btnBuild.Enabled = false;
                            btnBuild.Text = "Working";
                        }), new object[] { this });

            var spreadsheetPath = tbSpreadsheetPath.Text;

            if (File.Exists(spreadsheetPath))
            {
                var workbook = _excel.Workbooks.Open(spreadsheetPath);
                var requirements = new List<Requirement>();
                Word.Document doc = BuildRequirementsDoc(workbook, out requirements);
                if (cbBuildTrace.Enabled)
                {
                    BuildTraceMatrix(workbook, requirements);
                    try
                    {
                        workbook.Save();
                    }
                    catch (Exception) { }
                }
                try
                {
                    // This call throws when the user elects to 'cancel' the save operation.
                    doc.Save();
                }
                catch (Exception) { }
            }
            else
            {
                MessageBox.Show("No spreadsheet selected.");
            }

            foreach (Excel.Workbook wb in _excel.Workbooks)
            {
                wb.Close();
            }
            _excel.Quit();
            _word.Quit(ref Missing, ref Missing, ref Missing);

            this.BeginInvoke(
                        new Action<Form1>(s =>
                        {
                            btnBuild.Enabled = true;
                            btnBuild.Text = "Build";
                        }), new object[] { this });
        }
Exemplo n.º 36
0
        private void wordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog2.Filter = "doc files (*.doc)|*.doc|All files (*.*)|*.*";
            saveFileDialog2.FilterIndex = 2;
            saveFileDialog2.RestoreDirectory = true;

            if (saveFileDialog2.ShowDialog() == DialogResult.OK)
            {
                Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
                Object missing = Type.Missing;
                Word.Document word1 = application.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                //object text = "tesfsdfkslghsdgjh";
                //word1.Paragraphs[1].Range.InsertParagraphAfter();
                //word1.Paragraphs[1].Range.Text = "asaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                //word1.Footnotes.Location = Word.WdFootnoteLocation.wdBeneathText;
                //word1.Footnotes.NumberStyle = Word.WdNoteNumberStyle.wdNoteNumberStyleLowercaseRoman;
                //word1.Footnotes.Add(word1.Paragraphs[1].Range.Words[2].Characters[2], ref missing, ref text);
                Microsoft.Office.Interop.Word.Document doc = application.ActiveDocument;
                Microsoft.Office.Interop.Word.Range range = doc.Paragraphs[doc.Paragraphs.Count].Range;
                dataSetTemp = dbw1.ReadMetricsByReport(listView2.Items[listView2.SelectedIndices[0]].Text);
                doc.Tables.Add(range, dataSetTemp.Tables[0].Rows.Count + 1, 6, ref missing, ref missing);
                doc.Tables[1].Cell(1, 1).Range.Text = "NAME metric";
                doc.Tables[1].Cell(1, 2).Range.Text = "MIN value";
                doc.Tables[1].Cell(1, 3).Range.Text = "CUR value";
                doc.Tables[1].Cell(1, 4).Range.Text = "MAX value";
                doc.Tables[1].Cell(1, 5).Range.Text = "VALUE";
                doc.Tables[1].Cell(1, 6).Range.Text = "RATE";
                for (int i = 0; i < dataSetTemp.Tables[0].Rows.Count; i++)
                {
                    dataSetTemp1 = dbw1.ReadInfoMetricByReportMetric(listView2.Items[listView2.SelectedIndices[0]].Text, dataSetTemp.Tables[0].Rows[i].ItemArray[0].ToString());
                    doc.Tables[1].Cell(i + 2, 1).Range.Text = dataSetTemp.Tables[0].Rows[i].ItemArray[0].ToString();
                    doc.Tables[1].Cell(i + 2, 2).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[2].ToString();
                    doc.Tables[1].Cell(i + 2, 3).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[0].ToString();
                    doc.Tables[1].Cell(i + 2, 4).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[3].ToString();
                    doc.Tables[1].Cell(i + 2, 5).Range.Text = Double.Parse(dataSetTemp1.Tables[0].Rows[0].ItemArray[4].ToString()).ToString("F5");
                    doc.Tables[1].Cell(i + 2, 6).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[5].ToString();
                }
                doc.Tables[1].Columns.AutoFit();
                Word.Border[] borders = new Word.Border[6];
                Word.Table tbl = doc.Tables[doc.Tables.Count];
                borders[0] = tbl.Borders[Word.WdBorderType.wdBorderLeft];
                borders[1] = tbl.Borders[Word.WdBorderType.wdBorderRight];
                borders[2] = tbl.Borders[Word.WdBorderType.wdBorderTop];
                borders[3] = tbl.Borders[Word.WdBorderType.wdBorderBottom];
                borders[4] = tbl.Borders[Word.WdBorderType.wdBorderHorizontal];
                borders[5] = tbl.Borders[Word.WdBorderType.wdBorderVertical];
                foreach (Word.Border border in borders)
                {
                    border.LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    border.Color = Word.WdColor.wdColorBlack;
                }
                application.Documents[word1].SaveAs(saveFileDialog2.FileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                application.Quit();
                string info = "Doc file saved at\n" + saveFileDialog2.FileName;
                MessageBox.Show(this, info, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 37
0
        /// <summary>
        /// Чтение текста из файла
        /// </summary>
        /// <param name="str"> подается на вход. Адрес папки с файлами. </param>
        /// <returns> Возвращает весь текст из документа в перемнной типа string </returns>
        public static string Read(ref string str)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss = System.Reflection.Missing.Value;
            Console.WriteLine("Input name of file. Example: Text.docx or Text.doc");
            string nameFile = Console.ReadLine();
            string copyName = nameFile;
            //Если файл имеет неверное расширение, т.е. это не Word-овский файл, то выведется сообщение об ошибке.
            if (copyName.EndsWith(".docx") || copyName.EndsWith(".doc"))
            {
                string adresse = str + nameFile;
                object path = @adresse;
                object readOnly = true;
                //Проверка на правильность указания адреса файла
                try
                {
                    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 += docs.Paragraphs[i + 1].Range.Text.ToString();
                    docs.Close();
                    word.Quit();
                    return totaltext;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error! File not find!");
                    Console.ReadKey();
                    return "";
                }
            }
            else
            {
                Console.WriteLine("Error!!! Invalid file extension!");
                Console.ReadKey();
                return "";
            }
        }