Esempio n. 1
0
        /// <summary>
        /// Open a new word document.
        /// </summary>
        /// <param name="readOnly">open as readonly or not</param>
        public void WordOpenNewDocument(bool readOnly = false)
        {
            this.WordDocuments = WordApp.Documents;
            this.WordDocument  = WordDocuments.Add();

            // Create styles
            WordStyleName       = WordDocument.Styles.Add("Namn");
            WordStyleNormalText = WordDocument.Styles.Add("Normal Text");
            WordStyleItalicText = WordDocument.Styles.Add("Italic Text");

            WordStyleName.Font.Underline            = Word.WdUnderline.wdUnderlineSingle;
            WordStyleName.Font.Size                 = 12;
            WordStyleName.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            WordStyleName.Font.Italic               = 0;
            WordStyleName.Font.Name                 = "Lucida Calligraphy";

            WordStyleNormalText.Font.Underline            = Word.WdUnderline.wdUnderlineNone;
            WordStyleNormalText.Font.Size                 = 12;
            WordStyleNormalText.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            WordStyleNormalText.Font.Italic               = 0;
            WordStyleNormalText.Font.Name                 = "Calibri";

            WordStyleItalicText.Font.Underline            = Word.WdUnderline.wdUnderlineNone;
            WordStyleItalicText.Font.Size                 = 12;
            WordStyleItalicText.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            WordStyleItalicText.Font.Italic               = 1;
            WordStyleItalicText.Font.Name                 = "Calibri";
        }
Esempio n. 2
0
        private void Pregunta28()
        {
            p1 = "INCORRECTO";

            int start = docAlumno.Content.Text.IndexOf("Todos los fractales tienen algo en común") - 15;
            int end   = docAlumno.Content.Text.IndexOf("Todos los fractales tienen algo en común") + 25;

            if (start >= 0)
            {
                Word.Range range = docAlumno.Range(Start: start, End: end);

                Word.Style estilo = range.Paragraphs.get_Style();

                string tipo            = estilo.NameLocal; //"Cita"
                string cadenaAchequear = "Cita";

                if (tipo.Contains(cadenaAchequear))
                {
                    p1 = "CORRECTO";
                }
            }

            GuardarPuntaje();
            CerrarWords();

            BorrarPreguntasTemporales();
        }
Esempio n. 3
0
        public void ImportPDF(string path)
        {
            WordOM.Style s = _document.Styles["normal"];
// ReSharper disable UseIndexedProperty
            _document.Application.Selection.set_Style(s);
// ReSharper restore UseIndexedProperty
            _document.Application.Selection.InlineShapes.AddOLEObject("AcroExch.Document.7", path, false, false);
        }
Esempio n. 4
0
        private void CreateCustomerStyle()
        {
            var doc = Globals.ThisAddIn.Application.ActiveDocument;

            doc.Styles.Add("我的样式", Word.WdStyleType.wdStyleTypeParagraph);
            Word.Style myStyle = doc.Styles["我的样式"];
            myStyle.AutomaticallyUpdate       = true;
            myStyle.Font.Name                 = "楷体";
            myStyle.Font.Size                 = 22;
            myStyle.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
        }
Esempio n. 5
0
        public void IndentHeading(int indent)
        {
            bool hasIndex = false;

            // 删除目录
            if (doc.TablesOfContents.Count > 0 && doc.TablesOfContents[1] != null)
            {
                doc.TablesOfContents[1].Delete();
                hasIndex = true;;
            }

            foreach (Microsoft.Office.Interop.Word.Paragraph paragraph in doc.Paragraphs)
            {
                Microsoft.Office.Interop.Word.Style style = paragraph.get_Style() as Microsoft.Office.Interop.Word.Style;
                string styleName = style.NameLocal.ToString();

                int i = styleName.IndexOf(",");
                if (i != -1)
                {
                    styleName = styleName.Substring(0, i);
                }
                if (styleName.IndexOf("标题") != -1)
                {
                    int num = 0;
                    try
                    {
                        string level = styleName.Split(' ')[1];
                        num = int.Parse(level);
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message);
                        continue;
                    }
                    // Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleHeading1 = -2;
                    // 其它请看 WdBuiltinStyle 枚举类型,依此得出heading样式值
                    object heading = (object)((-1 - num) - indent);
                    paragraph.set_Style(ref heading);
                }
                else if (hasIndex)
                {
                    string text  = paragraph.Range.Text;
                    string regex = "\\s*目\\s*录\\s*";

                    if (Regex.IsMatch(text, regex))
                    {
                        paragraph.Range.Text = "";
                        hasIndex             = false;
                    }
                }
            }
        }
        private string NameLocal;      //название стиля

        public CheckedStyle(Word.Style style)
        {
            //IsChecked = false;
            FontName        = style.Font.NameAscii;
            FontSize        = style.Font.Size;
            FontColor       = style.Font.TextColor.RGB;
            FontBold        = style.Font.Bold;
            FontItalic      = style.Font.Italic;
            Alignment       = style.ParagraphFormat.Alignment.ToString();
            LineSpacing     = style.ParagraphFormat.LineSpacing;
            SpaceBefore     = style.ParagraphFormat.SpaceBefore;
            SpaceAfter      = style.ParagraphFormat.SpaceAfter;
            FirstLineIndent = style.ParagraphFormat.FirstLineIndent;
            NameLocal       = style.NameLocal;
        }
Esempio n. 7
0
        public static MSWord.Style CreateTableStyle(ref MSWord.Document wdDoc)
        {
            MSWord.WdBorderType verticalBorder = MSWord.WdBorderType.wdBorderVertical;
            MSWord.WdBorderType leftBorder     = MSWord.WdBorderType.wdBorderLeft;
            MSWord.WdBorderType rightBorder    = MSWord.WdBorderType.wdBorderRight;
            MSWord.WdBorderType topBorder      = MSWord.WdBorderType.wdBorderTop;

            MSWord.WdLineStyle doubleBorder = MSWord.WdLineStyle.wdLineStyleDouble;
            MSWord.WdLineStyle singleBorder = MSWord.WdLineStyle.wdLineStyleSingle;

            MSWord.WdTextureIndex noTexture = MSWord.WdTextureIndex.wdTextureNone;
            MSWord.WdColor        gray10    = MSWord.WdColor.wdColorGray10;
            MSWord.WdColor        gray70    = MSWord.WdColor.wdColorGray70;
            MSWord.WdColorIndex   white     = MSWord.WdColorIndex.wdWhite;

            object styleTypeTable = MSWord.WdStyleType.wdStyleTypeTable;

            MSWord.Style styl = wdDoc.Styles.Add("New Table Style", ref styleTypeTable);

            styl.Font.Name            = "Arial";
            styl.Font.Size            = 11;
            styl.Table.Borders.Enable = 1;

            MSWord.ConditionalStyle evenRowBanding = styl.Table.Condition(MSWord.WdConditionCode.wdEvenRowBanding);
            evenRowBanding.Shading.Texture = noTexture;
            evenRowBanding.Shading.BackgroundPatternColor = gray10;
            // Borders have to be set specifically for every condition.
            evenRowBanding.Borders[leftBorder].LineStyle     = doubleBorder;
            evenRowBanding.Borders[rightBorder].LineStyle    = doubleBorder;
            evenRowBanding.Borders[verticalBorder].LineStyle = singleBorder;

            MSWord.ConditionalStyle firstRow = styl.Table.Condition(MSWord.WdConditionCode.wdFirstRow);
            firstRow.Shading.BackgroundPatternColor = gray70;
            firstRow.Borders[leftBorder].LineStyle  = doubleBorder;
            firstRow.Borders[topBorder].LineStyle   = doubleBorder;
            firstRow.Borders[rightBorder].LineStyle = doubleBorder;
            firstRow.Font.Size       = 14;
            firstRow.Font.ColorIndex = white;
            firstRow.Font.Bold       = 1;

            // Set the number of rows to include in a "band".
            styl.Table.RowStripe = 1;
            return(styl);
        }
Esempio n. 8
0
        private void BookmarkInsertCrossReference()
        {
            Word.Document    doc = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Application app = Globals.ThisAddIn.Application;

            int i = 0;

            ArrayList refsToSave = new ArrayList();

            foreach (Word.Paragraph paragraph in doc.Paragraphs)
            {
                Word.Style style     = paragraph.get_Style() as Word.Style;
                string     styleName = style.NameLocal;

                if (styleName == "Heading 1,2016_Überschrift 1,Headline 1")
                {
                    i++;
                }
                else if (styleName == "Heading 2,2016_Überschrift 2,Headline 2")
                {
                    i++;
                }
                else if (styleName == "Heading 3,2016_Überschrift 3,Headline 3")
                {
                    i++;
                    refsToSave.Add(i);
                }
            }

            Word.Table table = FindTable("Report Name");

            foreach (int j in refsToSave)
            {
                table.Rows.Add();

                table.Cell(table.Rows.Count, 1).Range.Select();
                insertCrossReference(app, Word.WdReferenceKind.wdContentText, j);

                //table.Cell(table.Rows.Count, 4).Range.Select();
                //table.Cell(table.Rows.Count, 4).Range.Delete();
                //insertCrossReference(app, Word.WdReferenceKind.wdPageNumber, j);
            }
        }
Esempio n. 9
0
        public static void CreateWordDocTable(string[] qheader, string[][] qdata)
        {
            var application = new MSWord.Application();
            var document    = new MSWord.Document();

            //object missing = System.Reflection.Missing.Value;

            application.Visible       = true;
            application.DisplayAlerts = MSWord.WdAlertLevel.wdAlertsNone;
            document = application.Documents.Add();
            document.PageSetup.Orientation  = MSWord.WdOrientation.wdOrientLandscape;
            document.PageSetup.LeftMargin   = 20;
            document.PageSetup.RightMargin  = 20;
            document.PageSetup.TopMargin    = 20;
            document.PageSetup.BottomMargin = 20;
            document.PageSetup.PageWidth    = qheader.Length * 100 + 200 + 40;

            MSWord.Table qtable = document.Tables.Add(document.Range(), qdata.Length + 1, qheader.Length);
            MSWord.Style styl   = CreateTableStyle(ref document);
            qtable.Range.set_Style(styl);
            qtable.Borders[MSWord.WdBorderType.wdBorderBottom].LineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
            qtable.Columns.Width    = 100;
            qtable.Columns[1].Width = 300;

            for (int i = 0; i < qheader.Length; i++)
            {
                qtable.Cell(1, i + 1).Range.Text = qheader[i];
            }

            for (int j = 0; j < qdata.Length; j++)
            {
                //int level = Int16.Parse(qdata[j][0]);
                //qtable.Cell(j + 2, 1).Range.

                for (int i = 0; i < qheader.Length; i++)
                {
                    qtable.Cell(j + 2, i + 1).Range.Text = qdata[j][i];
                }
            }

            Marshal.ReleaseComObject(document);
            Marshal.ReleaseComObject(application);
        }
Esempio n. 10
0
        private void FormatNormalParagraphs(string DocToFormat)
        {
            var application = new Word.Application();

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

            int PCount = document.Content.Paragraphs.Count;

            if (PCount > 0)
            {
                for (int i = 1; i < document.Content.Paragraphs.Count; i++)
                {
                    Word.Paragraph para  = document.Content.Paragraphs[i];
                    Word.Style     style = para.get_Style() as Word.Style;
                    Word.Range     range = para.Range;

                    lblProcessing.Text = "Processing All Paragraphs...";
                    //document.RemoveNumbers();

                    if (style.NameLocal == "Normal")
                    {
                        {
                            para.Range.Font.Color = Word.WdColor.wdColorBlack;
                            para.Range.Font.Size  = 11;
                            para.Range.Font.Name  = "Arial";
                            para.Range.Bold       = 0;

                            para.Range.Paragraphs.LeftIndent      = 1;
                            para.Range.Paragraphs.RightIndent     = 0;
                            para.Range.Paragraphs.OutlineLevel    = Word.WdOutlineLevel.wdOutlineLevelBodyText;
                            para.Range.Paragraphs.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphJustify;
                            para.Range.Paragraphs.SpaceAfter      = 10;
                            para.Range.Paragraphs.SpaceBefore     = 0;
                            para.Range.Paragraphs.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
                        }
                    }
                }
            }
            document.Save();
            document.Close();
            application.Quit();
        }
Esempio n. 11
0
        public void ProcStyles(WORD.Style style)
        {
            var targetFont = LocalLang.GetLocFont(style.Font.Name);

            //_SetFontProperty(targetFont, style.Font.Name, style.Font.NameAscii, style.Font.NameOther);

            style.Font.Name      = targetFont;
            style.Font.NameAscii = targetFont;
            style.Font.NameOther = targetFont;

            if (LocalLang.IsFarEast)
            {
                style.Font.NameFarEast = targetFont;
            }

            if (LocalLang.IsRightToLeft)
            {
                style.Font.NameBi = targetFont;
            }
        }
Esempio n. 12
0
        public void TypeText(string text, string style = "")
        {
            _document.Activate();
            if (!String.IsNullOrEmpty(style))
            {
                WordOM.Style s = _document.Styles[style];
                //_document.Application.Selection.InsertStyleSeparator();
// ReSharper disable UseIndexedProperty
                _document.Application.Selection.set_Style(s);
// ReSharper restore UseIndexedProperty
            }

            _document.Application.Selection.TypeText(text);


            //if (!String.IsNullOrEmpty(style))
            //{
            //    //_document.Application.Selection.InsertStyleSeparator();

            //}
        }
        void listBox1_SelectedValueChanged(object sender, System.EventArgs e)
        {
            WrappedStyle ws = listBox1.SelectedItem as WrappedStyle;

            if (ws == null)
            {
                log.Warn("SelectedValueChanged, but IsNullOrEmpty.  Deselction?");
                return;
            }
            else
            {
                object pStyle;
                if (ws == selectedValue)
                {
                    // Fired on something already selected, so deselect
                    listBox1.SelectedIndex = -1;                    // no selection

                    cc.set_DefaultTextStyle(ref styleDefaultPFont); // can't set to null?

                    selectedValue = null;
                    return;
                }

                Word.Style selectedStyle = ws.getStyle();
                pStyle = ws.getStyle();
                // Displayed the paragraph style; use the linked character style
                // (but setting the p style seems to work)
                log.Info("selected " + selectedStyle.NameLocal);
                //object newStyle = (Word.Style)selectedStyle.get_LinkStyle();
                cc.set_DefaultTextStyle(ref pStyle); // I wonder whether we can use the p style?

                selectedValue = ws;                  //for next time

                // Now, select cc, and apply p style, so user see visible result
                // (only need to do that if you set c style (as opposed to p)
                // But it only applies the style to the first paragraph, so:
                cc.Range.set_Style(ref pStyle);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Adds a paragraph to the document with the specified text
        /// </summary>
        /// <param name="text">The string to add</param>
        /// <param name="style">normal, italic or name</param>
        public void WordAddText(string text, string style = "normal")
        {
            Word.Style st = null;
            if (style == "normal")
            {
                st = this.WordStyleNormalText;
            }
            else if (style == "italic")
            {
                st = this.WordStyleItalicText;
            }
            else if (style == "name")
            {
                st = this.WordStyleName;
            }

            // Word.Paragraph p = WordDocument.Words.Last.Paragraphs.Add();
            Word.Paragraph p = WordDocument.Paragraphs.Add();

            p.Range.Text = text;
            p.Range.set_Style(st);
            p.Range.InsertParagraphAfter();
        }
Esempio n. 15
0
        private void Pregunta9()
        {
            p1 = "INCORRECTO";
            Word.Tables tablas = docAlumno.Tables;
            if (tablas.Count == 1)
            {
                Word.Style estilo = tablas[1].get_Style();

                //Claves del éxito
                string cadenaAchequear    = "Tabla de cuadrícula 2 - Énfasis 4";
                string contenidoDeArchivo = estilo.NameLocal;

                if (contenidoDeArchivo.Equals(cadenaAchequear))
                {
                    p1 = "CORRECTO";
                }
            }

            GuardarPuntaje();
            CerrarWords();

            BorrarPreguntasTemporales();
        }
Esempio n. 16
0
        public static List <String> CheckAndWrite()     //проверка всего документа, исправление, запись примечаний
        {
            List <String> result = new List <string>(); //GetSetStyleFromDoc();

            //var styles = CheckStyles(_path, false); //получаем стили из документа
            //var defaultstyles = CheckStyles(_pathtotemplate, false); //получаем стили из шаблона
            //foreach (Style s in styles.Nodes().)

            //int CountParagraphs;

            OpenWordDocument(_path);
            //Получаем ссылки на параграфы документа
            //wordparagraphs = worddocument.Paragraphs;

            //List<string> SelectedParagraphs = new List<string>();
            for (int i = 1; i < worddocument.Paragraphs.Count; i++)                                //numeration of paragraphs starts from 1
            {
                string     WordP = worddocument.Paragraphs[i].Range.Text;                          // get paragraph text
                Word.Style style = ((Word.Style)worddocument.Paragraphs[i].get_Style());           //get style of paragraph
                string     WordS = ((Word.Style)worddocument.Paragraphs[i].get_Style()).NameLocal; //get paragraph style name

                if (style_names.LastIndexOf(WordS) != -1)                                          //если стиль входит в список эталонных
                {
                    int index = style_names_for_removing.LastIndexOf(WordS);
                    if (index != -1)                                                                //если стиль ещё ни разу не добавлялся в список
                    {
                        word_style_from_document.Add(new CheckedStyle(style));                      //добавляем стиль
                        style_names_for_removing.RemoveAt(style_names_for_removing.IndexOf(WordS)); //удаляем его из списка недобавленных стилей
                    }
                    //((Word.Style)worddocument.Paragraphs[i].get_Style()).Borders.
                    //CompareStyles(_pathtotemplate, _path, WordS);  // check some fields...
                    //result.Add(WordS + " шрифт " + style.Font.NameAscii + " размер " + style.Font.Size + " жирный " + style.Font.Bold);
                }
                else
                {
                    if (WordP.Length <= 100)  //выводим первые 100 символов абзаца, если он длиннее, то обрезаем до ста символов
                    {
                        result.Add("Стиль " + WordS + " не входит в список эталонов: " + WordP + "...");
                    }
                    else
                    {
                        result.Add("Стиль " + WordS + " не входит в список эталонов: " + WordP.Substring(0, 100) + "...");
                    }
                }
            }
            if (!CheckPageMargins()) //проверяем отступы
            {
                result.Add("Неверные поля");

                /*wordparagraph.Range.Text = "Поля исправлены";
                 * worddocument.Paragraphs.Add(ref oMissing); //next step
                 * wordparagraph = (Word.Paragraph)wordparagraphs[wordparagraphs.Count]; */
                //next step
            }
            CloseWordDocument();

            OpenWordDocument(_pathtotemplate);                                                     //открываем шаблонный документ

            for (int i = 1; i < worddocument.Paragraphs.Count; i++)                                //numeration of paragraphs starts from 1
            {
                string     WordP = worddocument.Paragraphs[i].Range.Text;                          // get paragraph text
                Word.Style style = ((Word.Style)worddocument.Paragraphs[i].get_Style());           //get style of paragraph
                string     WordS = ((Word.Style)worddocument.Paragraphs[i].get_Style()).NameLocal; //get paragraph style name

                if (style_names.LastIndexOf(WordS) != -1)                                          //если стиль входит в список эталонных
                {
                    word_style_from_template.Add(new CheckedStyle(style));
                }
            }
            CloseWordDocument();

            List <String> styles_comparing_errors = CompareStyles(); //соответствуют ли параметры форматирования стилей документа параметрам стилей из шаблона

            foreach (String s in styles_comparing_errors)            //добавляем результаты проверки в список результатов
            {
                result.Add(s);
            }

            return(result);
        }
Esempio n. 17
0
        private void FormatParagraphHeadings_LibertyBrand(string DocToFormat)
        {
            var application = new Word.Application();

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

            try
            {
                int PCount = document.Content.Paragraphs.Count;

                if (PCount > 0)
                {
                    for (int i = 1; i < document.Content.Paragraphs.Count; i++)
                    {
                        Word.Paragraph para  = document.Content.Paragraphs[i];
                        Word.Style     style = para.get_Style() as Word.Style;
                        lblProcessing.Text = "Processing All Paragraphs...";

                        if (style.NameLocal == "Heading 1")
                        {
                            para.Range.Font.Color = Word.WdColor.wdColorDarkTeal;
                            para.Range.Font.Size  = 12;
                            para.Range.Font.Name  = "Arial";
                            para.Range.Font.Bold  = 1;

                            //para.Range.Paragraphs.KeepWithNext = 1;
                            para.Range.Paragraphs.LeftIndent      = 0;
                            para.Range.Paragraphs.RightIndent     = 0;
                            para.Range.Paragraphs.OutlineLevel    = Word.WdOutlineLevel.wdOutlineLevel1;
                            para.Range.Paragraphs.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphJustify;
                            para.Range.Paragraphs.SpaceAfter      = 12;
                            para.Range.Paragraphs.SpaceBefore     = 0;
                            para.Range.Paragraphs.LineSpacing     = 14;
                            para.Range.Paragraphs.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
                        }
                        if (style.NameLocal == "Heading 2")
                        {
                            para.Range.Font.Color = Word.WdColor.wdColorBlueGray;
                            para.Range.Font.Size  = 11;
                            para.Range.Font.Name  = "Arial";
                            para.Range.Font.Bold  = 1;
                            para.Alignment        = Word.WdParagraphAlignment.wdAlignParagraphJustify;
                        }

                        if (style.NameLocal == "Heading 3")
                        {
                            para.Range.Font.Color = Word.WdColor.wdColorBlueGray;
                            para.Range.Font.Size  = 11;
                            para.Range.Font.Name  = "Arial";
                            para.Range.Font.Bold  = 1;
                            para.Alignment        = Word.WdParagraphAlignment.wdAlignParagraphJustify;
                        }

                        if (style.NameLocal == "Heading 4")
                        {
                            para.Range.Font.Color = Word.WdColor.wdColorBlueGray;
                            para.Range.Font.Size  = 11;
                            para.Range.Font.Name  = "Arial";
                            para.Range.Font.Bold  = 1;
                            para.Alignment        = Word.WdParagraphAlignment.wdAlignParagraphJustify;
                        }



                        if (style.NameLocal == "Book Title")
                        {
                            para.Range.Font.Color = Word.WdColor.wdColorBlueGray;
                            para.Range.Font.Size  = 11;
                            para.Range.Font.Name  = "Arial";
                            para.Range.Bold       = 0;
                            para.Range.Italic     = 0;
                            para.LineSpacing      = 14;
                            para.SpaceAfter       = 18;
                            para.SpaceBefore      = 24;


                            //para.Range.Paragraphs.SpaceAfter = 18;
                            //para.Range.Paragraphs.SpaceBefore = 24;
                            //para.Range.Paragraphs.LineSpacing = 14;
                            //para.Range.Paragraphs.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceDouble;
                        }
                    }

                    document.Save();
                    document.Close();
                    application.Quit();
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message.ToString());
                document.Close();
                application.Quit();
            }
        }
Esempio n. 18
0
        private void btn_ProperNouns_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Document    doc      = Globals.ThisAddIn.Application.ActiveDocument;
            HashSet <string> wordlist = new HashSet <string>();

            foreach (Word.Range rng in TextHelpers.GetText(doc))
            {
                string     txt   = rng.Text;
                Word.Style style = rng.get_Style();
                if (style != null)
                {
                    Regex re_heading = new Regex(@"(?i)(heading|title|date|toc)");
                    Match m          = re_heading.Match(style.NameLocal);
                    if (m.Success)
                    {
                        continue;
                    }
                }

                HashSet <string> propers = new HashSet <string>();
                propers = TextHelpers.ProperNouns(txt);
                wordlist.UnionWith(propers);
            }

            //Produce the groupings
            HashSet <string> capped = TextHelpers.KeepCaps(wordlist);

            //DoubleMetaphone
            Dictionary <ushort, List <string> > mpgroups = new Dictionary <ushort, List <string> >();
            //Dictionary<string, List<string>> mpgroups = new Dictionary<string, List<string>>();
            ShortDoubleMetaphone sdm = new ShortDoubleMetaphone();

            //HashSet<string> tested = new HashSet<string>();

            foreach (string word in capped)
            {
                /*
                 * if (tested.Contains(word))
                 * {
                 *  continue;
                 * }
                 * else
                 * {
                 *  tested.Add(word);
                 * }
                 */
                sdm.computeKeys(word);
                ushort pri = sdm.PrimaryShortKey;
                ushort alt = sdm.AlternateShortKey;
                if (mpgroups.ContainsKey(pri))
                {
                    mpgroups[pri].Add(word);
                }
                else
                {
                    List <string> node = new List <string>();
                    node.Add(word);
                    mpgroups[pri] = node;
                }
                if (mpgroups.ContainsKey(alt))
                {
                    mpgroups[alt].Add(word);
                }
                else
                {
                    List <string> node = new List <string>();
                    node.Add(word);
                    mpgroups[alt] = node;
                }
            }

            //Edit Distance
            List <string> dtested = new List <string>();
            int           mindist;

            int.TryParse(Properties.Settings.Default.mindist, out mindist);
            if (mindist == 0)
            {
                mindist = 2;
            }
            Dictionary <string, List <string> > distgroups = new Dictionary <string, List <string> >();

            foreach (string word1 in capped)
            {
                if (dtested.Contains(word1))
                {
                    continue;
                }
                else
                {
                    dtested.Add(word1);
                }

                if (word1.Length <= mindist)
                {
                    continue;
                }

                foreach (string word2 in capped)
                {
                    if (word2.Length <= mindist)
                    {
                        continue;
                    }
                    int dist = TextHelpers.EditDistance(word1, word2);
                    //int percent = (int)Math.Round((dist / word1.Length) * 100.0);
                    if ((dist > 0) && (dist <= mindist))
                    //if ((dist > 0) && (percent <= distpercent))
                    {
                        dtested.Add(word2);
                        if (distgroups.ContainsKey(word1))
                        {
                            distgroups[word1].Add(word2);
                        }
                        else
                        {
                            List <string> node = new List <string>();
                            node.Add(word2);
                            distgroups[word1] = node;
                        }
                    }
                }
            }

            //Create new document
            Word.Document newdoc = Globals.ThisAddIn.Application.Documents.Add();
            Word.View     view   = Globals.ThisAddIn.Application.ActiveWindow.View;
            view.DisplayPageBoundaries = false;
            Word.Paragraph pgraph;

            //Intro text
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 1"]);
            pgraph.Range.Text = "Proper Noun Checker\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Normal"]);
            pgraph.Range.Text = "This tool only looks at words that start with a capital letter. It then uses phonetic comparison and edit distance to find other proper nouns that are similar. Words in all caps (acronyms) are not included.\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = "The system tries to ignore words at the beginning of sentences and in headers. This means some errors may go unseen, so use multiple tools!\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = "Most of what you see here are false positives! That's unavoidable. But it still catches certain otherwise-hard-to-find misspellings.\n";

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            Word.Section sec = newdoc.Sections[2];
            sec.PageSetup.TextColumns.SetCount(2);
            sec.PageSetup.TextColumns.LineBetween = -1;

            //Distance
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 2"]);
            //pgraph.KeepWithNext = 0;
            pgraph.Range.Text = "Edit Distance (" + mindist + ")\n";

            foreach (string key in distgroups.Keys)
            {
                List <string> group = distgroups[key];
                pgraph = newdoc.Content.Paragraphs.Add();
                pgraph.set_Style(newdoc.Styles["Normal"]);
                pgraph.Range.Text = key + ", " + string.Join(", ", group) + "\n";
            }

            pgraph.Range.InsertBreak(Word.WdBreakType.wdPageBreak);
            //pgraph = newdoc.Content.Paragraphs.Add();
            //pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            //Word.InlineShape line = pgraph.Range.InlineShapes.AddHorizontalLineStandard();
            //line.Height = 2;
            //line.Fill.Solid();
            //line.HorizontalLineFormat.NoShade = true;
            //line.Fill.ForeColor.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
            //line.HorizontalLineFormat.PercentWidth = 90;
            //line.HorizontalLineFormat.Alignment = WdHorizontalLineAlignment.wdHorizontalLineAlignCenter;
            //sec = newdoc.Sections[3];
            //sec.PageSetup.TextColumns.SetCount(2);
            //sec.PageSetup.TextColumns.LineBetween = -1;

            //Metaphone
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 2"]);
            //pgraph.KeepWithNext = 0;
            pgraph.Range.Text = "Phonetic Comparisons\n";

            foreach (ushort key in mpgroups.Keys)
            {
                if (key == 65535)
                {
                    continue;
                }
                List <string> group = mpgroups[key];
                if (group.Count > 1)
                {
                    pgraph = newdoc.Content.Paragraphs.Add();
                    pgraph.set_Style(newdoc.Styles["Normal"]);
                    pgraph.Range.Text = string.Join(", ", group) + "\n";
                }
            }

            //pgraph = newdoc.Content.Paragraphs.Add();
            //pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            newdoc.GrammarChecked = true;
        }
Esempio n. 19
0
        /// <summary>
        /// Process a paragraph, converting its contents into jasper reports XML
        /// </summary>
        /// <param name="paragraph">A word paragraph</param>
        public void ProcessParagraph(Word.Paragraph paragraph)
        {
            XmlElement band;
            String     text = paragraph.Range.Text;

            text = text.Substring(0, text.Length - 1);
            Word.Style           style      = paragraph.get_Style();
            Word.ParagraphFormat paraFormat = paragraph.Format;

            int spaceBefore = (int)paraFormat.SpaceBefore;
            int spaceAfter  = (int)paraFormat.SpaceAfter;
            int fontSize    = (int)style.Font.Size;
            int bandHeight  = spaceBefore + spaceAfter + fontSize;

            Debug.WriteLine("Processing paragraph: " + text);
            int parseFromChar = 0;

            if (text.StartsWith("$"))
            {
                String tagName, tagValue;
                int    nextChar;

                if (ParseTagText(text, out tagName, out tagValue, out nextChar))
                {
                    if (tagName.Equals("bandtype"))
                    {
                        switch (tagValue.ToLower())
                        {
                        case "background":
                            currentBandType = BandType.Background;
                            break;

                        case "title":
                            currentBandType = BandType.Title;
                            break;

                        case "pageheader":
                            currentBandType = BandType.PageHeader;
                            break;

                        case "columnheader":
                            currentBandType = BandType.ColumnHeader;
                            break;

                        case "detail":
                            currentBandType = BandType.Detail;
                            break;

                        case "columnfooter":
                            currentBandType = BandType.ColumnFooter;
                            break;

                        case "pagefooter":
                            currentBandType = BandType.PageFooter;
                            break;

                        case "lastpagefooter":
                            currentBandType = BandType.LastPageFooter;
                            break;

                        case "summary":
                            currentBandType = BandType.Summary;
                            break;

                        case "nodata":
                            currentBandType = BandType.NoData;
                            break;

                        default:
                            Debug.WriteLine("Invalid band type " + tagValue);
                            break;
                        }
                        Debug.WriteLine("Changed band type to " + currentBandType.ToString());
                        return;
                    }
                }
            }
            if (currentBandType == BandType.Detail)
            {
                // Add a new band for each paragraph
                band = jDoc.CreateElement("band");
                jDetail.AppendChild(band);

                // Set the band attributes
                // Set the height based upon the font size - it will stretch
                band.SetAttribute("height", fontSize.ToString());
                // Split type
                band.SetAttribute("splitType", "Stretch");
            }
            else
            {
                // There is only one band of these types, so all paragraphs have to fit
                XmlElement bandElement = GetBandElement(currentBandType);

                // If there is a child element, it will be the band. If not, create it
                if (bandElement.HasChildNodes)
                {
                    XmlNode node = bandElement.GetElementsByTagName("band")[0];
                    band = (XmlElement)node;
                }
                else
                {
                    // Add a new band covering all paragraphs
                    band = jDoc.CreateElement("band");
                    bandElement.AppendChild(band);
                    band.SetAttribute("height", bandHeight.ToString());
                    band.SetAttribute("splitType", "Stretch");
                }
            }

            // Add the text field, report element, text element, and text field expression
            XmlElement textField    = jDoc.CreateElement("textField");
            XmlElement reportElt    = jDoc.CreateElement("reportElement");
            XmlElement box          = jDoc.CreateElement("box");
            XmlElement textElt      = jDoc.CreateElement("textElement");
            XmlElement textEltParag = jDoc.CreateElement("paragraph");
            XmlElement textFont     = jDoc.CreateElement("font");
            XmlElement textFieldExp = jDoc.CreateElement("textFieldExpression");

            band.AppendChild(textField);
            textField.AppendChild(reportElt);
            textField.AppendChild(box);
            textField.AppendChild(textElt);
            textField.AppendChild(textFieldExp);
            textElt.AppendChild(textFont);
            textElt.AppendChild(textEltParag);

            textField.SetAttribute("isStretchWithOverflow", "true");
            textField.SetAttribute("isBlankWhenNull", "true");

            reportElt.SetAttribute("stretchType", "RelativeToBandHeight");
            reportElt.SetAttribute("x", "0");
            reportElt.SetAttribute("width", ((int)columnWidth).ToString());
            // TODO: If not detail band, then y and height need to be calculated
            // TODO: y position should consider the paragraph spacing before
            reportElt.SetAttribute("y", "0");
            reportElt.SetAttribute("height", fontSize.ToString());

            // Left and right indents - use the box, so we have flexibility to use the
            // first line indent with negative values for hanging indents.
            box.SetAttribute("leftPadding", ((int)paragraph.LeftIndent).ToString());
            box.SetAttribute("rightPadding", ((int)paragraph.RightIndent).ToString());
            textEltParag.SetAttribute("firstLineIndent", ((int)paragraph.FirstLineIndent).ToString());
            // Top and bottom - paragraph spacing before and after
            box.SetAttribute("topPadding", spaceBefore.ToString());
            box.SetAttribute("bottomPadding", spaceAfter.ToString());

            // Paragraph alignment
            {
                String alignment = "";
                switch (paragraph.Alignment)
                {
                case Word.WdParagraphAlignment.wdAlignParagraphLeft:
                    alignment = "Left";
                    break;

                case Word.WdParagraphAlignment.wdAlignParagraphRight:
                    alignment = "Right";
                    break;

                case Word.WdParagraphAlignment.wdAlignParagraphCenter:
                    alignment = "Center";
                    break;

                case Word.WdParagraphAlignment.wdAlignParagraphJustify:
                case Word.WdParagraphAlignment.wdAlignParagraphJustifyHi:
                case Word.WdParagraphAlignment.wdAlignParagraphJustifyMed:
                case Word.WdParagraphAlignment.wdAlignParagraphJustifyLow:
                case Word.WdParagraphAlignment.wdAlignParagraphDistribute:
                case Word.WdParagraphAlignment.wdAlignParagraphThaiJustify:
                    alignment = "Justified";
                    break;

                default:
                    break;
                }
                textElt.SetAttribute("textAlignment", alignment);
            }

            // Markup type
            textElt.SetAttribute("markup", "styled");

            // Get the format of the first character we are parsing. This becomes
            // our 'base' format.
            int textLength = text.Length;

            Word.Characters chars = paragraph.Range.Characters;

            Word.Range refRange = chars[parseFromChar + 1];

            textFont.SetAttribute("fontName", refRange.Font.Name);
            textFont.SetAttribute("size", refRange.Font.Size.ToString());
            reportElt.SetAttribute("forecolor", RGBHex(refRange.Font.TextColor.RGB));
            Word.Range lastRange = refRange;

            String openStyle, closeStyle;

            GetStyleTags(refRange, refRange, out openStyle, out closeStyle);
            StringBuilder jText = new StringBuilder(openStyle, 2048);

            for (int c = parseFromChar; c < textLength; c++)
            {
                // Current character
                String ch = text.Substring(c, 1);
                // Previous character
                String prevCh = text.Substring((c > 0 ? c - 1 : 0), 1);

                // Check if we are processing style changes
                if (c > parseFromChar && // Must be past the first character to parse
                    (
                        // Either every character
                        styleCheck == StyleCheck.CheckEveryCharacter ||
                        // Or every word boundary (whitespace, punctuation)
                        (styleCheck == StyleCheck.CheckEveryWordBoundary &&
                         (
                             Char.IsWhiteSpace(ch, 0) || Char.IsWhiteSpace(prevCh, 0) ||
                             Char.IsPunctuation(ch, 0) || Char.IsPunctuation(prevCh, 0) ||
                             Char.IsSeparator(ch, 0) || Char.IsSeparator(prevCh, 0)
                         )
                        )
                    )
                    )
                {
                    // Compare the style to refRange, and if style is different,
                    // close previous style tag and create a new one
                    Word.Range curRange = chars[c + 1];
                    if (!AreStylesEqual(lastRange, curRange))
                    {
                        // Close the previous style
                        jText.Append(closeStyle);
                        // Start the new style
                        GetStyleTags(curRange, refRange, out openStyle, out closeStyle);
                        jText.Append(openStyle);
                        lastRange = curRange;
                    }
                }

                // TODO: Cater for fields, etc
                if (ch == "<")
                {
                    ch = "&lt;";
                }
                else if (ch == ">")
                {
                    ch = "&gt;";
                }
                else if (ch == "&")
                {
                    ch = "&amp;";
                }
                else if (ch == "\"")
                {
                    ch = "&quot;";
                }
                else if (ch == "'")
                {
                    ch = "&apos;";
                }
                else if (ch == "\r" || ch == "\n" || ch == "\v")
                {
                    ch = "<br/>";
                }
                jText.Append(ch);
            }
            // Close the style
            jText.Append(closeStyle);

            XmlCDataSection styledText = jDoc.CreateCDataSection("\"" + jText + "\"");

            textFieldExp.AppendChild(styledText);
        }
        public void MakeWord()
        {
            Word.Application word = new Word.Application();
            word.Visible = true;
            Word.Document doc = word.Documents.Add();

            //Set Document Style
            #region
            Word.Style style = word.ActiveDocument.Styles["Обычный"];
            style.Font.Name = "Times New Roman";
            style.Font.Size = 14;
            style.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpace1pt5;
            #endregion

            //Set Header Image from Resources
            #region
            var tempPath = Path.GetTempPath() + "AnswerHeader.png";
            if (!File.Exists(tempPath))
            {
                var headerBitmap = Properties.Resources.AnswerHeader;
                System.Drawing.Bitmap headerImage = (System.Drawing.Bitmap)(headerBitmap);
                try
                {
                    headerImage.Save(tempPath);
                }
                catch (Exception e)
                {
                    System.Windows.MessageBox.Show(e.ToString());
                }
            }
            doc.Shapes.AddPicture(tempPath,
                                  SaveWithDocument: true, Top: -56, Left: -85, Width: doc.PageSetup.PageWidth, Height: 98);
            #endregion

            //Set paragraphs
            #region
            var headerParagraph = doc.Paragraphs.Add();
            headerParagraph.Range.InsertParagraphAfter();
            var littleFormatRegion = doc.Paragraphs.Add();
            littleFormatRegion.Range.InsertParagraphAfter();
            var titleParagraph = doc.Content.Paragraphs.Add();
            titleParagraph.Range.InsertParagraphAfter();
            var afterTitleFirstFormat  = doc.Content.Paragraphs.Add();
            var afterTitleSecondFormat = doc.Content.Paragraphs.Add();
            var patientParagraph       = doc.Content.Paragraphs.Add();
            patientParagraph.Range.InsertParagraphAfter();
            var summaryFirstParagraph = doc.Paragraphs.Add();
            summaryFirstParagraph.Range.InsertParagraphAfter();
            var summarySecondParagraph = doc.Paragraphs.Add();
            summarySecondParagraph.Range.InsertParagraphAfter();
            var arraysSummaryParagraph = doc.Paragraphs.Add();
            arraysSummaryParagraph.Range.InsertParagraphAfter();
            var commentsParagraph = doc.Paragraphs.Add();
            commentsParagraph.Range.InsertParagraphAfter();
            var nonBalancedParagraphTitle = doc.Paragraphs.Add();
            var nonBalancedParagraph      = doc.Paragraphs.Add();
            nonBalancedParagraph.Range.InsertParagraphAfter();
            #endregion

            //Format paragraphs
            #region
            headerParagraph.Range.Font.Size        = 10;
            littleFormatRegion.Range.Font.Size     = 12;
            afterTitleFirstFormat.Range.Font.Size  = 12;
            afterTitleSecondFormat.Range.Font.Size = 12;

            titleParagraph.Range.Font.Bold                 = 1;
            titleParagraph.Range.Font.Underline            = Word.WdUnderline.wdUnderlineSingle;
            titleParagraph.Range.Text                      = "Результаты молекулярно-цитогенетического исследования методом сравнительной геномной гибридизации на микрочипах (молекулярное кариотипирование) с использованием SNP/олигонуклеотидной микроматрицы Affymetrix Cytoscan HD, содержащей 2 696 550 проб.";
            titleParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;

            patientParagraph.Range.Font.Underline            = Word.WdUnderline.wdUnderlineSingle;
            patientParagraph.Range.Text                      = _AnswerParser.GetPatientInfo();
            patientParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;

            summaryFirstParagraph.Range.Font.Underline            = Word.WdUnderline.wdUnderlineSingle;
            summaryFirstParagraph.Range.Text                      = "Заключение";
            summaryFirstParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;


            summarySecondParagraph.Range.Font.Underline            = Word.WdUnderline.wdUnderlineSingle;
            summarySecondParagraph.Range.Text                      = "Запись результатов молекулярного кариотипа(согласно ISCN 2013 ):";
            summarySecondParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;
            var footnoteRange = summarySecondParagraph.Range;
            footnoteRange.End -= 2;
            doc.Footnotes.Add(footnoteRange, Text: " ISCN (2013):An International System for Human Cytogenetic Nomenclature, L.G. Shaffer, J. McGowan-Jordan, M. Schmid (eds); S. Karger, Basel 2013.");

            arraysSummaryParagraph.Range.Text = _AnswerParser.GetSummary();
            doc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);

            commentsParagraph.Range.Font.Bold      = 1;
            commentsParagraph.Range.Font.Underline = Word.WdUnderline.wdUnderlineSingle;
            commentsParagraph.Range.Text           = "Несбалансированные хромосомные и геномные перестройки (более 1 млн пн):";

            nonBalancedParagraphTitle.Range.Font.Bold      = 1;
            nonBalancedParagraphTitle.Range.Font.Underline = Word.WdUnderline.wdUnderlineSingle;
            nonBalancedParagraphTitle.Range.Text           = "Несбалансированные хромосомные и геномные перестройки (более 1 млн пн):";
            #endregion

            //Set and Format NonStatic Paragraphs
            #region
            //if (_AnswerParser.NonBalanceRearrangements.Count != 0)
            //{
            //    foreach (var rearrangement in _AnswerParser.NonBalanceRearrangements)
            //    {
            //        nonBalancedParagraph.Range.Text = rearrangement.ToString();
            //        nonBalancedParagraph.Range.InsertParagraphAfter();
            //    }
            //}
            //else
            //{
            //    nonBalancedParagraph.Range.Text = "Не Выявленно.";
            //    nonBalancedParagraph.Range.InsertParagraphAfter();
            //}
            #endregion
        }
 public WrappedStyle(Word.Style s)
 {
     this.s = s;
 }
Esempio n. 22
0
        public WordSpecExport(CopyToClipboard cpc, BackgroundWorker ExportWorker, string filename)
        {
            Microsoft.Office.Interop.Word.Application  oWord  = null;
            Microsoft.Office.Interop.Excel.Application oExcel = null;


            try
            {
                List <SveraClass.FromDataBaseWide> rowgrid = SveraCl.PereformSpec(cpc, TypeOfExport.WordSpec);

                // return;

                int maxofprog = rowgrid.Count + 2 * 8;
                maxofprog += rowgrid.Count;
                int counter = 0;
                ExportWorker.ReportProgress(maxofprog, Operation.init);

                string exportPath = FunctionUse.GetExportPath(filename);
                try
                {
                    exportPath += "\\";
                    exportPath += (filename != null && filename != "") ? Path.GetFileNameWithoutExtension(filename) : "specification";
                    exportPath += ".docx";
                    if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.standart)
                    {
                        File.WriteAllBytes(exportPath, SveraExport.Properties.Resources.Specification);
                    }
                    else if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.rev)
                    {
                        File.WriteAllBytes(exportPath, SveraExport.Properties.Resources.specification_del);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Файл открыт и используется. Закройте файл и повторите попытку", "Svera Export Word", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                Microsoft.Office.Interop.Word.Document   oDoc;
                Microsoft.Office.Interop.Excel.Workbook  oBook;
                Microsoft.Office.Interop.Excel.Worksheet oSheet;
                //Microsoft.Office.Interop.Word.Table oTable;
                //Microsoft.Office.Interop.Word.Paragraph oPara1;


                counter += 2;
                ExportWorker.ReportProgress(counter, Operation.change);
                if (ExportWorker.CancellationPending)
                {
                    ExitWord(oWord, oExcel, true);
                    return;
                }



                try
                {
                    oWord  = new Microsoft.Office.Interop.Word.Application();
                    oDoc   = oWord.Documents.Open(exportPath);
                    oExcel = new Microsoft.Office.Interop.Excel.Application();
                    oBook  = oExcel.Workbooks.Add();
                    oSheet = oExcel.Worksheets[1];

                    podgotovWord(oWord, oExcel, false, false);

                    oDoc.SaveAs(exportPath);
                    oBook.SaveAs(Path.GetDirectoryName(exportPath) + "\\" + Path.GetFileNameWithoutExtension(exportPath) + ".xlsx");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Файл " + Path.GetDirectoryName(exportPath) + "\\" + Path.GetFileNameWithoutExtension(exportPath) + " уже открыт. Закройте файл. Повторите попытку", "Svera Export Word", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ExitWord(oWord, oExcel, true);
                    return;
                }


                counter += 2;
                ExportWorker.ReportProgress(counter, Operation.change);
                if (ExportWorker.CancellationPending)
                {
                    ExitWord(oWord, oExcel, true);
                    return;
                }



                oSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;
                oDoc.PageSetup.Orientation   = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
                oDoc.AutoHyphenation         = true;

                oDoc.Content.Font.Name = "Times New Roman";
                oDoc.Content.Font.Size = 10;

                int numberCOl = 9;
                if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.standart)
                {
                    numberCOl = 9;
                }
                else if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.rev)
                {
                    numberCOl = 11;
                }

                string[,] OtableStr = new string[rowgrid.Count, numberCOl];

                if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.standart)
                {
                    oSheet.Columns[1].ColumnWidth = 5;
                    oSheet.Columns[2].ColumnWidth = 30;
                    oSheet.Columns[3].ColumnWidth = 20;
                    oSheet.Columns[4].ColumnWidth = 12;
                    oSheet.Columns[5].ColumnWidth = 15;
                    oSheet.Columns[6].ColumnWidth = 5;
                    oSheet.Columns[7].ColumnWidth = 7;
                    oSheet.Columns[8].ColumnWidth = 8;
                    oSheet.Columns[9].ColumnWidth = 15;
                }
                else if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.rev)
                {
                    oSheet.Columns[1].ColumnWidth  = 5;
                    oSheet.Columns[2].ColumnWidth  = 30;
                    oSheet.Columns[3].ColumnWidth  = 20;
                    oSheet.Columns[4].ColumnWidth  = 8;
                    oSheet.Columns[5].ColumnWidth  = 8;
                    oSheet.Columns[6].ColumnWidth  = 10;
                    oSheet.Columns[7].ColumnWidth  = 8;
                    oSheet.Columns[8].ColumnWidth  = 8;
                    oSheet.Columns[9].ColumnWidth  = 8;
                    oSheet.Columns[10].ColumnWidth = 8;
                    oSheet.Columns[11].ColumnWidth = 12;
                }


                counter += 2;
                ExportWorker.ReportProgress(counter, Operation.change);
                if (ExportWorker.CancellationPending)
                {
                    ExitWord(oWord, oExcel, true);
                    return;
                }

                int numberRow = 0;
                for (int i = 0; i <= rowgrid.Count - 1; i++)
                {
                    addrowInSpec(cpc, rowgrid[i], OtableStr, oSheet, ref numberRow);
                }

                counter += 2;
                ExportWorker.ReportProgress(counter, Operation.change);
                if (ExportWorker.CancellationPending)
                {
                    ExitWord(oWord, oExcel, true);
                    return;
                }

                if (rowgrid.Count > 0)
                {
                    Microsoft.Office.Interop.Excel.Range rangeEx = oSheet.Range[oSheet.Cells[1, 1], oSheet.Cells[OtableStr.GetUpperBound(0) + 1, OtableStr.GetUpperBound(1) + 1]];
                    rangeEx.Value     = OtableStr;
                    rangeEx.Font.Name = "Times New Roman";
                    rangeEx.Font.Size = 10;
                    rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].LineStyle         = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].LineStyle          = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle       = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle        = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].LineStyle   = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    rangeEx.WrapText = true;
                }



                counter += 2;
                ExportWorker.ReportProgress(counter, Operation.change);
                if (ExportWorker.CancellationPending)
                {
                    ExitWord(oWord, oExcel, true);
                    return;
                }


                if (rowgrid.Count > 0)
                {
                    for (int i = 1; i <= OtableStr.GetUpperBound(1) + 1; i++)
                    {
                        if (i != 2 && i != 3)
                        {
                            oSheet.Columns[i].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                            oSheet.Columns[i].VerticalAlignment   = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
                        }
                        else
                        {
                            oSheet.Columns[i].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
                            oSheet.Columns[i].VerticalAlignment   = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
                        }
                    }

                    counter += 2;
                    ExportWorker.ReportProgress(counter, Operation.change);
                    if (ExportWorker.CancellationPending)
                    {
                        ExitWord(oWord, oExcel, true);
                        return;
                    }
                }


                for (int i = 0; i <= rowgrid.Count - 1; i++)
                {
                    if (rowgrid[i].RowTypes == RowsType.TipOborud)
                    {
                        oSheet.Cells[i + 1, 2].Font.Bold           = true;
                        oSheet.Cells[i + 1, 2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    }
                    else if (rowgrid[i].RowTypes == RowsType.TipPostav)
                    {
                        oSheet.Cells[i + 1, 2].Font.Bold           = true;
                        oSheet.Cells[i + 1, 2].Font.Underline      = Microsoft.Office.Interop.Excel.XlUnderlineStyle.xlUnderlineStyleSingle;
                        oSheet.Cells[i + 1, 2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    }
                    else if (rowgrid[i].RowTypes == RowsType.Etap)
                    {
                        oSheet.Cells[i + 1, 2].Font.Bold           = true;
                        oSheet.Cells[i + 1, 2].Font.Underline      = Microsoft.Office.Interop.Excel.XlUnderlineStyle.xlUnderlineStyleSingle;
                        oSheet.Cells[i + 1, 2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    }
                }

                counter += 2;
                ExportWorker.ReportProgress(counter, Operation.change);
                if (ExportWorker.CancellationPending)
                {
                    ExitWord(oWord, oExcel, true);
                    return;
                }


                oSheet.Rows.AutoFit();

                oExcel.ActiveWindow.SplitColumn = 0;
                oExcel.ActiveWindow.SplitRow    = 2;
                oExcel.ActiveWindow.FreezePanes = true;
                oExcel.ActiveWindow.Zoom        = 82;


                Microsoft.Office.Interop.Word.Style Stylus = oWord.Selection.get_Style();
                Stylus.Font.Name = "Times New Roman";
                Stylus.Font.Size = 10;
                Stylus.ParagraphFormat.SpaceBefore = 0;
                Stylus.ParagraphFormat.SpaceAfter  = 0;

                if (rowgrid.Count > 0)
                {
                    oSheet.Range[oSheet.Cells[1, 1], oSheet.Cells[OtableStr.GetUpperBound(0) + 1, OtableStr.GetUpperBound(1) + 1]].Copy();
                }
                oWord.Selection.Paste();
                oExcel.CutCopyMode = XlCutCopyMode.xlCopy;

                if (oDoc.Tables.Count > 1)
                {
                    oDoc.Tables[1].Rows.HeightRule = WdRowHeightRule.wdRowHeightAtLeast;
                    oDoc.Tables[1].Rows.Height     = oWord.CentimetersToPoints(0.58F);

                    oDoc.Tables[1].AllowAutoFit = false;
                    oDoc.Tables[1].LeftPadding  = oDoc.Tables[2].LeftPadding;
                    oDoc.Tables[1].RightPadding = oDoc.Tables[2].RightPadding;

                    if (oDoc.Tables[2].Columns.Count >= numberCOl && oDoc.Tables[1].Columns.Count >= numberCOl)
                    {
                        for (int i = 1; i <= numberCOl; i++)
                        {
                            oDoc.Tables[1].Columns[i].Width = oDoc.Tables[2].Columns[i].Width;
                        }
                    }
                    oDoc.Tables[2].Delete();

                    oDoc.Tables[1].Rows.SetLeftIndent(oWord.CentimetersToPoints(0.03F), Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustNone);
                }

                counter += 2;
                ExportWorker.ReportProgress(counter, Operation.change);
                if (ExportWorker.CancellationPending)
                {
                    ExitWord(oWord, oExcel, true);
                    return;
                }


                oDoc.Save();
                oBook.Save();
                ExitWord(oWord, oExcel, false);
                oWord  = null;
                oExcel = null;
            }
            catch (Exception ex)
            {
                ExitWord(oWord, oExcel, false);

                throw new Exception("WordExport", ex);
            }
        }
        public static void CreateDefaultDocumentStyle(Word.Document newDocument)
        {
            Word.PageSetup pageSetup = newDocument.PageSetup;
            pageSetup.TopMargin    = Globals.ThisAddIn.Application.InchesToPoints(0.95f);
            pageSetup.BottomMargin = Globals.ThisAddIn.Application.InchesToPoints(0.79f);
            pageSetup.LeftMargin   = Globals.ThisAddIn.Application.InchesToPoints(0.98f);
            pageSetup.RightMargin  = Globals.ThisAddIn.Application.InchesToPoints(0.79f);


            ///Ten dai bieu
            Word.Style style = Globals.ThisAddIn.Application.ActiveDocument.Styles.Add(Constants.RerpesentativeStyle);

            style.Font.Name   = "Times New Roman";
            style.Font.Size   = 14;
            style.Font.Color  = Word.WdColor.wdColorBlue;
            style.Font.Bold   = -1;
            style.Font.Italic = -1;

            style.ParagraphFormat.FirstLineIndent = Globals.ThisAddIn.Application.InchesToPoints(0.37f);
            style.ParagraphFormat.SpaceBefore     = 6;

            ///Loi phat bieu
            style = Globals.ThisAddIn.Application.ActiveDocument.Styles.Add(Constants.ContentStyle);

            style.Font.Name  = "Times New Roman";
            style.Font.Size  = 13;
            style.Font.Color = Word.WdColor.wdColorBlue;
            style.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;

            style.ParagraphFormat.FirstLineIndent = Globals.ThisAddIn.Application.InchesToPoints(0.37f);
            style.ParagraphFormat.SpaceAfterAuto  = 0;
            style.ParagraphFormat.SpaceBefore     = 0;

            ///Tieu de bien ban
            style              = Globals.ThisAddIn.Application.ActiveDocument.Styles.Add(Constants.MeetingTitleStyle);
            style.Font.Name    = "Times New Roman";
            style.Font.Size    = 16;
            style.Font.Color   = Word.WdColor.wdColorBlue;
            style.Font.Bold    = -1;
            style.Font.AllCaps = -1;
            style.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            style.ParagraphFormat.FirstLineIndent = Globals.ThisAddIn.Application.InchesToPoints(0);


            /// Ghi theo bang ghi am
            style = Globals.ThisAddIn.Application.ActiveDocument.Styles.Add(Constants.RecordingTitleStyle);

            style.Font.Name   = "Times New Roman";
            style.Font.Size   = 12;
            style.Font.Color  = Word.WdColor.wdColorBlue;
            style.Font.Italic = -1;
            style.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            style.ParagraphFormat.SpaceBefore     = 3;
            style.ParagraphFormat.FirstLineIndent = Globals.ThisAddIn.Application.InchesToPoints(0);

            ///Thoi gian hop
            style            = Globals.ThisAddIn.Application.ActiveDocument.Styles.Add(Constants.MeetingTimeTitleStyle);
            style.Font.Name  = "Times New Roman";
            style.Font.Size  = 13;
            style.Font.Color = Word.WdColor.wdColorBlue;
            style.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            style.ParagraphFormat.SpaceBefore     = 3;
            style.ParagraphFormat.FirstLineIndent = Globals.ThisAddIn.Application.InchesToPoints(0);

            ///Noi dung
            style            = Globals.ThisAddIn.Application.ActiveDocument.Styles.Add(Constants.MeetingContentTitleStyle);
            style.Font.Name  = "Times New Roman";
            style.Font.Size  = 13;
            style.Font.Color = Word.WdColor.wdColorBlue;
            style.Font.Bold  = -1;
            style.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            style.ParagraphFormat.SpaceBefore     = 6;
            style.ParagraphFormat.FirstLineIndent = Globals.ThisAddIn.Application.InchesToPoints(0);
        }
Esempio n. 24
0
        public static bool CreateWordDocParagraph(string qname, string[][] qdata, IVsThreadedWaitDialog2 dlg)
        {
            //InitializeVariables();
            System.Net.WebClient webclient = new System.Net.WebClient();
            webclient.Credentials = System.Net.CredentialCache.DefaultCredentials;

            var           application = new MSWord.Application();
            var           document    = new MSWord.Document();
            object        missing     = System.Reflection.Missing.Value;
            int           pagewidth   = 800;
            bool          bcanceled;
            int           progress = 1;
            StringBuilder strbld   = new StringBuilder();

            MSWord.WdBuiltinStyle[] hstyles = new MSWord.WdBuiltinStyle[8];
            hstyles[0] = MSWord.WdBuiltinStyle.wdStyleHeading1;
            hstyles[1] = MSWord.WdBuiltinStyle.wdStyleHeading2;
            hstyles[2] = MSWord.WdBuiltinStyle.wdStyleHeading3;
            hstyles[3] = MSWord.WdBuiltinStyle.wdStyleHeading4;
            hstyles[4] = MSWord.WdBuiltinStyle.wdStyleHeading5;
            hstyles[5] = MSWord.WdBuiltinStyle.wdStyleHeading6;
            hstyles[6] = MSWord.WdBuiltinStyle.wdStyleHeading7;
            hstyles[7] = MSWord.WdBuiltinStyle.wdStyleHeading8;

            application.Visible       = true;
            application.WindowState   = MSWord.WdWindowState.wdWindowStateMinimize;
            application.DisplayAlerts = MSWord.WdAlertLevel.wdAlertsNone;
            document = application.Documents.Add();
            //document.PageSetup.Orientation = MSWord.WdOrientation.wdOrientLandscape;
            document.PageSetup.LeftMargin   = 20;
            document.PageSetup.RightMargin  = 20;
            document.PageSetup.TopMargin    = 20;
            document.PageSetup.BottomMargin = 20;
            document.PageSetup.PageWidth    = pagewidth + 40;

            MSWord.Paragraph prg = document.Paragraphs.Add();
            prg.Range.Text = "Query results for " + qname + " [" + DateTime.Now + "]";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle);
            //prg.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            prg.SpaceAfter  = 100;
            prg.SpaceBefore = 100;
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "Table of Contents";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTocHeading);
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "TOC";
            prg.Range.InsertParagraphAfter();
            prg.Range.InsertBreak(MSWord.WdBreakType.wdPageBreak);

            prg = document.Paragraphs.Add();
            MSWord.Table qtable = document.Tables.Add(prg.Range, qdata.Length, 1);
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "Appendix";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle);
            prg.Range.InsertParagraphAfter();

            object styleTypeTable = MSWord.WdStyleType.wdStyleTypeTable;

            MSWord.Style styl = document.Styles.Add("New Table Style", ref styleTypeTable);
            styl.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle;
            styl.ParagraphFormat.SpaceAfter      = 0;
            styl.ParagraphFormat.SpaceBefore     = 0;
            styl.Table.TopPadding    = 0;
            styl.Table.BottomPadding = 0;
            styl.Table.LeftPadding   = 0;
            styl.Table.RightPadding  = 0;
            //styl.Table.Borders.Enable = 1;
            qtable.Range.set_Style(styl);

            MSWord.Cell cell = qtable.Cell(1, 1);

            int headerwidth = 85;
            int levelwidth  = 100;

            object rows, cols;

            for (int i = 0; i < qdata.Length; i++)
            {
                int level = int.Parse(qdata[i][1]);
                if (level > 0)
                {
                    rows = 1;
                    cols = 2;
                    cell.Split(ref rows, ref cols);
                    cell.Range.Cells.SetWidth(level * levelwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                    cell = cell.Next;
                }

                rows = 1 + (string.IsNullOrWhiteSpace(qdata[i][0]) ? 0 : 1) + (string.IsNullOrWhiteSpace(qdata[i][6]) ? 0 : 1);
                cols = 2;
                cell.Split(ref rows, ref cols);
                cell.Merge(cell.Next);

                string title = String.Format("{0} {1} ({2})",
                                             qdata[i][2],
                                             (qdata[i][5].Length > 128 ? qdata[i][5].Remove(128) : qdata[i][5]).Replace("\n", "").Replace("\r", "").Replace("\t", ""),
                                             qdata[i][4]);

                cell.Range.Text      = title;
                cell.Range.Font.Bold = 1;
                cell.Range.set_Style(hstyles[level < 8 ? level:7]);
                cell = cell.Next;

                dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Adding to Word document " + qdata[i][3] + " #" + qdata[i][4], "status", progress++, 100, false, out bcanceled);
                if (progress == 100)
                {
                    progress = 0;
                }
                if (bcanceled)
                {
                    application.Visible = true;
                    Marshal.ReleaseComObject(document);
                    Marshal.ReleaseComObject(application);

                    return(true);
                }

                /*cell.Range.Text = "Title";
                 * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                 * cell.Range.Font.Bold = 1;
                 * cell = cell.Next;
                 *
                 * cell.Range.Text = qdata[i][4];
                 * cell = cell.Next;*/

                /*cell.Range.Text = "Description";
                 * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                 * cell.Range.Font.Bold = 1;
                 * cell = cell.Next;*/

                if (!string.IsNullOrWhiteSpace(qdata[i][6]))
                {
                    cell.Merge(cell.Next);
                    cell.Range.Text = qdata[i][6];
                    cell            = cell.Next;
                }

                if (!string.IsNullOrWhiteSpace(qdata[i][0]))
                {
                    cell.Range.Text = "Attachments";
                    cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                    cell.Range.Font.Bold = 1;
                    cell = cell.Next;

                    var query = qdata[i][0]
                                .Split(';')
                                .Where(x => !string.IsNullOrWhiteSpace(x))
                                .Select(x =>
                    {
                        string[] ch = x.Split('~');
                        return(new { name = ch[0], value = ch[1] });
                    }).ToArray();
                    cell.Split(query.Length, 1);

                    foreach (var kvp in query)
                    {
                        string localpath = Path.GetTempFileName() + "." + kvp.name;
                        //try { File.Delete(localpath); }
                        //catch { }

                        try
                        {
                            webclient.DownloadFile(kvp.value, localpath);
                        }
                        catch (Exception ex)
                        {
                            localpath = "";
                            Utilities.OutputCommandString(ex.ToString());
                        }

                        prg            = document.Paragraphs.Add();
                        prg.Range.Text = kvp.name;
                        prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleHeading3);

                        cell.Range.Text = kvp.name;
                        document.Hyperlinks.Add(cell.Range, missing, prg.Range);

                        prg.Range.InsertParagraphAfter();
                        document.InlineShapes.AddHorizontalLineStandard(prg.Range);
                        prg = document.Paragraphs.Add();

                        if (!string.IsNullOrEmpty(localpath))
                        {
                            try
                            {
                                Image img = Image.FromFile(localpath);
                                img.Dispose();
                                document.InlineShapes.AddPicture(localpath, false, true, prg.Range);
                            }
                            catch
                            {
                                if (Path.GetExtension(kvp.name).Equals(".sql", StringComparison.InvariantCultureIgnoreCase) ||
                                    Path.GetExtension(kvp.name).Equals(".txt", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    prg.Range.InsertFile(localpath);//, prg.Range, false, true, false);
                                }
                                else
                                {
                                    MSWord.InlineShape shape = document.InlineShapes.AddOLEObject(missing, localpath, false, false, missing, missing, missing, prg.Range);
                                    if (shape.OLEFormat.ClassType.ToString() != "Package")
                                    {
                                        shape.Width = document.PageSetup.PageWidth - 40;
                                    }
                                }
                            }
                        }
                        cell = cell.Next;
                    }
                    if (query.Length == 0)
                    {
                        cell = cell.Next;
                    }
                }
            }

            object styleTypePara = MSWord.WdStyleType.wdStyleTypeParagraph;

            MSWord.Style styl2 = document.Styles.Add("New Paragraph Style", ref styleTypePara);
            //styl2.ParagraphFormat.set_Style(MSWord.WdBuiltinStyle.wdStyleNormal);
            styl2.ParagraphFormat.LeftIndent      = 100;
            styl2.ParagraphFormat.RightIndent     = 100;
            styl2.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle;
            styl2.ParagraphFormat.SpaceAfter      = 0;
            styl2.ParagraphFormat.SpaceBefore     = 0;

            MSWord.Paragraph       tocpara = document.Paragraphs[3];
            MSWord.TableOfContents tblct   = document.TablesOfContents.Add(tocpara.Range, missing, 1, 1);
            tblct.Update();
            //tblct.Range.set_Style(styl2);

            //application.Visible = true;

            Marshal.ReleaseComObject(document);
            Marshal.ReleaseComObject(application);

            return(false);
        }
        object styleDefaultPFont = null; //Word.Style

        #endregion Fields

        #region Constructors

        public FormStyleChooser()
        {
            InitializeComponent();

            styleDefaultPFont = Globals.ThisAddIn.Application.ActiveDocument.Styles[Word.WdBuiltinStyle.wdStyleDefaultParagraphFont];

            cc = ContentControlMaker.getActiveContentControl(Globals.ThisAddIn.Application.ActiveDocument, Globals.ThisAddIn.Application.Selection);
            if (cc == null)
            {
                // Shouldn't happen
                log.Error("Which content control?");
                this.Close();
            }

            dynamic d = cc.get_DefaultTextStyle(); // actually returns the PARAGRAPH style!
            if (d == null)
            {
                // Nothing selected
                log.Error("No current style!");

            }
            else
            {
                //log.Debug(((Object)d).GetType().FullName);
                // System.__ComObject

                //string typeName = ComHelper.GetTypeName(d);
                //log.Debug(typeName);
                //Marshal.ReleaseComObject(selection);

                existingStyle = d as Word.Style;
                log.Debug(existingStyle.NameLocal); // eg Heading 6 ie the PARAGRAPH style!

            }

            foreach (Word.Style s in Globals.ThisAddIn.Application.ActiveDocument.Styles) {

                try
                {

                    if (s.Type.Equals(Word.WdStyleType.wdStyleTypeParagraph) && s.Linked)
                    {
                        //log.Debug(s.NameLocal);
                        //log.Debug(".. linked to " + linkedS.NameLocal);

                        WrappedStyle wrapped = new WrappedStyle(s);
                        listBox1.Items.Add(wrapped);

                        if (existingStyle!=null
                            && wrapped.ToString().Equals(existingStyle.NameLocal))
                        {
                            //log.Debug(" found  " + existingStyle.NameLocal);

                            listBox1.SelectedItem = wrapped;
                        }

                    }
                }
                catch (System.Runtime.InteropServices.COMException) { }

            }

            // events click, doubleclick, mouseXXX
            //this.listBox1.SelectedIndexChanged += new System.EventHandler(listBox1_SelectedIndexChanged);
            this.listBox1.SelectedValueChanged += new System.EventHandler(listBox1_SelectedValueChanged);
        }
 public WrappedStyle(Word.Style s)
 {
     this.s = s;
 }
        public FormStyleChooser()
        {
            InitializeComponent();

            styleDefaultPFont = Globals.ThisAddIn.Application.ActiveDocument.Styles[Word.WdBuiltinStyle.wdStyleDefaultParagraphFont];

            cc = ContentControlMaker.getActiveContentControl(Globals.ThisAddIn.Application.ActiveDocument, Globals.ThisAddIn.Application.Selection);
            if (cc == null)
            {
                // Shouldn't happen
                log.Error("Which content control?");
                this.Close();
            }


            dynamic d = cc.get_DefaultTextStyle(); // actually returns the PARAGRAPH style!

            if (d == null)
            {
                // Nothing selected
                log.Error("No current style!");
            }
            else
            {
                //log.Debug(((Object)d).GetType().FullName);
                // System.__ComObject

                //string typeName = ComHelper.GetTypeName(d);
                //log.Debug(typeName);
                //Marshal.ReleaseComObject(selection);

                existingStyle = d as Word.Style;
                log.Debug(existingStyle.NameLocal); // eg Heading 6 ie the PARAGRAPH style!
            }



            foreach (Word.Style s in Globals.ThisAddIn.Application.ActiveDocument.Styles)
            {
                try
                {
                    if (s.Type.Equals(Word.WdStyleType.wdStyleTypeParagraph) && s.Linked)
                    {
                        //log.Debug(s.NameLocal);
                        //log.Debug(".. linked to " + linkedS.NameLocal);

                        WrappedStyle wrapped = new WrappedStyle(s);
                        listBox1.Items.Add(wrapped);

                        if (existingStyle != null &&
                            wrapped.ToString().Equals(existingStyle.NameLocal))
                        {
                            //log.Debug(" found  " + existingStyle.NameLocal);

                            listBox1.SelectedItem = wrapped;
                        }
                    }
                }
                catch (System.Runtime.InteropServices.COMException) { }
            }



            // events click, doubleclick, mouseXXX
            //this.listBox1.SelectedIndexChanged += new System.EventHandler(listBox1_SelectedIndexChanged);
            this.listBox1.SelectedValueChanged += new System.EventHandler(listBox1_SelectedValueChanged);
        }
Esempio n. 28
0
        private void UploadFileButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

                // Set filter for file extension and default file extension
                dlg.DefaultExt = ".doc";
                dlg.Filter     = "Word documents|*.doc;*.docx";

                // Display OpenFileDialog by calling ShowDialog method
                Nullable <bool> result = dlg.ShowDialog();



                // Get the selected file name and display in a TextBox
                if (result == true)
                {
                    //string filename = dlg.FileName;
                    //string path = System.IO.Path.GetFullPath(filename);
                    //var document = DocX.Load(filename);
                    //string content = document.Text;

                    List <string> headingsList = new List <string>();
                    List <string> heading2List = new List <string>();
                    //string myhead = headingsList.ToString();
                    //headingsList.ToArray();

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

                    Document doc = app.Documents.Open(dlg.FileName);
                    app.Application.Visible = false;

                    foreach (Microsoft.Office.Interop.Word.Paragraph paragraph in doc.Paragraphs)
                    {
                        Microsoft.Office.Interop.Word.Style style = paragraph.get_Style() as Microsoft.Office.Interop.Word.Style;
                        string styleName = style.NameLocal;
                        string text      = paragraph.Range.Text;

                        string agendaID   = agenda_id_text.Text;
                        string path       = System.IO.Path.GetFullPath(dlg.FileName);
                        string minuteName = System.IO.Path.GetFileNameWithoutExtension(path);



                        if (styleName == "Heading 1")
                        {
                            string heading1 = text.ToString() + "\n";
                            MessageBox.Show(heading1);
                            headingsList.Add(heading1);

                            headingsList.ToArray();

                            /* if (styleName == "Heading 2")
                             * {
                             *
                             *   string heading2 = text.ToString();
                             *   MessageBox.Show(heading2);
                             *   heading2List.Add(heading2);
                             *
                             *
                             * }*/
                            foreach (string head in headingsList)
                            {
                                if (heading1.Contains("Student"))
                                {
                                    string       studentQuery = $"INSERT INTO student_agenda(agenda_Id, Agenda_name, Data) VALUES ('{agendaID}','{minuteName}','{path}')";
                                    MySqlCommand student_cmd  = new MySqlCommand(studentQuery, conn);
                                    conn.Open();
                                    student_cmd.ExecuteNonQuery();
                                    conn.Close();
                                    MessageBox.Show("Uploaded successfully to Student");
                                }



                                if (heading1.Contains("Faculty"))
                                {
                                    string       facultyQuery = $"INSERT INTO faculty_agenda(agenda_Id, agenda_name, Data) VALUES ('{agendaID}','{minuteName}','{path}')";
                                    MySqlCommand faculty_cmd  = new MySqlCommand(facultyQuery, conn);
                                    conn.Open();
                                    faculty_cmd.ExecuteNonQuery();
                                    conn.Close();
                                    MessageBox.Show("Uploaded to Faculty Case");
                                }



                                if (heading1.Contains("Approval of previous minute"))
                                {
                                    string       approveQuery = $"INSERT INTO approve_agenda(agenda_Id, agenda_name, Data) VALUES ('{agendaID}','{minuteName}','{path}')";
                                    MySqlCommand approve_cmd  = new MySqlCommand(approveQuery, conn);
                                    conn.Open();
                                    approve_cmd.ExecuteNonQuery();
                                    conn.Close();
                                    MessageBox.Show("uploaded to approval");
                                }

                                if (heading1.Contains("Matters arising from previous minutes"))
                                {
                                    string       reviewQuery = $"INSERT INTO review_agenda(agenda_Id, agenda_name, Data) VALUES ('{agendaID}','{minuteName}','{path}')";
                                    MySqlCommand review_cmd  = new MySqlCommand(reviewQuery, conn);
                                    conn.Open();
                                    review_cmd.ExecuteNonQuery();
                                    conn.Close();
                                    MessageBox.Show("uploadded to review");
                                }


                                if (heading1.Contains("Staff"))
                                {
                                    string       staffQuery = $"INSERT INTO staff_agenda(agenda_Id, agenda_name, Data) VALUES ('{agendaID}','{minuteName}','{path}')";
                                    MySqlCommand staff_cmd  = new MySqlCommand(staffQuery, conn);
                                    conn.Open();
                                    staff_cmd.ExecuteNonQuery();
                                    conn.Close();
                                    MessageBox.Show("uploadded to staff");
                                }


                                if (heading1.Contains("Other matters"))
                                {
                                    string       othersQuery = $"INSERT INTO others_agenda(agenda_Id, agenda_name, Data) VALUES ('{agendaID}','{minuteName}','{path}')";
                                    MySqlCommand other_cmd   = new MySqlCommand(othersQuery, conn);
                                    conn.Open();
                                    other_cmd.ExecuteNonQuery();
                                    conn.Close();
                                    MessageBox.Show("uploadded to others");
                                }



                                /* string agendaQuery = $"INSERT INTO agenda(fagenda_id, Agenda_name, Data) VALUES ('{agendaID}','{minuteName}','{path}')";
                                 *
                                 * MySqlCommand agenda_cmd = new MySqlCommand(agendaQuery, conn);
                                 * conn.Open();
                                 * agenda_cmd.ExecuteNonQuery();
                                 * conn.Close();
                                 * MessageBox.Show("uploaded successfully in agenda");
                                 *
                                 *
                                 */
                            }



                            //MessageBox.Show(myhead);
                        }
                    }



                    //foreach (string heading in headingsList)
                    //{

                    /*if (styleName == "Heading 2")
                     * {
                     *  string heading2 = text.ToString();
                     *
                     *  //MessageBox.Show(heading2);
                     *
                     *
                     * }*/
                }
            }

            catch (Exception ex) { MessageBox.Show(ex.Message); }
            finally
            {
                conn.Close();
            }
        }