Example #1
0
        private void MakePdwWatermark(Microsoft.Office.Interop.Word.Application wApp, TemplateType templateType,
                                      Core.InternalBookmarkDomain firstDomain)
        {
            try
            {
                Microsoft.Office.Interop.Word.Selection Selection = wApp.Selection;
                Microsoft.Office.Interop.Word.Shape     wmShape;
                Selection.Select();

                // set focus on header to put watermark
                wApp.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;

                //Create the watermar shape
                wmShape = Selection.HeaderFooter.Shapes.AddTextEffect(
                    Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,
                    GenPdwWatermarkValue(templateType, firstDomain),
                    "Times New Roman", 1,
                    Microsoft.Office.Core.MsoTriState.msoFalse,
                    Microsoft.Office.Core.MsoTriState.msoFalse,
                    0, 0);

                //Set all of the attributes of the watermark
                wmShape.Select();
                wmShape.Name = PdwWaterMarkName;
                wmShape.TextEffect.NormalizedHeight = Microsoft.Office.Core.MsoTriState.msoFalse;
                wmShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
                wmShape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
                wmShape.Fill.Solid();
                wmShape.Fill.ForeColor.RGB = (int)Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
                wmShape.Fill.Transparency  = 0.5f;
                wmShape.Rotation           = GenPdwWatermarkRotation(templateType);
                wmShape.LockAspectRatio    = Microsoft.Office.Core.MsoTriState.msoTrue;
                wmShape.Height             = GenPdwWatermarkHeight(wApp, templateType);
                wmShape.Width = wApp.InchesToPoints(7.64f);
                wmShape.WrapFormat.AllowOverlap    = -1;                                                  //true
                wmShape.WrapFormat.Side            = Microsoft.Office.Interop.Word.WdWrapSideType.wdWrapBoth;
                wmShape.WrapFormat.Type            = Microsoft.Office.Interop.Word.WdWrapType.wdWrapNone; //3
                wmShape.RelativeHorizontalPosition =
                    Microsoft.Office.Interop.Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;
                wmShape.RelativeVerticalPosition =
                    Microsoft.Office.Interop.Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin;
                wmShape.Left = (float)Microsoft.Office.Interop.Word.WdShapePosition.wdShapeCenter;
                wmShape.Top  = (float)Microsoft.Office.Interop.Word.WdShapePosition.wdShapeCenter;

                //set focus back to document
                wApp.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
            }
            catch { }
        }
Example #2
0
        public void addLink(int index, string file_name)
        {
            try
            {
                Microsoft.Office.Interop.Word.Selection linkSelection = word_app.ActiveWindow.Selection;
                linkSelection.Start = 9999;
                linkSelection.End   = 9999;

                Microsoft.Office.Interop.Word.Range linkRange = linkSelection.Range;

                Microsoft.Office.Interop.Word.Hyperlinks bookmarksLinks = word_wrt.Hyperlinks;
                string file_Path       = this.created_folder + "\\" + file_name;
                object linkAddr        = file_Path;
                string single_bookmark = bookmark_list[index];
                object linkSubAddr     = single_bookmark;
                // you may need more parameters here
                Microsoft.Office.Interop.Word.Hyperlink bookmarkLink = bookmarksLinks.Add(linkRange, ref linkAddr, ref linkSubAddr);
                bookmarkLink.Range.Font.Size = 8;
                word_app.ActiveWindow.Selection.InsertAfter("\n");

                //落款
                word_wrt.Paragraphs.Last.Range.Text = "created in:" + DateTime.Now.ToString();
                //myWordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                //保存
                //myWordDoc.Save();
                //myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                //myWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                //return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                //return false;
            }
        }
Example #3
0
        //экспорт в шаблон Word
        private void button6_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("" + My.oborudovanie.ToString() );
            //if (textBox2.Text == "")
            //{
            //    MessageBox.Show("Не выбран(ы) испытатель(ли)!");
            //    return;
            //}

            //MessageBox.Show("" + My.poveritelListLength);
            //dbCon.Close();
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = new Microsoft.Office.Interop.Word.Document();
            object missing = Type.Missing;

            //Объявляем новый экземпляр класса Stopwatch
            //запускаем
            Stopwatch testStopwatch = new Stopwatch();

            testStopwatch.Start();

            if (dataGridView1.Rows.Count != 0)
            {
                object fileName   = Directory.GetCurrentDirectory() + @"\ОА\tmpl.doc";
                object falseValue = false;
                object trueValue  = true;

                doc = app.Documents.Open(ref fileName, ref missing, ref falseValue,
                                         ref missing, ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing);
                //app.Visible = true;

                //exception();
                //string[] txt = { label1.Text, DateTime.Now.ToLongDateString(), label2.Text, label3.Text, /*label4.Text,*/ label5.Text, label4.Text, label6.Text, label23.Text, label7.Text, label8.Text, label9.Text, label10.Text, label11.Text, label12.Text, /*label13.Text*/ label18.Text, label19.Text, label20.Text, label21.Text, label22.Text, label14.Text, label15.Text };
                string[] txt     = { label1.Text, label26.Text, /*DateTime.Now.ToLongDateString(),*/ label2.Text, label3.Text, /*label4.Text,*/ label5.Text, label4.Text, label6.Text, label23.Text, label7.Text, label8.Text, label9.Text, label10.Text, label11.Text, label12.Text, label13.Text /*, label18.Text, label19.Text, label20.Text, label21.Text, label22.Text*/ /*, label14.Text, label15.Text*/ };
                string[] FindObj = { "$num$", "$date$", /*"$date$",*/ "$zakazchik$", "$adress_zakazchika$", /*"$postavshik$",*/ "$name_izgotov$", "$adress_izgotov$", "$product_name$", "$product_group$", "$name$", "$proba$", "$date_time_postuplenia$", "$date_exe$", "$osnovanie$", "$nd$", "$conditions$" /*, "$temperature$", "$vlazhnost$","$davlenie$", "$elmagpole$", "$magpole$"*/ /*, "$dolznost$", "$sotrudnik$"*/ };

                int n = 0;
                while (n < FindObj.Length)
                {
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM    = FindObj[n];
                    object replaceWithNUM = txt[n];
                    object replaceNUM     = 2;

                    app.Selection.Find.Execute(ref findTextNUM, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM, ref replaceNUM, ref missing, ref missing, ref missing, ref missing);
                    n++;
                }
                n = 0;


                //string poveritelListFind = "$poveritelList$";
                for (int nn = 0; nn < My.poveritelListLength; nn++)
                {
                    if (My.poveritelList[nn] == "")
                    {
                        nn++;
                    }
                    else
                    {
                        textBox2.AppendText(My.poveritelList[nn] + "\r\r");
                    }
                }

                //Очищаем параметры поиска
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();

                //Задаём параметры замены и выполняем замену.
                object findTextNUM2    = "$poveritelList$";
                object replaceWithNUM2 = textBox2.Text;
                object replaceNUM2     = 2;

                app.Selection.Find.Execute(ref findTextNUM2, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing,
                                           ref replaceWithNUM2, ref replaceNUM2, ref missing, ref missing, ref missing, ref missing);


                //string oborudovanieListFind = "$oborudovanie$";
                for (int nn = 0; nn < My.oborudovanieListLength; nn++)
                {
                    //textBox2.AppendText(My.poveritelList[nn] + "\r\r");
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM3    = "$oborudovanie$";
                    object replaceWithNUM3 = "- " + My.oborudovanieList[nn] + ";\r$oborudovanie$";
                    object replaceNUM3     = 2;

                    app.Selection.Find.Execute(ref findTextNUM3, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM3, ref replaceNUM3, ref missing, ref missing, ref missing, ref missing);
                }

                //Задаём параметры замены и выполняем замену.
                object findTextNUM4    = "$oborudovanie$";
                object replaceWithNUM4 = "";
                object replaceNUM4     = 2;

                app.Selection.Find.Execute(ref findTextNUM4, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing,
                                           ref replaceWithNUM4, ref replaceNUM4, ref missing, ref missing, ref missing, ref missing);

                Microsoft.Office.Interop.Word.Table table = doc.Tables[2];

                int i;

                for (i = 1; i < dataGridView1.Rows.Count + 1; i++)
                {
                    table.Rows.Add();
                    table.Cell(i + 2, 1).Range.Text = i.ToString();          //нумерация

                    for (int j = 1; j < dataGridView1.ColumnCount - 1; j++)  //цикл вставки dGV
                    {
                        //table.Cell(i + 2, j + 1).Range.Text = dataGridView1.Rows[i - 1].Cells[j].Value.ToString();
                        table.Cell(i + 3, j + 1).Range.Text = dataGridView1.Rows[i - 1].Cells[j].Value.ToString();
                    }
                }

                //количество страниц/листов
                Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
                double           x    = doc.ComputeStatistics(stat, ref missing); //страницы
                string           y    = Math.Ceiling(x / 2).ToString("G17");      //листы
                //label16.Text = x.ToString("G17");

                //поиск и вставка x&y
                string[] xy     = { x.ToString("G17"), y };
                string[] Findxy = { "$x$", "$y$" };

                while (n < Findxy.Length)
                {
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM    = Findxy[n];
                    object replaceWithNUM = xy[n];
                    object replaceNUM     = 2;

                    app.Selection.Find.Execute(ref findTextNUM, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM, ref replaceNUM, ref missing, ref missing, ref missing, ref missing);
                    n++;
                }
                n = 0;

                DialogResult res = MessageBox.Show("Экспорт завершен. При нажатии ДА будет открыт сгенерированный файл, при нажатии НЕТ произойдет автоматическое сохранение файла и его открытие.", "Экспорт в Excel", MessageBoxButtons.YesNoCancel);

                if (res == DialogResult.Yes)    //открытие сгенерированного файла
                {
                    try
                    {
                        //Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ОА\tmpl.doc";
                        //object newfileName = Directory.GetCurrentDirectory() + @"\ОА\протокол №" + label1.Text + ".doc";
                        app.Visible = true;

                        //doc = app.Documents.Open(ref fileName, ref missing, ref trueValue,
                        //                         ref missing, ref missing, ref missing, ref missing, ref missing,
                        //                         ref missing, ref missing, ref missing, ref missing, ref missing,
                        //                         ref missing, ref missing, ref missing);
                        //// Закрываем родительскую форму
                        //Hide();
                        MessageBox.Show("Экспорт успешно завершен, протокол открыт. При необходимости, сохраните протокол.");

                        /*
                         * string lastNumDir = Directory.GetCurrentDirectory() + @"\ОА\последний_номер.txt";
                         * string lastNumUPD = label1.Text;
                         * System.IO.File.WriteAllText(lastNumDir, lastNumUPD);
                         */
                    }
                    catch
                    {
                        MessageBox.Show("ooooops...! что-то пошло не так. Пожалуйста обратитесь в службу поддержки");
                    }
                }

                if (res == DialogResult.No)     //автоматическое сохранение файла
                {
                    try
                    {
                        object Target  = (Directory.GetCurrentDirectory() + @"\ОА\Протоколы\" + label1.Text + ".doc"); // куда сохранить
                        object format_ = Word.WdSaveFormat.wdFormatDocumentDefault;
                        //Сохранение файла
                        doc.SaveAs(ref Target, ref format_,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing);

                        //object falseValue = false;
                        //object trueValue = true;

                        doc = app.Documents.Open(ref Target, ref missing, ref falseValue,
                                                 ref missing, ref missing, ref missing, ref missing, ref missing,
                                                 ref missing, ref missing, ref missing, ref missing, ref missing,
                                                 ref missing, ref missing, ref missing);
                        ///
                        ///колонтитулы
                        ///

                        //верний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekFirstPageHeader;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                            doc.ActiveWindow.Selection.TypeText("");
                            doc.ActiveWindow.Selection.Fields.Add(s.Range);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //верхний колонтитул
                        //остальные страницы
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                            doc.ActiveWindow.Selection.TypeText("ФБУ «Нижегородский ЦСМ» ИЦ «НИЖЕГОРОДСИСПЫТАНИЯ»          Протокол №" + label1.Text + " от " + label26.Text);
                            doc.ActiveWindow.Selection.Fields.Add(s.Range);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //нижний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            //нижний колонтитул
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            // код для номеров страницы
                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekFirstPageFooter;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                            doc.ActiveWindow.Selection.TypeText("страница ");
                            object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; //текущая страница
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref CurrentPage, ref oMissing, ref oMissing);

                            doc.ActiveWindow.Selection.TypeText(" из ");
                            object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; //всего страниц
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref TotalPages, ref oMissing, ref oMissing);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //нижний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            //нижний колонтитул
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            // код для номеров страницы
                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryFooter;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                            doc.ActiveWindow.Selection.TypeText("страница ");
                            object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; //текущая страница
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref CurrentPage, ref oMissing, ref oMissing);

                            doc.ActiveWindow.Selection.TypeText(" из ");
                            object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; //всего страниц
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref TotalPages, ref oMissing, ref oMissing);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        app.Visible = true;

                        MessageBox.Show("Экспорт успешно завершен, протокол сохранен под номером " + label1.Text);
                    }
                    catch
                    {
                        MessageBox.Show("ooooops...! что-то пошло не так. Пожалуйста обратитесь в службу поддержки");
                    }
                }

                if (res == DialogResult.Cancel) //отмена
                {
                    MessageBox.Show("Сохранение результатов экспорта отменено");
                    ((Microsoft.Office.Interop.Word._Application)app).Quit(false, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
                }
                //Останавливаем
                testStopwatch.Stop();

                //Теперь можем смотреть время выполнения операции
                TimeSpan tSpan; tSpan = testStopwatch.Elapsed;
                //MessageBox.Show("Время выполнения операции - " + tSpan.ToString()); //время выполнения операции
            }
            else
            {
                MessageBox.Show("Не открыта таблица для запроса");
            }
            exit = false;



            Hide();
            Form3 form3 = new Form3();

            form3.Show();
        }