Exemplo n.º 1
0
        //записывает текст из текущего документа в массив строк - каждый абзац с новой строки
        public string[] GetAllText()
        {
            Word.Paragraphs wordparagraphs = null;
            try
            {
                wordparagraphs = worddocument.Paragraphs;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
            string[] allText = null;
            if ((wordparagraphs != null) && (wordparagraphs.Count > 0))
            {
                allText = new string[wordparagraphs.Count];
            }
            else
            {
                return(null);
            }

            for (int i = 1; i <= wordparagraphs.Count; i++)
            {
                Word.Paragraph wordparagraph = (Word.Paragraph)wordparagraphs[i];
                allText[i - 1] = wordparagraph.Range.Text;
            }
            return(allText);
        }
        protected bool ProcessParagraphs(OfficeDocumentProcessor aWordProcessor, Word.Paragraphs aParagraphs)
        {
            foreach (Word.Paragraph aParagraph in aParagraphs)
            {
                // get the Range object for this paragraph
                Word.Range aParagraphRange = aParagraph.Range;

                // if we're picking up where we left off and we're not there yet...
                int nCharIndex = 0;
                if (aWordProcessor.AreLeftOvers)
                {
                    if (aWordProcessor.LeftOvers.Start > aParagraphRange.End)
                    {
                        continue;   // skip to the next paragraph
                    }
                    nCharIndex = aWordProcessor.LeftOvers.StartIndex;
                    aWordProcessor.LeftOvers = null; // turn off "left overs"
                }

                WordRange aThisParagraph = new WordRange(aParagraphRange);
                if (!ProcessRangeAsWords(aWordProcessor, aThisParagraph, nCharIndex))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 3
0
        //записывает текст из массива строк в документ, каждый элемент массива - новый абзац
        public bool WriteAllText(string[] content)
        {
            //Получаем ссылки на параграфы документа
            worddocument.Content.Font.Size  = 14;
            worddocument.Content.Font.Bold  = 0;
            worddocument.Content.Font.Name  = "Times New Roman";
            worddocument.Content.Font.Color = Word.WdColor.wdColorBlack;
            worddocument.Content.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphJustify;

            try
            {
                Word.Paragraphs wordparagraphs = worddocument.Paragraphs;
                for (int i = 0; i < content.Length; i++)
                {
                    object oMissing = Missing.Value;
                    worddocument.Paragraphs.Add(ref oMissing);
                    Word.Paragraph wordparagraph = (Word.Paragraph)wordparagraphs[i + 1];
                    wordparagraph.Range.Text = content[i];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
            return(true);
        }
Exemplo n.º 4
0
        public void wTitle(Office.IRibbonControl control)
        {
            wordApp = Globals.ThisAddIn.Application;
            Word.Paragraphs par = wordApp.Application.ActiveDocument.Paragraphs;
            foreach (Word.Paragraph p in par)
            {
                p.Range.Font.NameFarEast = "方正仿宋_GBK";
                p.Range.Font.NameAscii   = "宋体";
                p.Range.Font.Size        = 16;
                string pattern1 = "[一二三四五六七八九十]{1,3}、";
                string pattern2 = "^[((][一二三四五六七八九十]{1,3}[))]";
                string pattern3 = "[一二三四五六七八九十]{1,3}、.*。";
                string pattern4 = "^[((][一二三四五六七八九十]{1,3}[))].*。";

                if (System.Text.RegularExpressions.Regex.IsMatch(p.Range.Text, pattern3))
                {
                    p.Range.Sentences[1].Font.NameFarEast = "方正黑体_GBK";
                }
                else if (System.Text.RegularExpressions.Regex.IsMatch(p.Range.Text, pattern4))
                {
                    p.Range.Sentences[1].Font.NameFarEast = "方正楷体_GBK";
                }
                else if (p.Range.Text.Length < 40 && System.Text.RegularExpressions.Regex.IsMatch(p.Range.Text, pattern1))
                {
                    p.Range.Font.NameFarEast = "方正黑体_GBK";
                }
                else if (p.Range.Text.Length < 40 && System.Text.RegularExpressions.Regex.IsMatch(p.Range.Text, pattern2))
                {
                    p.Range.Font.NameFarEast = "方正楷体_GBK";
                }
                p.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;
            }
        }
Exemplo n.º 5
0
        private void createThesis()
        {
            buttonX3.Enabled = false;
            int start, end;

            MSWord.Paragraphs pgs = wordDoc.TablesOfContents[1].Range.Paragraphs;
            wordApp.Selection.SetRange(wordDoc.TablesOfContents[1].Range.End, wordDoc.TablesOfContents[1].Range.End);
            foreach (MSWord.Paragraph pa in pgs)
            {
                if (pa.Range.Text.Split('\t')[0].Trim() != "")
                {
                    pa.Range.Hyperlinks[1].Follow();
                    //wordApp.Visible = false;
                    start = wordApp.Selection.Range.End + 1;
                    wordApp.Selection.SetRange(start, start);
                    if (pa.Next() != null)
                    {
                        if (pa.Next().Range.Text.Trim() == "")
                        {
                            end = wordDoc.Content.End;
                        }
                        else
                        {
                            pa.Next().Range.Hyperlinks[1].Follow();
                            //wordApp.Visible = false;
                            end = wordApp.Selection.Range.Start - 1;
                        }
                        wordApp.Selection.SetRange(start, end);
                    }
                    else
                    {
                        break;
                    }

                    try
                    {
                        if (wordApp.Selection.Range.Text.Trim() != "")
                        {
                            wordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = 0;
                            wordApp.Selection.ParagraphFormat.LeftIndent  = wordApp.CentimetersToPoints(float.Parse("0"));
                            wordApp.Selection.ParagraphFormat.RightIndent = wordApp.CentimetersToPoints(float.Parse("0"));
                            wordApp.Selection.ClearFormatting();
                            wordApp.Selection.Copy();
                            tempDoc = tempApp.Documents.Add();
                            tempDoc.Paragraphs.Last.Range.Paste();
                            tempDoc.SaveAs(officetemp + titleHandle(pa.Range.Text.Split('\t')[0].Trim()) + ".doc", ref format, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS);
                            tempDoc.Close(ref QS, ref QS, ref QS);
                        }
                    }
                    catch { }
                    wordApp.Selection.SetRange(end, end);
                    progressBarX1.Value++;
                }
            }
            listSave();
            saveDocument();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }
Exemplo n.º 6
0
        public Braile()
        {
            Word.Paragraphs paragraphs = Globals.ThisAddIn.Application.ActiveDocument.Paragraphs;

            foreach (Word.Paragraph paragraph in paragraphs)
            {
                this.text += paragraph.Range.Text + "\n";
            }
        }
Exemplo n.º 7
0
        static public void WordRecordingRange(String textWord, Object start, object end)
        {
            Word.Paragraphs wordparagraphs       = worddocument.Paragraphs;
            Word.Range      wordrange            = worddocument.Range(ref start, ref end);
            Object          defaultTableBehavior = Word.WdDefaultTableBehavior.wdWord9TableBehavior;
            Object          autoFitBehavior      = Word.WdAutoFitBehavior.wdAutoFitWindow;

            wordrange.Text = textWord;
        }
        /// <summary>
        /// Remove Blank Page in Word document
        /// </summary>
        private bool RemoveBlankPage()
        {
            Word.Application wordapp    = null;
            Word.Document    doc        = null;
            Word.Paragraphs  paragraphs = null;
            try
            {
                // Start Word APllication and set it be invisible
                wordapp         = new Word.Application();
                wordapp.Visible = false;
                doc             = wordapp.Documents.Open(wordPath);
                paragraphs      = doc.Paragraphs;
                foreach (Word.Paragraph paragraph in paragraphs)
                {
                    if (paragraph.Range.Text.Trim() == string.Empty)
                    {
                        paragraph.Range.Select();
                        wordapp.Selection.Delete();
                    }
                }

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

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

            return(true);
        }
Exemplo n.º 9
0
 public void ZJName(Office.IRibbonControl control)
 {
     wordApp = Globals.ThisAddIn.Application;
     Word.Paragraphs par = wordApp.Application.ActiveDocument.Paragraphs;
     par[par.Count].Range.InsertAfter("\n\n\n");
     wordApp.Application.ActiveDocument.Paragraphs[wordApp.Application.ActiveDocument.Paragraphs.Count].Range.InsertAfter("隆阳区住房和城乡建设局\n");
     wordApp.Application.ActiveDocument.Paragraphs[wordApp.Application.ActiveDocument.Paragraphs.Count].Range.InsertAfter(DateTime.Now.Year + "年" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日");
     Word.Paragraphs par2 = wordApp.Application.ActiveDocument.Paragraphs;
     par2[par2.Count].Range.ParagraphFormat.Alignment     = Word.WdParagraphAlignment.wdAlignParagraphRight;
     par2[par2.Count - 1].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
 }
Exemplo n.º 10
0
        // Remove Blank Page in Word document
        private bool RemoveBlankPage()
        {
            Word.Application wordapp    = null;
            Word.Document    doc        = null;
            Word.Paragraphs  paragraphs = null;
            try
            {
                // Start Word APllication and set it be invisible
                wordapp         = new Word.Application();
                wordapp.Visible = false;
                doc             = wordapp.Documents.Open(wordPath);
                paragraphs      = doc.Paragraphs;
                foreach (Word.Paragraph paragraph in paragraphs)
                {
                    if (paragraph.Range.Text.Trim() == string.Empty)
                    {
                        paragraph.Range.Select();
                        wordapp.Selection.Delete();
                    }
                }

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

                // Quit the word application
                wordapp.Quit();
            }
            catch
            {
                throw;
            }
            finally
            {
                // Clean up the unmanaged Word COM resources by explicitly
                if (paragraphs != null)
                {
                    Marshal.FinalReleaseComObject(paragraphs);
                    paragraphs = null;
                }
                if (doc != null)
                {
                    Marshal.FinalReleaseComObject(doc);
                    doc = null;
                }
                if (wordapp != null)
                {
                    Marshal.FinalReleaseComObject(wordapp);
                    wordapp = null;
                }
            }

            return(true);
        }
Exemplo n.º 11
0
 public void DelPar(Office.IRibbonControl control)
 {
     wordApp = Globals.ThisAddIn.Application;
     Word.Paragraphs par = wordApp.Application.ActiveDocument.Paragraphs;
     foreach (Word.Paragraph p in par)
     {
         if (p.Range.Text.Length == 1)
         {
             p.Range.Delete();
         }
     }
 }
Exemplo n.º 12
0
        private void readInfo()
        {
            wordDoc = wordApp.Documents.Open((object)docName, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS);
            wordApp.ActiveWindow.View.ShowFieldCodes = false;
            //wordApp.Visible = true;
            MSWord.Paragraphs pgs = wordDoc.TablesOfContents[1].Range.Paragraphs;

            int start = wordDoc.GoTo(MSWord.WdGoToItem.wdGoToPage, MSWord.WdGoToDirection.wdGoToAbsolute, QS, 1).Start;
            int end   = wordDoc.GoTo(MSWord.WdGoToItem.wdGoToPage, MSWord.WdGoToDirection.wdGoToAbsolute, QS, 2).Start;
            //richTextBoxEx1.Text = wordDoc.Range(start, end).Text;
            //richTextBoxEx1.AppendText("\n"+pgs[1].Next().Range.Hyperlinks[1]);
        }
        public bool ProcessWholeParagraphs(OfficeDocumentProcessor aWordProcessor, Word.Paragraphs aParagraphs)
        {
            foreach (Word.Paragraph aParagraph in aParagraphs)
            {
                // get the Range object for this paragraph
                Word.Range aParagraphRange = aParagraph.Range;

                // if we're picking up where we left off and we're not there yet...
                int nCharIndex = 0;
                if (aWordProcessor.AreLeftOvers)
                {
                    if (aWordProcessor.LeftOvers.Start > aParagraphRange.End)
                    {
                        continue;   // skip to the next paragraph
                    }
                    nCharIndex = aWordProcessor.LeftOvers.StartIndex;
                    aWordProcessor.LeftOvers = null; // turn off "left overs"
                }

                WordRange aRunRange  = new WordRange(aParagraphRange);
                int       nEndIndex  = --aRunRange.EndIndex;
                int       nLastIndex = nCharIndex;

                // exclude the paragraph end and process it as a whole unit (we may have to do this multiple times
                bool bStop = false;
                while (!bStop && (nCharIndex < nEndIndex))
                {
                    aRunRange.StartIndex = nCharIndex;
                    if (aRunRange.EndIndex != nEndIndex)
                    {
                        aRunRange.EndIndex = nEndIndex;
                    }

                    nLastIndex = nCharIndex;

                    System.Diagnostics.Trace.WriteLine(String.Format("Start: {0}, End: {1}, text: {2}, length: {3}",
                                                                     aRunRange.Start, aRunRange.End, aRunRange.Text, aRunRange.Text.Length));

                    if (!aWordProcessor.Process(aRunRange, ref nCharIndex))
                    {
                        aWordProcessor.LeftOvers = aRunRange;
                        return(false);
                    }

                    if (nLastIndex == nCharIndex)
                    {
                        break;
                    }
                }
            }

            return(true);
        }
Exemplo n.º 14
0
        public static void fillTemplate(string templatePath, Dictionary <string, string> mappedValues)
        {
            Word.Document doc = null;
            try
            {
                Word.Application app = new Word.Application();
                doc = app.Documents.Open(templatePath);
                doc.Activate();

                Word.Paragraphs paragraphs = doc.Paragraphs;
                Word.Range      wRange;

                foreach (Word.Paragraph mark in paragraphs)
                {
                    wRange = mark.Range;
                    foreach (KeyValuePair <string, string> entry in mappedValues)
                    {
                        string oldValue = wRange.Text;
                        if (oldValue.Contains(entry.Key))
                        {
                            string newParagraphVal = oldValue.Replace(entry.Key, entry.Value).Trim();
                            Console.Write(newParagraphVal);
                            wRange.Text = newParagraphVal;
                        }
                    }
                }

                string filledDocPath = Path.GetTempFileName();
                Console.WriteLine(filledDocPath);
                doc.SaveAs2(filledDocPath);

                app.Documents.Open(filledDocPath);
                app.Activate();
                app.Visible = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Console.ReadLine();
            }
            finally
            {
                if (doc != null)
                {
                    doc = null;
                }
            }
        }
Exemplo n.º 15
0
        public WordParagraphs(Word.Selection aBasedOnSelection)
        {
            if (aBasedOnSelection.End > aBasedOnSelection.Start)
            {
                Word.Paragraphs aParagraphs     = aBasedOnSelection.Paragraphs;
                int             nParagraphCount = aParagraphs.Count;
                int             i      = 1;
                Word.Range      aRange = aParagraphs[i].Range.Duplicate;
                aRange.Start = aBasedOnSelection.Start;
                Add(aRange);

                while (i < nParagraphCount)
                {
                    aRange = aParagraphs[++i].Range.Duplicate;
                    Add(aRange);
                }

                aRange.End = aBasedOnSelection.End;
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Создание названия таблицы
 /// </summary>
 public async Task CreateTableNameAsync()
 {
     await Task.Factory.StartNew(() =>
     {
         // Получаем ссылки на параграфы документа
         _wordParagraphs = _wordDocument.Paragraphs;
         // Будем работать с первым параграфом
         _wordParagraph = _wordParagraphs[1];
         // Выводим текст в первый параграф
         _wordParagraph.Range.Text = "Таблица 1.X – Рецензия-рейтинг на проведение занятия со студентами при прохождении научно-педагогической практики";
         // Меняем характеристики текста и параграфа
         _wordParagraph.Range.Font.Color  = Word.WdColor.wdColorBlack;
         _wordParagraph.Range.Font.Size   = 12;
         _wordParagraph.Range.Font.Name   = "Times New Roman";
         _wordParagraph.Range.Font.Italic = 0;
         _wordParagraph.Range.Font.Bold   = 0;
         // Абзацный отступ
         _wordParagraph.FirstLineIndent = 0;
         // Выравнивание
         _wordParagraph.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     });
 }
        public bool ProcessParagraphsIsoFormat(OfficeDocumentProcessor aWordProcessor, Word.Paragraphs aParagraphs)
        {
            foreach (Word.Paragraph aParagraph in aParagraphs)
            {
                // get the Range object for this paragraph
                Word.Range aParagraphRange = aParagraph.Range;

                // if we're picking up where we left off and we're not there yet...
                int nCharIndex = 0;
                if (aWordProcessor.AreLeftOvers)
                {
                    if (aWordProcessor.LeftOvers.Start > aParagraphRange.End)
                    {
                        continue;                           // skip to the next paragraph
                    }
                    nCharIndex = aWordProcessor.LeftOvers.StartIndex;
                    aWordProcessor.LeftOvers = null;                     // turn off "left overs"
                }

                WordRange aRunRange   = new WordRange(aParagraphRange);
                int       nStartIndex = aRunRange.StartIndex;
                System.Diagnostics.Debug.Assert(nStartIndex == 0);

                // if we have mixed character formatting, then use a binary search algorithm to find
                //	the maximum run.
                if (MixedCharacterFormatting(aRunRange))
                {
                    int nWidth = aRunRange.EndIndex / 2;

                    do
                    {
                        aRunRange.EndIndex++;
                    } while (!MixedCharacterFormatting(aRunRange));

                    aRunRange.EndIndex--;                       // back up one
                }
                else
                {
                    // the whole paragraph seems to be iso formatted, so exclude the paragraph end and
                    // process it as a whole unit
                    aRunRange.EndIndex--;
                    if (!aWordProcessor.Process(aRunRange, ref nCharIndex))
                    {
                        aWordProcessor.LeftOvers = aRunRange;
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Создание таблицы
        /// </summary>
        /// <param name="list">Данные для заполнения</param>
        public async Task CreateTableAsync(List <Report> list)
        {
            await Task.Factory.StartNew(() =>
            {
                // Добавляем в документ несколько параграфов
                _wordDocument.Paragraphs.Add(Missing.Value);

                // Получаем ссылки на параграфы документа
                _wordParagraphs = _wordDocument.Paragraphs;
                // Будем работать со вторым параграфом
                _wordParagraph = _wordParagraphs[2];

                // Новая таблица
                Word.Table _wordTable = _wordDocument.Tables.Add(_wordParagraph.Range, list.Count + 2, 7,
                                                                 Word.WdDefaultTableBehavior.wdWord9TableBehavior, Word.WdAutoFitBehavior.wdAutoFitWindow);

                #region Ширина столбцов
                _wordTable.Columns[1].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[2].SetWidth(ColumnWidth: 192f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[3].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[4].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[5].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[6].SetWidth(ColumnWidth: 28f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                _wordTable.Columns[7].SetWidth(ColumnWidth: 135f, RulerStyle: Word.WdRulerStyle.wdAdjustNone);
                #endregion

                #region Объединение ячеек
                // № п/п
                object begCell           = _wordTable.Cell(1, 1).Range.Start;
                object endCell           = _wordTable.Cell(2, 1).Range.End;
                Word.Range wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.Cells.Merge();

                // Критерии оценки
                begCell       = _wordTable.Cell(1, 2).Range.Start;
                endCell       = _wordTable.Cell(2, 2).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.Cells.Merge();

                // Шкала оценок
                begCell       = _wordTable.Cell(1, 3).Range.Start;
                endCell       = _wordTable.Cell(1, 6).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.Cells.Merge();

                // Краткое обоснование оценки
                begCell       = _wordTable.Cell(1, 4).Range.Start;
                endCell       = _wordTable.Cell(2, 7).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.Cells.Merge();
                #endregion

                #region Заполнение таблицы
                // Шапка
                Word.Range _wordCellRange = _wordTable.Cell(1, 1).Range;
                _wordCellRange.Text       = "№ п/п";
                _wordCellRange            = _wordTable.Cell(1, 2).Range;
                _wordCellRange.Text       = "Критерии оценки";
                _wordCellRange            = _wordTable.Cell(1, 3).Range;
                _wordCellRange.Text       = "Шкала оценок";
                _wordCellRange            = _wordTable.Cell(1, 4).Range;
                _wordCellRange.Text       = "Краткое обоснование\nоценки";

                #if DEBUG
                // Видимость Word'а
                _wordApp.Visible = true;
                #endif

                // Виды оценок
                for (int i = 3; i < 7; i++)
                {
                    _wordCellRange      = _wordTable.Cell(2, i).Range;
                    _wordCellRange.Text = (i - 1).ToString();
                }

                for (int i = 0; i < list.Count; i++)
                {
                    // № п/п
                    _wordCellRange      = _wordTable.Cell(i + 3, 1).Range;
                    _wordCellRange.Text = list[i].Number.ToString();

                    // Критерии оценки
                    _wordCellRange      = _wordTable.Cell(i + 3, 2).Range;
                    _wordCellRange.Text = list[i].Name.ToString();

                    // 2
                    _wordCellRange      = _wordTable.Cell(i + 3, 3).Range;
                    _wordCellRange.Text = list[i].Mark2.ToString();

                    // 3
                    _wordCellRange      = _wordTable.Cell(i + 3, 4).Range;
                    _wordCellRange.Text = list[i].Mark3.ToString();

                    // 4
                    _wordCellRange      = _wordTable.Cell(i + 3, 5).Range;
                    _wordCellRange.Text = list[i].Mark4.ToString();

                    // 5
                    _wordCellRange      = _wordTable.Cell(i + 3, 6).Range;
                    _wordCellRange.Text = list[i].Mark5.ToString();

                    // Краткое обоснование оценки
                    _wordCellRange      = _wordTable.Cell(i + 3, 7).Range;
                    _wordCellRange.Text = list[i].Comment.ToString();
                }

                // Выравнивание
                begCell       = _wordTable.Cell(1, 1).Range.Start;
                endCell       = _wordTable.Cell(1, 4).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                _wordApp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                begCell       = _wordTable.Cell(2, 3).Range.Start;
                endCell       = _wordTable.Cell(2, 6).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                _wordApp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                begCell       = _wordTable.Cell(3, 3).Range.Start;
                endCell       = _wordTable.Cell(17, 6).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                _wordApp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                begCell       = _wordTable.Cell(3, 1).Range.Start;
                endCell       = _wordTable.Cell(17, 1).Range.End;
                wordcellrange = _wordDocument.Range(ref begCell, ref endCell);
                wordcellrange.Select();
                _wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                _wordApp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                #endregion

                // Меняем характеристики текста в таблице
                _wordTable.Range.Font.Color  = Word.WdColor.wdColorBlack;
                _wordTable.Range.Font.Size   = 12;
                _wordTable.Range.Font.Name   = "Times New Roman";
                _wordTable.Range.Font.Italic = 0;
                _wordTable.Range.Font.Bold   = 0;
            });
        }
Exemplo n.º 19
0
        internal WordDocumentInfo RetrieveTextWithPosition(string inputPath)
        {
            var ret = new WordDocumentInfo();

            Text = "";
            doc  = OpenDocument(inputPath);

            //get header
            string header = "";

            foreach (WinWord.Section aSection in application.ActiveDocument.Sections)
            {
                foreach (WinWord.HeaderFooter aHeader in aSection.Headers)
                {
                    header += aHeader.Range.Text;
                }
            }
            ret.Header = header;


            int left   = 0;
            int top    = 0;
            int width  = 0;
            int height = 0;


            WinWord.Window     w          = doc.ActiveWindow;
            WinWord.Paragraphs paragraphs = doc.Paragraphs;

            int charIndex = 0;
            int unindentedParagraphLeft = 0;

            foreach (WinWord.Paragraph paragraph in paragraphs)
            {
                var range = paragraph.Range;

                if (!(range.TextVisibleOnScreen == 1))
                {
                    //text not visible --> change view
                    application.GoForward();
                }


                if (range.ParagraphFormat.FirstLineIndent != 0)   // if it is indented
                //get difference to unindented Line and add as space
                {
                    w.GetPoint(out left, out top, out width, out height, range);
                    ReplaceTab(left - unindentedParagraphLeft, range.Font.Size);
                }
                else
                {
                    try {
                        w.GetPoint(out left, out top, out width, out height, range);
                    }
                    catch {
                    }
                    finally {
                        unindentedParagraphLeft = left;
                    }
                }


                for (int i = 0; i < paragraph.Range.Text.Count(); i++)  //for each character in the paragraph
                {
                    range.Start = charIndex;
                    range.End   = charIndex + 1;

                    //if its a tab
                    if (range.Text == "\t" || range.Text == "\r")
                    {
                        //determine width
                        w.GetPoint(out left, out top, out width, out height, range);
                        ReplaceTab((float)width, range.Font.Size);
                    }
                    //if its a normal char
                    else
                    {
                        Text += range.Text;
                    }
                    charIndex++;
                }
                Text += "\n";
            }
            ret.Text = Text;

            doc.Close(SaveChanges: MsoTriState.msoFalse);
            return(ret);
        }
Exemplo n.º 20
0
        public static void AutomateWord()
        {
            object missing = Type.Missing;
            object notTrue = false;

            Word.Application oWord    = null;
            Word.Documents   oDocs    = null;
            Word.Document    oDoc     = null;
            Word.Paragraphs  oParas   = null;
            Word.Paragraph   oPara    = null;
            Word.Range       oParaRng = null;
            Word.Font        oFont    = null;

            try
            {
                // Create an instance of Microsoft Word and make it invisible.

                oWord         = new Word.Application();
                oWord.Visible = false;
                Console.WriteLine("Word.Application is started");

                // Create a new Document and add it to document collection.
                oDoc = oWord.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                Console.WriteLine("A new document is created");

                // Insert a paragraph.

                Console.WriteLine("Insert a paragraph");

                oParas        = oDoc.Paragraphs;
                oPara         = oParas.Add(ref missing);
                oParaRng      = oPara.Range;
                oParaRng.Text = "Heading 1";
                oFont         = oParaRng.Font;
                oFont.Bold    = 1;
                oParaRng.InsertParagraphAfter();

                // Save the document as a docx file and close it.

                Console.WriteLine("Save and close the document");

                object fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.docx";
                object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument;

                // Saves the document with a new name or format.
                // Some of the arguments for this method correspond to
                // the options in the Save As dialog box.
                // For details,please refer to
                // :http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.saveas(VS.80).aspx
                oDoc.SaveAs(ref fileName, ref fileFormat, 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);
                ((Word._Document)oDoc).Close(ref missing, ref missing,
                                             ref missing);

                // Quit the Word application.

                Console.WriteLine("Quit the Word application");
                ((Word._Application)oWord).Quit(ref notTrue, ref missing,
                                                ref missing);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution1.AutomateWord throws the error: {0}",
                                  ex.Message);
            }
            finally
            {
                // Clean up the unmanaged Word COM resources by explicitly
                // calling Marshal.FinalReleaseComObject on all accessor objects.
                // See http://support.microsoft.com/kb/317109.

                if (oFont != null)
                {
                    Marshal.FinalReleaseComObject(oFont);
                    oFont = null;
                }
                if (oParaRng != null)
                {
                    Marshal.FinalReleaseComObject(oParaRng);
                    oParaRng = null;
                }
                if (oPara != null)
                {
                    Marshal.FinalReleaseComObject(oPara);
                    oPara = null;
                }
                if (oParas != null)
                {
                    Marshal.FinalReleaseComObject(oParas);
                    oParas = null;
                }
                if (oDoc != null)
                {
                    Marshal.FinalReleaseComObject(oDoc);
                    oDoc = null;
                }
                if (oDocs != null)
                {
                    Marshal.FinalReleaseComObject(oDocs);
                    oDocs = null;
                }
                if (oWord != null)
                {
                    Marshal.FinalReleaseComObject(oWord);
                    oWord = null;
                }
            }
        }
Exemplo n.º 21
0
 private void readListThread()
 {
     wordDoc = wordApp.Documents.Open((object)docName, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS);
     wordApp.ActiveWindow.View.ShowFieldCodes = false;
     wordApp.Visible = false;
     advTree1.Nodes.Clear();
     try
     {
         if (wordDoc.TablesOfContents.Count == 0)
         {
             if (MessageBox.Show(this, "检测到该文档中不包含目录,是否手动创建?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.Yes)
             {
                 createList();
             }
             else
             {
                 wordDoc.Close(false, ref QS, ref QS);
                 progressBarX1.ProgressType = DevComponents.DotNetBar.eProgressItemType.Standard;
                 return;
             }
         }
         MSWord.Paragraphs pgs = wordDoc.TablesOfContents[1].Range.Paragraphs;
         if (pgs.Count == 1 && pgs.First.Range.Text.IndexOf("未找到目录项") != -1)
         {
             MessageBox.Show(this, "创建失败,该文档没有目录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
             progressBarX1.ProgressType = DevComponents.DotNetBar.eProgressItemType.Standard;
             return;
         }
         int num = 0;
         foreach (MSWord.Paragraph pa in pgs)
         {
             if (pa.Range.Text.Split('\t')[0].Trim() != "")
             {
                 num++;
             }
             if (pa.Range.Text.Trim() != "" && pa.Range.Text.Trim()[0] == '摘' && num == 1)
             {
                 createNode("摘  要");
             }
             else if (pa.Range.Text.Trim() != "" && pa.Range.Text.Trim()[0] == '关' && num == 2)
             {
                 createNode("关键词");
             }
             else if (pa.Range.Text.Trim() != "" && (pa.Range.Text.Trim()[0] == 'A' || pa.Range.Text.Trim()[0] == 'a') && num == 3)
             {
                 createNode("Abstract");
             }
             else if (pa.Range.Text.Trim() != "" && (pa.Range.Text.Trim()[0] == 'K' || pa.Range.Text.Trim()[0] == 'k') && num == 4)
             {
                 createNode("Key word");
             }
             else if (pa.Range.Text.Trim() != "" && pa.Range.Text.Trim()[0] == '参' && num == pgs.Count - 2)
             {
                 createNode("参考文献");
             }
             else if (pa.Range.Text.Trim() != "" && pa.Range.Text.Trim()[0] == '致' && num == pgs.Count - 1)
             {
                 createNode("致  谢");
             }
             else
             {
                 createNode(titleHandle(pa.Range.Text.Split('\t')[0].Trim()));
             }
             Application.DoEvents();
         }
         progressBarX1.Maximum = num;
     }
     catch
     {
         advTree1.Nodes.Clear();
         MSWord.Paragraphs pgs = wordDoc.TablesOfContents[1].Range.Paragraphs;
         foreach (MSWord.Paragraph pa in pgs)
         {
             if (pa.Range.Text.Split('\t')[0].Trim() != "")
             {
                 advTree1.Nodes.Add(new DevComponents.AdvTree.Node(pa.Range.Text.Split('\t')[0].Trim()));
             }
         }
         MessageBox.Show(this, "尝试自动排版目录失败,请手动拖拽排版目录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     progressBarX1.ProgressType = DevComponents.DotNetBar.eProgressItemType.Standard;
 }
Exemplo n.º 22
0
        private void RestartParagraph()
        {
            bHasPrevTextBoxLink = false;

////
//            // if restart-par, then change the paragraph in the original document
//            if (bRestartPar)
//            {
//                Word.Range rgPar = oPars[nParIndex].Range;
//                rgPar.Text = txtText.Text;
//            }

            if (bCheckNormalText)
            {
                // get all paragraphs of normal text area (including field regions)
                oPars     = Globals.ThisAddIn.Application.ActiveDocument.Paragraphs;
                nParCount = oPars.Count;

                Word.Paragraph CurPar  = oPars[nParIndex];
                int            nCurPos = Math.Max(CurPar.Range.Start, nCursorPos);

                // start with the range of the whole active document
                Object     oRS = null, oRE = null;
                Word.Range rg = Globals.ThisAddIn.Application.ActiveDocument.Range(ref oRS, ref oRE);
                rg.End = int.MaxValue;

                // search for the first armenian character starting from the current cursor position
                nCurPos = SearchForArmenianChar(rg, nCurPos);
                if (nParIndex > nParCount)
                {
                    bCheckNormalText = false;
                    if (oShapes.Count > 0)
                    {
                        nShapeIndex = 1;
                        RestartParagraph();
                    }
                    else
                    {
                        TerminateSpellCheck();
                    }
                    return;
                }
            }
            else
            {
                if (!bCursorInShape)
                {
                    nCursorPos = 0;
                }
                if (nShapeIndex > oShapes.Count)
                {
                    TerminateSpellCheck();
                    return;
                }
                object     obj = nShapeIndex;
                Word.Shape shp = oShapes.get_Item(ref obj);

                while (nShapeIndex <= oShapes.Count && !HasText(shp))
                {
                    obj = ++nShapeIndex;
                    if (nShapeIndex > oShapes.Count)
                    {
                        RestartParagraph();
                        return;
                    }
                    shp = oShapes.get_Item(ref obj);
                }
                Word.Range rg = null;
                if (nShapeIndex <= oShapes.Count && HasText(shp))
                {
                    rg        = shp.TextFrame.TextRange;
                    oPars     = rg.Paragraphs;
                    nParCount = oPars.Count;
                    if (shp.TextFrame.ContainingRange.Start < shp.TextFrame.TextRange.Start)
                    {
                        bHasPrevTextBoxLink = true;
                    }
                }
                else
                {
                    nShapeIndex++;
                    RestartParagraph();
                    return;
                }
                nParIndex = 1;

                Word.Range rgOffset = shp.TextFrame.TextRange;
                // search for the first armenian character in the shape object
                nCursorPos = SearchForArmenianChar(rgOffset, nCursorPos);
                if (nParIndex > nParCount)
                {
                    bCheckNormalText = false;
                    if (oShapes.Count > 0)
                    {
                        nShapeIndex++;
                        RestartParagraph();
                    }
                    else
                    {
                        TerminateSpellCheck();
                    }
                    return;
                }
            }

            if (!bRestartPar)
            {
                Word.Paragraph par = oPars[nParIndex];
                Word.Range     pRg = par.Range;
                nIParOffset = Math.Max(nCursorPos - pRg.Start, 0);
                pRg.End     = pRg.Start + nIParOffset;
                nParOffset  = 0;
                if (nIParOffset > 0 && pRg.Text != null)
                {
                    nParOffset += pRg.Text.Length;
                }
                CheckParagraph(par);
            }
            bRestartPar = false;
        }
        /// <summary>
        /// Метод проверки оформления документа
        /// </summary>
        /// <param name="path">Путь к проверяемому файлу</param>
        /// <param name="action">Тип проверяемого файла</param>
        protected void ParsingFile(string path, string action)
        {
            int               countParagraph, countSection = 0, countLibrary = 0, index;
            string            pathSave = "", hat = "";
            string            type     = "txt";
            var               tmp      = 0;
            DocumentStructure document = new DocumentStructure();
            //запускаем Word
            var wordApp = new word.Application();
            var wordDoc = wordApp.Documents.Open(path);

            // Показывает открытый файл пользователю
            wordApp.Visible = false;

            wordparagraphs = wordDoc.Paragraphs;
            countParagraph = wordDoc.Paragraphs.Count;

            List <string> text = new List <string>();

            List <string> fontName       = new List <string>();
            List <double> fontSize       = new List <double>();
            List <string> color          = new List <string>();
            List <int>    inscription    = new List <int>();
            List <string> alignment      = new List <string>();
            List <double> leftIndention  = new List <double>();
            List <double> rightIndention = new List <double>();

            List <string> answer = new List <string>();

            for (int i = 1; i < countParagraph; i++)
            {
                if (wordDoc.Paragraphs[i].Range.Text != "\r" && wordDoc.Paragraphs[i].Range.Text != "\r\a")
                {
                    text.Add(wordDoc.Paragraphs[i].Range.Text);
                    fontName.Add(wordDoc.Paragraphs[i].Range.Font.Name);
                    fontSize.Add(wordDoc.Paragraphs[i].Range.Font.Size);
                    color.Add(wordDoc.Paragraphs[i].Range.Font.Color.ToString());
                    inscription.Add(wordDoc.Paragraphs[i].Range.Font.Bold);
                    alignment.Add(wordDoc.Paragraphs[i].Alignment.ToString());
                    leftIndention.Add(wordDoc.Paragraphs[i].LeftIndent);
                    rightIndention.Add(wordDoc.Paragraphs[i].RightIndent);
                }
            }

            if (action == "BKP")
            {
                pathSave = System.IO.Path.Combine(Server.MapPath("~/FilesChecks/"), "answerBKR.txt");
                foreach (var item in text)
                {
                    if (item.Trim() == "РЕФЕРАТ")
                    {
                        countSection++;
                    }
                    if (item.Trim() == "СОДЕРЖАНИЕ")
                    {
                        countSection++;
                    }
                    if (item.Trim() == "ВВЕДЕНИЕ")
                    {
                        countSection++;
                    }
                    if (item.Trim() == "ОСНОВНАЯ ЧАСТЬ")
                    {
                        countSection++;
                    }
                    if (item.Trim() == "ЗАКЛЮЧЕНИЕ")
                    {
                        countSection++;
                    }
                    if (item.Trim() == "СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ")
                    {
                        countSection++;
                    }
                }
                if (countSection < 5)
                {
                    using (StreamWriter sw = new StreamWriter(pathSave, false, System.Text.Encoding.Default))
                        sw.WriteLine("Неправильная структура файла. Количество разделов (структурных элементов) недостаточно.");
                }
                else if (countSection >= 5)
                {
                    if (text.IndexOf("ВВЕДЕНИЕ") > text.IndexOf("ОСНОВНАЯ ЧАСТЬ") ||
                        text.IndexOf("ВВЕДЕНИЕ") > text.IndexOf("ЗАКЛЮЧЕНИЕ") ||
                        text.IndexOf("ОСНОВНАЯ ЧАСТЬ") > text.IndexOf("ЗАКЛЮЧЕНИЕ"))
                    {
                        using (StreamWriter sw = new StreamWriter(pathSave, false, System.Text.Encoding.Default))
                            sw.WriteLine("Неправильная структура файла. Порядок разделов неверен.");
                    }
                    else
                    {
                        using (StreamWriter sw = new StreamWriter(pathSave, false, System.Text.Encoding.Default))
                            sw.WriteLine("Cтруктура файла верна.");
                        // Далее идёт проверка стилей оформления
                        for (int i = 0; i < countParagraph; i++)
                        {
                            if (fontSize.ElementAt(i) != 14)
                            {
                                using (StreamWriter sw = new StreamWriter(pathSave, false, System.Text.Encoding.Default))
                                    sw.WriteLine("В " + i + " абзаце неправильный размер шрифта");
                            }
                            if (fontName.ElementAt(i).Equals("Times New Roman"))
                            {
                                tmp = 1;
                            }
                            else
                            {
                                using (StreamWriter sw = new StreamWriter(pathSave, false, System.Text.Encoding.Default))
                                    sw.WriteLine("В " + i + " абзаце неправильный шрифт");
                            }
                        }
                    }
                }

                SaveAsFile(pathSave, type);
            }
            else if (action == "Report")
            {
                pathSave = System.IO.Path.Combine(Server.MapPath("~/FilesChecks/"), "answerReport");
                foreach (var item in text)
                {
                    index = text.IndexOf(item);
                    if (item.Contains("МИНИСТЕРСТВО ОБРАЗОВАНИЯ И НАУКИ РОССИЙСКОЙ ФЕДЕРАЦИИ"))
                    {
                        hat = "МИНИСТЕРСТВО ОБРАЗОВАНИЯ И НАУКИ РОССИЙСКОЙ ФЕДЕРАЦИИ ";
                        if (fontName[index] != "Times New Roman")
                        {
                            answer.Add("Строка " + index + " имеет неправильный шрифт.");
                        }
                        if (fontSize[index] != 10)
                        {
                            answer.Add("Строка " + index + " имеет неправильный размер шрифта.");
                        }
                    }
                    if (item.Contains("ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ"))
                    {
                        hat = string.Concat(hat, "ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ ");
                        if (fontName[index] != "Times New Roman")
                        {
                            answer.Add("Строка " + index + " имеет неправильный шрифт.");
                        }
                        if (fontSize[index] != 10)
                        {
                            answer.Add("Строка " + index + " имеет неправильный размер шрифта.");
                        }
                    }
                    if (item.Contains("«МОСКОВСКИЙ АВИАЦИОННЫЙ ИНСТИТУТ"))
                    {
                        hat = string.Concat(hat, "«МОСКОВСКИЙ АВИАЦИОННЫЙ ИНСТИТУТ ");
                        if (fontName[index] != "Times New Roman")
                        {
                            answer.Add("Строка " + index + " имеет неправильный шрифт.");
                        }
                        if (fontSize[index] != 10)
                        {
                            answer.Add("Строка " + index + " имеет неправильный размер шрифта.");
                        }
                    }
                    if (item.Contains("(национальный исследовательский университет)»"))
                    {
                        hat = string.Concat(hat, "(национальный исследовательский университет)»");
                        if (fontName[index] != "Times New Roman")
                        {
                            answer.Add("Строкаимеет неправильный шрифт.");
                        }
                        if (fontSize[index] != 10)
                        {
                            answer.Add("Строка" + index + "имеет неправильный размер шрифта.");
                        }
                        if (inscription[index] != 0)
                        {
                            answer.Add("Строка" + index + "имеет неправильное начертание.");
                        }
                    }
                    //if (item.Contains("МИНИСТЕРСТВО ОБРАЗОВАНИЯ И НАУКИ РОССИЙСКОЙ ФЕДЕРАЦИИ ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ"))
                    //{
                    //    hat = "МИНИСТЕРСТВО ОБРАЗОВАНИЯ И НАУКИ РОССИЙСКОЙ ФЕДЕРАЦИИ ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ";
                    //}
                    if (item.Contains("студента"))
                    {
                        countSection++;
                    }
                    if (item.Contains("Институт"))
                    {
                        countSection++;
                    }
                    if (item.Contains("Кафедра"))
                    {
                        countSection++;
                    }
                    if (item.Contains("Группа"))
                    {
                        countSection++;
                    }
                    if (item.Contains("Направление подготовки"))
                    {
                        countSection++;
                    }
                    if (item.Contains("Квалификация"))
                    {
                        countSection++;
                    }
                    if (item.Contains("Наименование темы"))
                    {
                        countSection++;
                    }
                    if (item.Contains("Рецензент"))
                    {
                        countSection++;
                    }
                    if (item.StartsWith("Отмеченные достоинства"))
                    {
                        countSection++;
                    }
                    if (item.StartsWith("Отмеченные недостатки"))
                    {
                        countSection++;
                    }
                    if (item.StartsWith("Заключение"))
                    {
                        countSection++;
                    }
                }
                if (hat != "МИНИСТЕРСТВО ОБРАЗОВАНИЯ И НАУКИ РОССИЙСКОЙ ФЕДЕРАЦИИ ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ «МОСКОВСКИЙ АВИАЦИОННЫЙ ИНСТИТУТ (национальный исследовательский университет)»")
                {
                    using (StreamWriter sw1 = new StreamWriter(pathSave, false, System.Text.Encoding.Default))
                        sw1.WriteLine("Шапка в рецензии неверна.");
                }
                else if (countSection < 10)
                {
                    using (StreamWriter sw1 = new StreamWriter(pathSave, false, System.Text.Encoding.Default))
                        sw1.WriteLine("Количество граф недостаточно. (Графы: институт, кафедра, отмеченные достоинства и так далее).");
                }
                else if (answer.Count > 0)
                {
                    foreach (var item in answer)
                    {
                        using (StreamWriter sw1 = new StreamWriter(pathSave, false, System.Text.Encoding.Default))
                            sw1.WriteLine(item);
                    }
                }
                else
                {
                    using (StreamWriter sw1 = new StreamWriter(pathSave, false, System.Text.Encoding.Default))
                        sw1.WriteLine("Cтруктура верна.");
                }
            }
            wordDoc.Close();
            wordApp.Quit();
            SaveAsFile(pathSave, type);
        }
Exemplo n.º 24
0
        public static void AutomateWord()
        {
            object missing = Type.Missing;
            object notTrue = false;

            Word.Application oWord    = null;
            Word.Documents   oDocs    = null;
            Word.Document    oDoc     = null;
            Word.Paragraphs  oParas   = null;
            Word.Paragraph   oPara    = null;
            Word.Range       oParaRng = null;
            Word.Font        oFont    = null;

            try
            {
                // 创建一个Microsoft Word实例并令其不可见

                oWord         = new Word.Application();
                oWord.Visible = false;
                Console.WriteLine("Word.Application is started");

                // 创建一个新的文档

                oDocs = oWord.Documents;
                oDoc  = oDocs.Add(ref missing, ref missing, ref missing, ref missing);
                Console.WriteLine("A new document is created");

                // 插入段落

                Console.WriteLine("Insert a paragraph");

                oParas        = oDoc.Paragraphs;
                oPara         = oParas.Add(ref missing);
                oParaRng      = oPara.Range;
                oParaRng.Text = "Heading 1";
                oFont         = oParaRng.Font;
                oFont.Bold    = 1;
                oParaRng.InsertParagraphAfter();

                // 将文档保存为.docx文件并关闭

                Console.WriteLine("Save and close the document");

                object fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.docx";
                object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument;
                oDoc.SaveAs(ref fileName, ref fileFormat, 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);
                ((Word._Document)oDoc).Close(ref missing, ref missing,
                                             ref missing);

                // 退出Word应用程序

                Console.WriteLine("Quit the Word application");
                ((Word._Application)oWord).Quit(ref notTrue, ref missing,
                                                ref missing);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution1.AutomateWord throws the error: {0}",
                                  ex.Message);
            }
            finally
            {
                // 通过在所有访问对象上显示调用Marshal.FinalReleaseComObject方法
                // 释放非托管Word COM资源
                // 见 http://support.microsoft.com/kb/317109.

                if (oFont != null)
                {
                    Marshal.FinalReleaseComObject(oFont);
                    oFont = null;
                }
                if (oParaRng != null)
                {
                    Marshal.FinalReleaseComObject(oParaRng);
                    oParaRng = null;
                }
                if (oPara != null)
                {
                    Marshal.FinalReleaseComObject(oPara);
                    oPara = null;
                }
                if (oParas != null)
                {
                    Marshal.FinalReleaseComObject(oParas);
                    oParas = null;
                }
                if (oDoc != null)
                {
                    Marshal.FinalReleaseComObject(oDoc);
                    oDoc = null;
                }
                if (oDocs != null)
                {
                    Marshal.FinalReleaseComObject(oDocs);
                    oDocs = null;
                }
                if (oWord != null)
                {
                    Marshal.FinalReleaseComObject(oWord);
                    oWord = null;
                }
            }
        }
        /// <summary>
        /// Метод сортировки списка литературы
        /// </summary>
        /// <param name="path">Путь к проверяемому файлу</param>
        protected void ParsingFile(string path)
        {
            var    pathSave = System.IO.Path.Combine(Server.MapPath("~/FilesLibrary/"), "answerReport");
            var    tempPathSave = @"D:\Документы\Диплом магистра\Verification\VerificationDocs.WebUI\FilesLibrary\Ответ.docx";
            int    countParagraph, countLibrary;
            string type     = "docx";
            string temptype = "txt";
            var    index    = 0;

            DocumentStructure document = new DocumentStructure();
            //запускаем Word
            var wordApp = new word.Application();
            var wordDoc = wordApp.Documents.Open(path);

            // Показывает открытый файл пользователю
            wordApp.Visible = true;

            wordparagraphs = wordDoc.Paragraphs;
            countParagraph = wordDoc.Paragraphs.Count;
            word.Range[]             Range      = new word.Range[countParagraph];
            string[]                 text       = new string[countParagraph];
            List <string>            libr       = new List <string>();
            List <int>               librLink   = new List <int>();
            Dictionary <string, int> listLibPar = new Dictionary <string, int>();
            Dictionary <string, int> TempLib    = new Dictionary <string, int>();

            // https://coderoad.ru/4016960/C-%D0%BF%D0%BE%D0%B8%D1%81%D0%BA-%D1%82%D0%B5%D0%BA%D1%81%D1%82%D0%B0-%D0%B2-Word-%D0%B8-%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B4%D0%B8%D0%B0%D0%BF%D0%B0%D0%B7%D0%BE%D0%BD%D0%B0-%D1%80%D0%B5%D0%B7%D1%83%D0%BB%D1%8C%D1%82%D0%B0%D1%82%D0%B0
            // https://coderoad.ru/11778013/%D0%9A%D0%B0%D0%BA-%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C-%D0%BD%D0%BE%D0%BC%D0%B5%D1%80-%D0%B0%D0%B1%D0%B7%D0%B0%D1%86%D0%B0-%D0%B2-%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D0%B5-word-%D1%81-C
            string title = "СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ";

            for (int i = 1; i < countParagraph; i++)
            {
                //styleHead = wordDoc.Paragraphs[i].Range.ParagraphStyle();
                string WordS = ((word.Style)wordDoc.Paragraphs[i].get_Style()).NameLocal;

                text[i] = wordDoc.Paragraphs[i].Range.Text;

                Range[i] = wordDoc.Paragraphs[i].Range;
                Range[i].Select();
                // Находим начало списка литературы
                if (WordS == "Заголовок" && Range[i].Text.Trim() == title)
                {
                    index = i + 1;
                }
            }
            wordApp.Selection.Start = index;
            wordApp.Selection.End   = countParagraph - 1;

            // Удаляем старый список литературы
            for (int i = wordDoc.Paragraphs.Count; i >= wordApp.Selection.Start; i--)
            {
                wordDoc.Paragraphs[i].Range.Delete();
            }

            var ind = 0;

            for (int i = index; i <= wordApp.Selection.End; i++)
            {
                listLibPar.Add(text[i].Trim(), ind);
                ind++;
            }

            // Сортируем словарь со списком литературы
            var sortedDict = new SortedDictionary <string, int>(listLibPar);

            foreach (var kvp in sortedDict)
            {
                TempLib.Add(kvp.Key, kvp.Value);
            }

            //SearchLinkOnLibrInText(text, librLink, TempLib);

            // Вставляем новый нумерованный список в документ (с отсортированным списком литературы)
            int j   = wordApp.Selection.Start;
            var num = 0;

            wordDoc.Paragraphs.Add();
            wordDoc.Paragraphs[j].Range.ListFormat.ApplyNumberDefault(word.WdListType.wdListListNumOnly); // если уже есть список, то нумерация удаляется
            foreach (var item in TempLib)
            {
                wordDoc.Paragraphs.Add();
                wordDoc.Paragraphs[j].Range.Text      = item.Key;
                wordDoc.Paragraphs[j].Range.Font.Name = "Times New Roman";
                wordDoc.Paragraphs[j].Range.Font.Size = 14;
                wordDoc.Paragraphs[j].Space15();
                wordDoc.Paragraphs[j].Range.SetListLevel(1);
                j++;
            }

            wordDoc.Save();
            wordDoc.Close();
            wordApp.Quit();
            SaveAsFile(path, type);
        }
Exemplo n.º 26
0
        string paraFullText;   //段落下文本内容

        public string Fill(ArrayList pathWord, System.Windows.Forms.RichTextBox richTextBoxTest)
        {
            Word.Application app = new Microsoft.Office.Interop.Word.Application(); //可以打开word程序,程序是Application
            Word.Document    doc = null;                                            //一会要记录word打开的文档,打开word文档和word程序不是一回事,文档是document
            //设置打开文档参数
            Object confirmConversions    = Type.Missing;
            Object readOnly              = Type.Missing;
            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;

            //匹配关键字正则表达式
            ArrayList keywordsList = new ArrayList();

            keywordsList.Add(new Regex("(^([\\s]*)摘([\\s]*)要([\\s]*))"));  //正则表达式——摘要
            keywordsList.Add(new Regex("(^([\\s]*)abstract)"));            //正则表达式——摘要
            keywordsList.Add(new Regex("(^([\\s]*)关([\\s]*)键([\\s]*)字)")); //正则表达式——关键字
            keywordsList.Add(new Regex("(^([\\s]*)关([\\s]*)键([\\s]*)词)")); //正则表达式——关键词
            keywordsList.Add(new Regex("(^([\\s]*)key([\\s]*)words)"));    //正则表达式——关键词
            keywordsList.Add(new Regex("^([\\s]*)图([\\s]*)([0-9]*)"));     //正则表达式——图题
            keywordsList.Add(new Regex("^([\\s]*)表([\\s]*)([0-9]*)"));     //正则表达式——表题
            //匹配编号正则表达式
            ArrayList listFormatList = new ArrayList();

            //公式编号
            listFormatList.Add(new Regex("(\\((\\d+(.\\d+)?)\\)([\\s]*)$)"));
            listFormatList.Add(new Regex("(\\((\\d+(.\\d+)?)\\)([\\s]*)$)"));
            //列表编号
            listFormatList.Add(new Regex("(^\\((\\d+)\\))"));
            listFormatList.Add(new Regex("(^\\((\\d+)\\))"));
            listFormatList.Add(new Regex("(^\\d+\\))"));
            listFormatList.Add(new Regex("(^\\d+\\))"));
            //标题编号
            listFormatList.Add(new Regex("(^\\d+(\\.\\d+)*)"));
            listFormatList.Add(new Regex("(^第([\u4e00-\u9fa5]+)章)"));

            for (int pathWord_i = 0; pathWord_i < pathWord.Count; pathWord_i++)//逐个打开文件夹下文档
            {
                string directoryName = System.IO.Path.GetDirectoryName(pathWord[pathWord_i].ToString());
                directoryName = directoryName.Substring(0, directoryName.LastIndexOf("\\"));
                string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(pathWord[pathWord_i].ToString());
                //string testDir = directoryName + "\\extractFromWordTxt\\" + fileNameWithoutExtension + ".txt";
                string       testDir = @"E:\Users\zhangzhen\PycharmProjects\document\docreconstruct2\data\test.txt";
                StreamWriter sw      = new StreamWriter(testDir);//将控制台输出写入txt文件
                Console.SetOut(sw);
                Console.WriteLine("等号\t关键字\t字体\t字号\t字形\t字数\t编号\t编号位置\tword对象\t行距\t缩进\t段前距\t段后距\t对齐方式\t大纲级别\t标点\t中文比例\t邮箱符号");
                //打开word文档
                object openPathWord = pathWord[pathWord_i];
                doc = app.Documents.Open(ref openPathWord, 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.Paragraphs paragraphs = doc.Paragraphs;                                                                          //获得段落集合
                Dictionary <string, Dictionary <float, int> > relativeFontSize = new Dictionary <string, Dictionary <float, int> >(); //相对字号
                //初始化特征
                initCharacter();
                //删除所有批注
                add_table_Comment(doc);
                richTextBoxTest.AppendText("特征提取开始" + "\n");
                int pCount = paragraphs.Count;
                int para_i = 1;
                for (; para_i <= paragraphs.Count; para_i++)
                {
                    richTextBoxTest.AppendText("第" + para_i + "/" + pCount + "段" + "\n");
                    Word.Paragraph para = paragraphs[para_i];
                    if (para.Range.Text.Trim() != "")
                    {
                        if (para.Range.Tables.Count == 0)
                        {
                            writeToTxt(para.Range, para, keywordsList, listFormatList, richTextBoxTest);
                        }
                        else
                        {
                            //   // int para_num_table = para.Range.Comments[1].Scope.Paragraphs.Count;
                            while (paragraphs[para_i].Range.Comments.Count != 1)
                            {
                                para_i++;
                            }
                            writeToTxt(paragraphs[para_i].Range.Comments[1].Scope, para, keywordsList, listFormatList, richTextBoxTest);
                            while (paragraphs[para_i].Range.Tables.Count != 0)
                            {
                                para_i++;
                            }
                            para_i--;

                            //只处理第一段 其它都略过
                        }
                    }
                }
                for (int numAtt = 0; numAtt < 17; numAtt++)
                {
                    Console.Write("-" + "\t");
                }
                Console.Write("-");
                //先关闭打开的文档(注意saveChanges选项)
                Object saveChanges    = Word.WdSaveOptions.wdSaveChanges;
                Object originalFormat = Type.Missing;
                Object routeDocument  = Type.Missing;
                app.Documents.Close(ref saveChanges, ref originalFormat, ref routeDocument);
                sw.Flush();
                sw.Close();
            }

            //若已经没有文档存在,则关闭应用程序
            if (app.Documents.Count == 0)
            {
                app.Quit(Type.Missing, Type.Missing, Type.Missing);
            }

            return("测试文件特征提取完成");
        }
Exemplo n.º 27
0
        //将段落角色添加到段落中
        public void FillParaId(ArrayList pathWord)
        {
            Word.Application app = new Microsoft.Office.Interop.Word.Application(); //可以打开word程序,程序是Application
            Word.Document    doc = null;                                            //一会要记录word打开的文档,打开word文档和word程序不是一回事,文档是document
            //设置打开文档参数
            Object confirmConversions    = Type.Missing;
            Object readOnly              = Type.Missing;
            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;
            string fullPath             = @"E:\Users\zhangzhen\PycharmProjects\document\docreconstruct2\data\result.csv";

            StreamReader  reader     = new StreamReader(fullPath);
            string        line       = "";
            List <string> listStrArr = new List <string>(); //数组List,相当于可以无限扩大的二维数组。

            line = reader.ReadLine();                       //读取一行数据
            while (line != null)
            {
                listStrArr.Add(line);//将文件内容分割成数组
                line = reader.ReadLine();
            }


            for (int pathWord_i = 0; pathWord_i < pathWord.Count; pathWord_i++)//逐个打开文件夹下文档
            {
                string directoryName = System.IO.Path.GetDirectoryName(pathWord[pathWord_i].ToString());
                directoryName = directoryName.Substring(0, directoryName.LastIndexOf("\\"));
                string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(pathWord[pathWord_i].ToString());
                //打开word文档
                object openPathWord = pathWord[pathWord_i];
                doc = app.Documents.Open(ref openPathWord, 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);
                //特殊处理表格,先直接判断 添加表格批注
                app.Visible = true;

                add_table_Comment(doc);
                Word.Paragraphs paragraphs = doc.Paragraphs;  //获得段落集合
                for (int i = 1, j = 0; i <= paragraphs.Count; i++)
                {
                    if (paragraphs[i].Range.Text.Trim() != "")
                    {
                        if (i <= listStrArr.Count && paragraphs[i].Range.Tables.Count == 0)
                        {
                            if (listStrArr[j] == "表格")
                            {
                                j++;
                            }
                            Word.Range range = paragraphs[i].Range;
                            splitLabel(listStrArr[j++], range);
                        }
                    }
                }
                Object saveChanges    = Word.WdSaveOptions.wdSaveChanges;
                Object originalFormat = Type.Missing;
                Object routeDocument  = Type.Missing;
                doc.Save();
            }
        }
Exemplo n.º 28
0
        private void TitlePage(String beginDate, String endDate, Teacher teacher)
        {
            Word.Paragraphs wordparagraphs = adoc.Paragraphs;

            adoc.Paragraphs.Add();
            wordparagraphs[1].Range.Text           = "Форма № 12";
            wordparagraphs[1].Range.Bold           = 0;
            wordparagraphs[1].Range.Font.Size      = 8;
            wordparagraphs[1].Range.Font.Name      = "Times New Roman";
            wordparagraphs[1].Range.Font.Underline = 0;
            wordparagraphs[1].Alignment            = Word.WdParagraphAlignment.wdAlignParagraphRight;
            adoc.Paragraphs.Add();

            adoc.Paragraphs.Add();
            wordparagraphs[2].Range.Text           = "ЗАПОРІЗЬКИЙ НАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ";
            wordparagraphs[2].Range.Bold           = 1;
            wordparagraphs[2].Range.Font.Size      = 14;
            wordparagraphs[2].Range.Font.Name      = "Times New Roman";
            wordparagraphs[2].Range.Font.Underline = 0;
            wordparagraphs[2].Alignment            = Word.WdParagraphAlignment.wdAlignParagraphCenter;

            adoc.Paragraphs.Add();
            wordparagraphs[3].Range.Text           = "Інститут, факультет: " + teacher.institute + ", " + teacher.faculty;
            wordparagraphs[3].Range.Bold           = 1;
            wordparagraphs[3].Range.Font.Size      = (float)12.5;
            wordparagraphs[3].Range.Font.Name      = "Times New Roman";
            wordparagraphs[3].Range.Font.Underline = 0;
            wordparagraphs[3].Alignment            = Word.WdParagraphAlignment.wdAlignParagraphCenter;

            adoc.Paragraphs.Add();
            adoc.Paragraphs.Add();
            adoc.Paragraphs.Add();
            adoc.Paragraphs.Add();
            adoc.Paragraphs.Add();

            adoc.Paragraphs.Add();
            wordparagraphs[9].Range.Text           = "ЖУРНАЛ ОБЛІКУ РОБОТИ ВИКЛАДАЧА";
            wordparagraphs[9].Range.Bold           = 0;
            wordparagraphs[9].Range.Font.Name      = "Times New Roman";
            wordparagraphs[9].Range.Font.Size      = 34;
            wordparagraphs[9].Range.Font.Underline = 0;
            wordparagraphs[9].Alignment            = Word.WdParagraphAlignment.wdAlignParagraphCenter;

            adoc.Paragraphs.Add();
            wordparagraphs[10].Range.Text           = "на " + beginDate + " - " + endDate + " навчальний рік";
            wordparagraphs[10].Range.Bold           = 0;
            wordparagraphs[10].Range.Font.Name      = "Times New Roman";
            wordparagraphs[10].Range.Font.Size      = (float)24.5;
            wordparagraphs[10].Range.Font.Underline = 0;
            wordparagraphs[10].Alignment            = Word.WdParagraphAlignment.wdAlignParagraphCenter;

            adoc.Paragraphs.Add();
            adoc.Paragraphs.Add();
            adoc.Paragraphs.Add();
            adoc.Paragraphs.Add();
            adoc.Paragraphs.Add();

            adoc.Paragraphs.Add();
            wordparagraphs[16].Range.Text           = "1. Кафедра__________________________" + teacher.department + "";
            wordparagraphs[16].Range.Bold           = 0;
            wordparagraphs[16].Range.Font.Name      = "Times New Roman";
            wordparagraphs[16].Range.Font.Size      = 18;
            wordparagraphs[16].Range.Font.Underline = 0;
            wordparagraphs[16].Alignment            = Word.WdParagraphAlignment.wdAlignParagraphLeft;

            adoc.Paragraphs.Add();
            wordparagraphs[17].Range.Text           = "2. Прізвище, ім'я, по батькові__________" + teacher.fullName;
            wordparagraphs[17].Range.Bold           = 0;
            wordparagraphs[17].Range.Font.Name      = "Times New Roman";
            wordparagraphs[17].Range.Font.Size      = 18;
            wordparagraphs[17].Range.Font.Underline = 0;
            wordparagraphs[17].Alignment            = Word.WdParagraphAlignment.wdAlignParagraphLeft;

            adoc.Paragraphs.Add();
            wordparagraphs[18].Range.Text           = "3. Вчене звання, науковий ступінь______" + teacher.academicRank;
            wordparagraphs[18].Range.Bold           = 0;
            wordparagraphs[18].Range.Font.Name      = "Times New Roman";
            wordparagraphs[18].Range.Font.Size      = 18;
            wordparagraphs[18].Range.Font.Underline = 0;
            wordparagraphs[18].Alignment            = Word.WdParagraphAlignment.wdAlignParagraphLeft;

            adoc.Paragraphs.Add();
            wordparagraphs[19].Range.Text           = "4. Посада___________________________" + teacher.post;
            wordparagraphs[19].Range.Bold           = 0;
            wordparagraphs[19].Range.Font.Name      = "Times New Roman";
            wordparagraphs[19].Range.Font.Size      = 18;
            wordparagraphs[19].Range.Font.Underline = 0;
            wordparagraphs[19].Alignment            = Word.WdParagraphAlignment.wdAlignParagraphLeft;


            rangeEndOfFile = adoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            rangeEndOfFile.InsertBreak(Word.WdBreakType.wdSectionBreakNextPage);
        }