Ejemplo n.º 1
0
    /// <summary>
    /// Button click event for submitting the entaire form data into the mail
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    protected void submitbutton_Click(object sender, EventArgs e)
    {
        // Convert text format to html format
        string text = txtformat.Text;
        string M    = Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
        string Mar  = M.Replace("&nbsp;", " ");

        string[] split = Mar.Split(new Char[] { ' ', ',', '.', ':', '\t' }, StringSplitOptions.RemoveEmptyEntries);
        string[] Sid   = M.Split(split, StringSplitOptions.RemoveEmptyEntries);
        // string filename = split[0].ToString() + ".docx";
        string dttym    = DateTime.Now.ToString("dd-MMM-yyyy") + "_" + DateTime.Now.ToString("HH-mm-ss");
        string filename = split[0].ToString() + dttym + ".docx";
        //object fileName = Server.MapPath(@".\Docs\") + filename;
        object fileName  = Server.MapPath("~/Docs/") + filename;
        object readOnly  = false;
        object isVisible = true;
        object missing   = System.Reflection.Missing.Value;

        Microsoft.Office.Interop.Word.ApplicationClass oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
        Microsoft.Office.Interop.Word.Document         oWordDoc = oWordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
        oWordDoc.Activate();
        oWordApp.Selection.TypeText(text);
        oWordApp.Selection.TypeParagraph();
        oWordDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        oWordDoc.Close(ref missing, ref missing, ref missing);
        oWordApp.Application.Quit(ref missing, ref missing, ref missing);
    }
Ejemplo n.º 2
0
        public static void PrintDocument(object filename)
        {
            WordOffice.Application wordApp = new WordOffice.Application();
            object missing = Missing.Value;

            WordOffice.Document myWordDoc = null;

            if (File.Exists((string)filename))
            {
                object readOnly  = false;
                object isVisible = false;
                wordApp.Visible = false;

                myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing,
                                                   ref missing, ref missing, ref missing, ref missing);
                myWordDoc.Activate();

                myWordDoc.Application.ActivePrinter = "PCL6 V4 Driver for Universal Print";
                myWordDoc.PrintOut();
            }
            else
            {
                MessageBox.Show("File not Found!");
            }

            myWordDoc.Close();
            wordApp.Quit();
            MessageBox.Show("File Created!");
        }
Ejemplo n.º 3
0
        private void WordMailMergeLink(string fileNameTemplate, string projectid)
        {
            MSWord.Application winword        = null;
            MSWord.Document    actualDocument = null;

            winword = new MSWord.Application();
            MSWord.Document docNew = null;

            winword.ShowAnimation = false;
            winword.Visible       = true;
            object missing = System.Reflection.Missing.Value;

            try
            {
                docNew = winword.Documents.Open(fileNameTemplate);
                docNew.Activate();
                actualDocument = docNew;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            var wrdMailMerge = actualDocument.MailMerge;

            wrdMailMerge.OpenDataSource(@"C:\ErasmDB\localDB.accdb", missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing,
                                        "SELECT * FROM [tblWordMailMerge] WHERE ProjectID='" + projectid + "'");

            actualDocument.Save();
            actualDocument.Close();
        }
Ejemplo n.º 4
0
        private void Export(List <Disassembly> dissasemblyList)
        {
            object fileName = Path.Combine(Application.StartupPath, "Templates\\template_disassembly_count.doc");

            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application {
                Visible = true
            };
            Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(fileName, ReadOnly: false, Visible: true);
            aDoc.Activate();


            FindAndReplace(wordApp, "{date}", DateTime.Today.ToString("D"));
            object missing = System.Reflection.Missing.Value;

            for (int i = 0; i < dissasemblyList.Count; i++)
            {
                aDoc.Tables[1].Rows.Add(ref missing);
                aDoc.Tables[1].Rows[i + 2].Range.Bold          = 0;
                aDoc.Tables[1].Rows[i + 2].Range.Font.Size     = 10;
                aDoc.Tables[1].Rows[i + 2].Cells[1].Range.Text = (i + 1).ToString();
                aDoc.Tables[1].Rows[i + 2].Cells[2].Range.Text = dissasemblyList[i].Date;
                aDoc.Tables[1].Rows[i + 2].Cells[3].Range.Text = dissasemblyList[i].Address;
                aDoc.Tables[1].Rows[i + 2].Cells[4].Range.Text = dissasemblyList[i].CountDisassembly.ToString();
                aDoc.Tables[1].Rows[i + 2].Cells[5].Range.Text = dissasemblyList[i].CountInstall.ToString();
            }
        }
Ejemplo n.º 5
0
        public static void InWord(IEnumerable <Tuple <string, string> > res, string relativeSource)
        {
            try
            {
                Word.Application app    = new Word.Application();
                string           source = AppDomain.CurrentDomain.BaseDirectory + relativeSource;
                Word.Document    doc    = app.Documents.Add(source);
                doc.Activate();
                Word.Bookmarks bookmarks = doc.Bookmarks;

                StringBuilder result = new StringBuilder();

                foreach (var b in res)
                {
                    result.AppendLine(b.Item1);
                    result.AppendLine(b.Item2);
                }

                bookmarks["Results"].Range.Text    = result.ToString();
                bookmarks["Name"].Range.Text       = StaticParameters.User.Name;
                bookmarks["SecondName"].Range.Text = StaticParameters.User.SecondName;

                app.PrintOut(Range: Word.WdPrintOutRange.wdPrintAllDocument);
            }
            catch
            {
                MessageBox.Show("Произошла ошибка с печатью документа");
            }
        }
Ejemplo n.º 6
0
        public void leerWord(String fileName)
        {
            //variable para representar variables perdidas cuando
            //se llamen metodos mediante el interop.
            object missing = System.Reflection.Missing.Value;

            //preparamos la clase Word
            Word.Application wordApp =
                new Word.Application();
            //preparamos la clase documento de word
            Word.Document doc       = null;
            object        readOnly  = false;
            object        isVisible = false;

            //ponemos la aplicacion word invisible
            wordApp.Visible = false;
            //obtenemos la ruta del archivo word
            object ruta = fileName;

            //abrimos el archivo word
            doc = wordApp.Documents.Open(ref ruta, ref missing, ref readOnly, ref missing,
                                         ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref isVisible, ref missing, ref missing,
                                         ref missing, ref missing);

            //activamos el archivo word
            doc.Activate();
            //obtenemos el texto del archivo
            String data = doc.Content.Text.ToString();

            //cerramos el archivo
            doc.Close(ref missing, ref missing, ref missing);
        }
Ejemplo n.º 7
0
        public void processWord(string saved_path, bool newSmry)
        {
            word_app = createWordApp();
            this.insertBookmark(saved_doc_list);
            object strFileName = saved_path;
            Object Nothing     = System.Reflection.Missing.Value;
            object readOnly    = false;
            object isVisible   = false;

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

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

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

            word_app  = null;
            word_show = null;
        }
Ejemplo n.º 8
0
        // Create the Doc Method
        public static void CreateWordDocument(object filename, object SaveAs, int copies)
        {
            // the instance of word
            Word.Application wordApp   = new Word.Application();
            Word.Document    myWordDoc = null;
            wordApp.Visible = true;

            if (!File.Exists((string)filename))
            {
                throw new IOException("File not Found!");
            }

            for (int i = 1; i <= copies; i++)
            {
                // The passed in document
                myWordDoc = wordApp.Documents.Open(ref filename);

                myWordDoc.Activate();

                //find and replace ---------------------------------------------------------
                SerialNumber oldNum = new SerialNumber(WhatToFind(myWordDoc));
                FindAndReplace(wordApp, oldNum.ToString(), oldNum.Increment(i).ToString());

                //Save as
                object name = (string)SaveAs + i;
                myWordDoc.SaveAs2(ref name);

                myWordDoc.Close();
            }
            wordApp.Quit();
            MessageBox.Show("Success!");
        }
Ejemplo n.º 9
0
        private void btn_hrm_res_resignation_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

            OpenFileDialog open = new OpenFileDialog();

            if (open.ShowDialog() == DialogResult.OK)
            {
                object fileName  = open.FileName;
                object readOnly  = true;
                object isVisible = true;
                object missing   = System.Reflection.Missing.Value;

                wordApp.Visible = true;
                Word.Document newDoc = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly,
                                                              ref missing, ref missing, ref missing,
                                                              ref missing, ref missing, ref missing,
                                                              ref missing, ref missing, ref isVisible);

                newDoc.Activate();
                this.FindAndReplace(wordApp, "<name>", txt_flname.Text);
                this.FindAndReplace(wordApp, "<address>", lbl_fullAdd.Text);
                this.FindAndReplace(wordApp, "<join_date>", txt_joinDate.Text);
                this.FindAndReplace(wordApp, "<position>", txt_position.Text);
                this.FindAndReplace(wordApp, "<date>", DateTime.Now.ToShortDateString());
            }
        }
Ejemplo n.º 10
0
        private static Word.Range Open(object path)
        {
            Object misObj   = Missing.Value;
            Object trueObj  = true;
            Object falseObj = false;

            app = new Word.Application();
            try
            {
                doc = app.Documents.Add(ref path, ref misObj, ref misObj, ref misObj);
                Word.Range ra = doc.Range();
                Console.WriteLine("Открываем");
                doc.Activate();
                Console.WriteLine("Активируем");
                //Переделать в шаблон
                doc = app.Documents.Open(path);
                doc = app.Documents.Add(ref path, ref misObj, ref misObj, ref misObj);
                return(doc.Range());
            }
            catch (Exception exp)
            {
                Close();
                Console.WriteLine("Файл не найден или произошла ошибка чтения файла. Проверьте файл" +
                                  "конфигурации.");
                Console.WriteLine("Ошибка: " + exp.Message);
                return(null);
            }
        }
Ejemplo n.º 11
0
        public void OpentoSignMethod(object FilePath)
        {
            Word.Application wordApp    = new Word.Application();
            Word.Document    myDocument = null;

            object missing   = Missing.Value;
            object ReadOnly  = false;
            object isVisible = true;

            wordApp.Visible = true;

            object saveChange = Word.WdSaveOptions.wdDoNotSaveChanges;

            try
            {
                myDocument = wordApp.Documents.Open(ref FilePath, ref missing, ref ReadOnly, ref missing,
                                                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                                    ref isVisible, ref missing, ref missing, ref missing, ref missing);

                myDocument.Activate();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                myDocument.Close(saveChange, missing, missing);
                wordApp.Quit();
            }
        }
Ejemplo n.º 12
0
 void KeepNewWindowActivated(Word.Document Doc, Word.Window Wn)
 {
     if (newDoc == Doc)
     {
         Doc.Activate();
     }
 }
Ejemplo n.º 13
0
        public static void WriteOlympicIntoWordFile(string Subject, string Content)
        {
            string filePath = string.Join(@"\", AppConstants.DiskToDocs, AppConstants.ProjectDirectory, AppConstants.OlympicDirectory);

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = string.Join(@"\", filePath, $"Олимпиада_{Subject}.doc");

            Word.Application app      = new Word.Application();
            object           oMissing = System.Reflection.Missing.Value;

            Word.Document doc = app.Documents.Add();
            doc.Activate();

            doc.Content.Font.Bold = 1;
            doc.Content.Font.Size = 14;
            doc.Content.Font.Name = "Times New Roman";
            Word.Paragraph oPara0;
            oPara0 = doc.Content.Paragraphs.Add(ref oMissing);
            oPara0.Range.Font.Size = 18;
            oPara0.Range.Text      = $"ВОШ. {Subject}";
            oPara0.Range.InsertParagraphAfter();

            Word.Paragraph oPara1;
            oPara1 = doc.Content.Paragraphs.Add(ref oMissing);

            oPara1.Range.Text = Content;

            doc.SaveAs2(filePath);
            doc.Close();
        }
 public override object OpenFile(ISiteSetting siteSetting, string filePath)
 {
     if (siteSetting.UseClaimAuthentication == true)
     {
         string url = siteSetting.Url + "/_layouts/WordViewer.aspx?id=" + filePath.Replace(siteSetting.Url, string.Empty);
         //http://muratteknik.sharepoint.com/TeamSite/Functions/Tax/_layouts/WordViewer.aspx?id=/TeamSite/Functions/Tax/Weekly%20Reports/test/testttt.docx
         Process.Start("IEXPLORE.EXE", url);
         return(null);
     }
     else
     {
         // set the file name from the open file dialog
         object fileName             = filePath;
         object readOnly             = false;
         object isVisible            = true;
         object confirmConversations = true;
         // Here is the way to handle parameters you don't care about in .NET
         object missing = System.Reflection.Missing.Value;
         // Make word visible, so you can see what's happening
         // Open the document that was chosen by the dialog
         Word.Document doc = this.WordApplication.Documents.Open(ref fileName, ref confirmConversations, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
         // Activate the document so it shows up in front
         doc.Activate();
         return(doc);
     }
 }
Ejemplo n.º 15
0
 public WordDocument(string docPath, string archivo, string temporal)
 {
     try{
         temporal = "\\" + temporal;
         File.Copy(docPath + archivo, docPath + temporal, true);
         docPath  = docPath + temporal;
         wordApp  = new Word.Application();
         filename = Path.Combine(docPath);
         if (File.Exists((string)filename))
         {
             object readOnly  = false;
             object isVisible = false;
             wordApp.Visible = false;
             aDoc            = wordApp.Documents.Open(ref filename, ref missing,
                                                      ref readOnly, ref missing, ref missing, ref missing,
                                                      ref missing, ref missing, ref missing, ref missing,
                                                      ref missing, ref isVisible, ref missing, ref missing,
                                                      ref missing, ref missing);
             aDoc.Activate();
         }
         else
         {
             MessageBox.Show("El archivo no existe.", "Sin archivo", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
     }
     catch (Exception ex) {
         MessageBox.Show("Error durante el proceso. Descripcion: " + ex.Message, "Error Interno", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Ejemplo n.º 16
0
        public static void WriteFiltersResultIntoFile(string line)
        {
            string filePath = string.Join(@"\", AppConstants.DiskToDocs, AppConstants.ProjectDirectory, AppConstants.FiltersDirectory);

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = string.Join(@"\", filePath, AppConstants.FiltersFile);

            Word.Application app = new Word.Application();
            //object docPath = filePath;
            object oMissing = System.Reflection.Missing.Value;

            Word.Document doc = app.Documents.Add();
            doc.Activate();

            doc.Content.Font.Bold = 1;
            doc.Content.Font.Size = 14;
            doc.Content.Font.Name = "Times New Roman";
            Word.Paragraph oPara1;
            oPara1 = doc.Content.Paragraphs.Add(ref oMissing);

            oPara1.Range.Text = line;

            doc.SaveAs2(filePath);
            doc.Close();
        }
Ejemplo n.º 17
0
Archivo: Word.cs Proyecto: Zagii/EAkzg
        object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

        public Word(String plikSzablonu, String plikHLD, bool widoczna = true)
        {
            fileToOpen = plikSzablonu;
            fileToSave = plikHLD;
            //missing oject to use with various word commands
            missing = System.Reflection.Missing.Value;


            //Create new instance of word and create a new document
            wordApp = new Wordy.Application();
            // doc = null;

            //Settings the application to invisible, so the user doesn't notice that anything is going on
            wordApp.Visible = widoczna;

            //Open and activate the chosen template
            doc = wordApp.Documents.Open(ref fileToOpen, ref missing,
                                         ref readOnly, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref isVisible, ref missing, ref missing,
                                         ref missing, ref missing);

            doc.Activate();
            doc.SpellingChecked = false;

            sprawdzajPisownie  = doc.ShowSpellingErrors;
            sprawdzajGramatyke = doc.ShowGrammaticalErrors;

            doc.ShowGrammaticalErrors = false;
            doc.ShowSpellingErrors    = false;
        }
Ejemplo n.º 18
0
    /// </summary>
    public void ConvertDOCtoPDF(int InterviewID, string PathToWordDocWithFileName, string PathToPDFWithFileName)
    {
        object misValue = System.Reflection.Missing.Value;

        try
        {
            WORD = new Word.Application();

            PathToWordDocWithFileName = PathToWordDocWithFileName.Replace(".docx", "") + InterviewID + ".docx";
            doc = WORD.Documents.Open(PathToWordDocWithFileName);
            doc.Activate();
            //Extract fields from PDF

            PathToPDFWithFileName = PathToPDFWithFileName.Replace(".pdf", "") + InterviewID + ".pdf";
            doc.SaveAs2(PathToPDFWithFileName, Word.WdSaveFormat.wdFormatPDF, misValue, misValue, misValue,
                        misValue, misValue, misValue, misValue, misValue, misValue, misValue);
            System.Console.WriteLine($"{InterviewID} Report saved successfully as PDF after conversion.");
        }
        catch (Exception e) { System.Console.WriteLine("Error Occurred " + e); }
        finally
        {
            doc.Close();
            WORD.Quit();
            releaseObject(doc);
            releaseObject(WORD);
        }
    }
Ejemplo n.º 19
0
        public void WordMarks(string filename, string currDir, string mark1, string mark2, string mark3, string mark4, string mark5, string group, string parent)
        {
            db  = new UseDataBase();
            app = new Word.Application();
            doc = app.Documents.Add(currDir);
            doc.Activate();
            wBookmarks = doc.Bookmarks;
            dt         = new DataTable();
            dt         = db.SQLQuery("SELECT Teachers.FIO FROM Teachers INNER JOIN Groups ON Groups.idTeacher = Teachers.idTeacher where Groups.Name = '" + mark5 + "'");
            string teacherFio = dt.Rows[0][0].ToString();

            data = new string[5] {
                mark1, mark2, mark3, mark4, teacherFio
            };
            foreach (Microsoft.Office.Interop.Word.Bookmark mark in wBookmarks)
            {
                wRange      = mark.Range;
                wRange.Text = data[i];
                i++;
            }
            i         = 0;
            filename += "_" + group + "_" + parent;
            doc.SaveAs(FileName: (Environment.CurrentDirectory + @"\report\" + filename));
            string path = Environment.CurrentDirectory + @"\report\" + filename + ".docx";

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

            dt = db.SQLQuery("SELECT DISTINCT Parents.Email FROM Parents, Groups INNER JOIN ParentsSudents ON ParentsSudents.idParent = Parents.idParent INNER JOIN Students ON Students.idGroup = Groups.idGroup AND ParentsSudents.idStudent = Students.idStudent WHERE Groups.Name = '" + group + "' and Parents.FIO = '" + parent + "'");
            string ParentEmail = dt.Rows[0][0].ToString();

            mail = new SendAnEmail();
            mail.MultiMessage(ParentEmail, "Уведомление от РКРИПТ", "", @path);
        }
Ejemplo n.º 20
0
        private void Open(string tempDoc)
        {
            object objTempDoc = tempDoc;
            object objMissing = System.Reflection.Missing.Value;

            objDocLast = objApp.Documents.Open(
                ref objTempDoc, //FileName
                ref objMissing, //ConfirmVersions
                ref objMissing, //ReadOnly
                ref objMissing, //AddToRecentFiles
                ref objMissing, //PasswordDocument
                ref objMissing, //PasswordTemplate
                ref objMissing, //Revert
                ref objMissing, //WritePasswordDocument
                ref objMissing, //WritePasswordTemplate
                ref objMissing, //Format
                ref objMissing, //Enconding
                ref objMissing, //Visible
                ref objMissing, //OpenAndRepair
                ref objMissing, //DocumentDirection
                ref objMissing, //NoEncodingDialog
                ref objMissing  //XMLTransform
                );
            objDocLast.Activate();
        }
Ejemplo n.º 21
0
        private void button1_Click(object sender, EventArgs e)
        {
            Word.Document wd = new Word.Document();
            wd.Activate();
            Object start = Type.Missing;
            Object end   = Type.Missing;

            Word.Range rng = wd.Range(ref start, ref end);
            Object     defaultTableBehavior = Type.Missing;
            Object     autoFitBehavior      = Type.Missing;
            object     missing = System.Type.Missing;

            Word.Table tbl = wd.Tables.Add(rng, 1, 7, ref missing, ref missing);
            SetHeadings(tbl.Cell(1, 1), "Title 1");
            SetHeadings(tbl.Cell(1, 2), "Title 2");
            SetHeadings(tbl.Cell(1, 3), "Title 3");
            SetHeadings(tbl.Cell(1, 4), "Title 4");
            SetHeadings(tbl.Cell(1, 5), "Title 5");
            SetHeadings(tbl.Cell(1, 6), "Title 6");
            SetHeadings(tbl.Cell(1, 7), "Title 7");
            for (int i = 0; i < lecturerData.Rows.Count; i++)
            {
                Word.Row newRow = wd.Tables[1].Rows.Add(ref missing);
                newRow.Range.Font.Bold = 0;
                newRow.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                newRow.Cells[1].Range.Text             = lecturerData.Rows[i][0].ToString();
                newRow.Cells[2].Range.Text             = lecturerData.Rows[i][1].ToString();
                newRow.Cells[3].Range.Text             = lecturerData.Rows[i][2].ToString();
                newRow.Cells[4].Range.Text             = lecturerData.Rows[i][3].ToString();;
                newRow.Cells[5].Range.Text             = lecturerData.Rows[i][4].ToString();
                newRow.Cells[6].Range.Text             = lecturerData.Rows[i][5].ToString();
                newRow.Cells[7].Range.Text             = lecturerData.Rows[i][6].ToString();
            }
        }
Ejemplo n.º 22
0
        public void SaveAsPDF()
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object oMissing = System.Reflection.Missing.Value;
            // Cast as Object for word Open method

            Object filename = (Object)_filename;

            Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(ref filename, ref oMissing,
                                                                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                                             ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            doc.Activate();

            object outputFileName = _filename.Replace(".docx", ".pdf");
            object fileFormat     = WdSaveFormat.wdFormatPDF;

            // Save document into PDF Format
            doc.SaveAs(ref outputFileName,
                       ref fileFormat, ref oMissing, ref oMissing,
                       ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                       ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                       ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            object saveChanges = WdSaveOptions.wdDoNotSaveChanges;

            ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
            doc = null;

            // word has to be cast to type _Application so that it will find
            // the correct Quit method.
            ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
            word = null;
        }
Ejemplo n.º 23
0
        public void Open(string path)
        {
            application = new Word.Application();
            Word.Options opt         = application.Options;
            string       defaultPath = opt.DefaultFilePath[Word.WdDefaultFilePath.wdDocumentsPath];

            application.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll;
            application.Visible       = true;

            if (string.IsNullOrEmpty(path))
            {
                document = application.Documents.Add(!string.IsNullOrEmpty(path) ? (object)path : Missing.Value);
                document.Activate();
            }
            else
            {
                if (string.IsNullOrEmpty(Path.GetDirectoryName(path)))
                {
                    path = defaultPath + "\\" + path;
                }
                document = application.Documents.Open(path);
                document.Activate();
            }
            this.path = path;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Creates a copy of the current document.
        /// </summary>
        /// <param name="InputDocument">The document to clone.</param>
        /// <returns>A Document representing the cloned document.</returns>
        internal static Word.Document CloneDocument(Word.Document InputDocument)
        {
            object Missing        = Type.Missing;
            object NormalTemplate = InputDocument.Application.NormalTemplate;
            object TempFile       = Path.GetTempFileName();

            //copy this document into a temp file and open it
            using (StreamWriter sw = new StreamWriter((string)TempFile))
            {
                sw.Write(InputDocument.WordOpenXML);
            }
            Word.Document FileToRedact = InputDocument.Application.Documents.Add(ref TempFile, ref Missing, ref Missing, ref Missing);

            //clear the dummy template reference and move focus
            FileToRedact.set_AttachedTemplate(ref NormalTemplate);
            FileToRedact.Activate();

            //if track changes was on, turn it off
            FileToRedact.TrackRevisions = false;

            //bug 5862: lock all fields in the document body, since we shouldn't have them in the redacted copy
            FileToRedact.Fields.Unlink();

            return(FileToRedact);
        }
        public static void InWord(Dictionary <string, string> dict, string path)
        {
            if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + path))
            {
                MessageBox.Show($"Файл шаблона ({AppDomain.CurrentDomain.BaseDirectory + path}) не найден");
            }
            try
            {
                Word.Application app    = new Word.Application();
                string           source = AppDomain.CurrentDomain.BaseDirectory + path;
                Word.Document    doc    = app.Documents.Add(source);
                doc.Activate();
                Word.Bookmarks bookmarks = doc.Bookmarks;

                foreach (var b in dict)
                {
                    bookmarks[b.Key].Range.Text = b.Value;
                }

                app.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Произошла ошибка");
            }
        }
Ejemplo n.º 26
0
        public void PastTest()
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.ApplicationClass();
            app.Visible = false;
            Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(@"C:\Users\Administrator\Desktop\WorkFiles\Letter Automation\Template\NewTemplate\(chi) Cancellation of PW1.doc", false);

            doc.Activate();

            doc.Tables[2].Cell(2, 2).Range.FormFields[1].Result = "44444444";
            int count = doc.FormFields.Count;

            doc.Tables[1].ConvertToText(WdTableFieldSeparator.wdSeparateByParagraphs, false);
            doc.Tables[2].Cell(1, 3).Range.Text = "33";
            doc.Tables[3].Rows.Add();
            object unite = WdUnits.wdStory;

            app.Selection.EndKey(ref unite, Type.Missing); //将光标移动到文档末尾
            doc.Tables[3].Rows[1].Cells[1].Range.Paste();
            doc.Tables[3].Rows.Add();

            doc.Protect(WdProtectionType.wdAllowOnlyFormFields, true, Type.Missing, Type.Missing, true);
            doc.Save();
            doc.Save();
            doc.Close();
            app.Quit();
        }
Ejemplo n.º 27
0
        public CounterData getCounters(String filePath)
        {
            CounterData counters = new CounterData {
                wordCount = 0, charCount = 0, paraCount = 0, pageCount = 0
            };
            string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);

            log.Info("Counting " + fileName);
            Microsoft.Office.Interop.Word.Application word = null;
            Microsoft.Office.Interop.Word.Document    doc  = null;

            object missing     = Type.Missing;
            object saveChanges = false;
            object includeFootnotesAndEndnotes = true;

            Microsoft.Office.Interop.Word.WdStatistic wordStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticWords;
            Microsoft.Office.Interop.Word.WdStatistic charStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticCharacters;
            Microsoft.Office.Interop.Word.WdStatistic paraStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticParagraphs;
            Microsoft.Office.Interop.Word.WdStatistic pageStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;

            try
            {
                word = new Microsoft.Office.Interop.Word.Application();
                doc  = new Microsoft.Office.Interop.Word.Document();
                object objFilePath = @filePath;

                /*
                 * Document OpenNoRepairDialog(ref Object FileName,
                 *          ref Object ConfirmConversions, ref Object ReadOnly, ref Object AddToRecentFiles, ref Object PasswordDocument,
                 *      ref Object PasswordTemplate, ref Object Revert, ref Object WritePasswordDocument, ref Object WritePasswordTemplate,
                 *          ref Object Format, ref Object Encoding, ref Object Visible, ref Object OpenAndRepair,
                 *          ref Object DocumentDirection, ref Object NoEncodingDialog, ref Object XMLTransform
                 *  )
                 */
                doc = word.Documents.OpenNoRepairDialog(ref objFilePath,
                                                        ref missing, true, 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);
                if (doc != null)
                {
                    doc.Activate();

                    counters.wordCount = doc.ComputeStatistics(wordStats, ref includeFootnotesAndEndnotes);
                    counters.charCount = doc.ComputeStatistics(charStats, ref includeFootnotesAndEndnotes);
                    counters.paraCount = doc.ComputeStatistics(paraStats, ref includeFootnotesAndEndnotes);
                    counters.pageCount = doc.ComputeStatistics(pageStats, ref includeFootnotesAndEndnotes);
                    log.Info(counters);
                }
                //doc.Save();
                word.Quit(ref saveChanges, ref missing, ref missing);
            }
            catch (Exception ex)
            {
                word.Quit(ref saveChanges, ref missing, ref missing);
                log.Error(ex);
            }

            return(counters);
        }
Ejemplo n.º 28
0
        public void FindAndReplace(object ToFindText, object replaceWithText)
        {
            object matchCase       = true;
            object matchWholeWord  = true;
            object matchWildCards  = false;
            object matchSoundLike  = false;
            object nmatchAllforms  = false;
            object forward         = true;
            object format          = false;
            object matchKashida    = false;
            object matchDiactitics = false;
            object matchAlefHamza  = false;
            object matchControl    = false;
            object replace         = 2;
            object wrap            = 1;

            WordDocx.Activate();

            wordApp.Selection.Find.Execute(ref ToFindText,
                                           ref matchCase, ref matchWholeWord,
                                           ref matchWildCards, ref matchSoundLike,
                                           ref nmatchAllforms, ref forward,
                                           ref wrap, ref format, ref replaceWithText,
                                           ref replace, ref matchKashida,
                                           ref matchDiactitics, ref matchAlefHamza,
                                           ref matchControl);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Opens the original word file and initializes the Word.Document object.
        /// The original file may be HTML, DOC, DOCX, or RTF
        /// </summary>
        private void OpenWordDoc()
        {
            object fileNameAsObj     = m_originalFileName;
            object readOnly          = false;
            object addToRecentFiles  = false;
            object isVisible         = true;
            object confirmConversion = false;
            object noEncodingDialog  = true;
            object missing           = System.Reflection.Missing.Value;

            m_wordDoc = m_wordApp.Documents.OpenNoRepairDialog(
                ref fileNameAsObj, ref confirmConversion, ref readOnly,
                ref addToRecentFiles, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref isVisible,
                ref missing, ref missing, ref noEncodingDialog, ref missing);

            m_wordDoc.Activate();

            try
            {
                m_wordDoc.WebOptions.Encoding     = Office_Core.MsoEncoding.msoEncodingUTF8;
                m_wordDoc.WebOptions.BrowserLevel =
                    Word_Class.WdBrowserLevel.wdBrowserLevelMicrosoftInternetExplorer5;
                m_wordDoc.WebOptions.OptimizeForBrowser = false;
            }
            catch (Exception ex)
            {
                m_log.Log("[Warn] Get web options of word document failed : " + ex.ToString());
            }
        }
Ejemplo n.º 30
0
        private void generateSemesterTitle()
        {
            String path = Environment.CurrentDirectory + "\\SemesterTitle.dotx";

            Word.Application app = new Word.Application();
            // Создаём объект документа
            Word.Document doc = app.Documents.Add(path);
            doc.Activate();

            doc.Bookmarks["NAME"].Range.Text            = textName.Text;
            doc.Bookmarks["DIRECTION"].Range.Text       = textCathedra.Text;
            doc.Bookmarks["FACULTY"].Range.Text         = textFaculty.Text;
            doc.Bookmarks["GROUP"].Range.Text           = textGroup.Text;
            doc.Bookmarks["PROFESSOR"].Range.Text       = textProfessor.Text;
            doc.Bookmarks["SUBJECT"].Range.Text         = textSubject.Text;
            doc.Bookmarks["SUBJECT_LESSONS"].Range.Text = textDiscipline.Text;
            doc.Bookmarks["YEAR"].Range.Text            = numYear.Value.ToString();


            doc.SaveAs(FileName: Environment.CurrentDirectory + "\\" + textName.Text + "_" + textDiscipline.Text + ".docx");
            doc.Close();

            MessageBox.Show("Файл " + textName.Text + "_" + textDiscipline.Text + ".docx успешно сгенерирован!",
                            "Успех",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxOptions.DefaultDesktopOnly);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// 调用模板生成word
        /// </summary>
        /// <param name="templateFile">模板文件</param>
        /// <param name="fileName">生成的具有模板样式的新文件</param>
        public void ExportWord(string templateFile, string fileName)
        {
            try
               {
                   #region 生成word应用程序对象
                   //生成word程序对象
                   object obj = System.Reflection.Missing.Value;
                   Word.Application app = new Word.Application();

                   //模板文件
                   string TemplateFile = templateFile;

                   //生成的具有模板样式的新文件
                   string FileName = fileName;

                   //模板文件拷贝到新文件
                   File.Copy(TemplateFile, FileName);

                   //生成documnet对象
                   //Word.Document doc=app.Documents.Add(ref obj,ref obj,ref obj,ref,obj,ref obj);
                   Word.Document doc = new Word.Document();
                   object Obj_FileName = FileName;
                   object Visible = false;
                   object ReadOnly = false;
                   object missing = System.Reflection.Missing.Value;

                   //打开文件
                   doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                       ref missing, ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing, ref Visible,
                       ref missing, ref missing, ref missing,
                       ref missing);
                   doc.Activate();
                   #endregion

                   //声明书签数组
                   object[] BookMark = new object[100];

                   //赋值书签名
                   BookMark[0] = "lb0001";
                   BookMark[1] = "lb0002";
                   BookMark[2] = "lb0003";
                   BookMark[3] = "lb0004";
                   BookMark[4] = "lb0005";
                   BookMark[5] = "lb0006";
                   BookMark[6] = "lb0007";
                   BookMark[7] = "lb0008";
                   BookMark[8] = "tb001";
                   BookMark[9] = "tb002";
                   BookMark[10] = "tb003";
                   BookMark[11] = "tb004";
                   BookMark[12] = "tb005";
                   BookMark[13] = "tb006";
                   BookMark[14] = "tb007";
                   BookMark[15] = "tb008";
                   BookMark[16] = "tb009";
                   BookMark[17] = "tb010";
                   BookMark[18] = "tb011";
                   BookMark[19] = "tb012";
                   BookMark[20] = "tb013";
                   BookMark[21] = "tb014";
                   BookMark[22] = "tb015";
                   BookMark[23] = "tb016";
                   BookMark[24] = "tb017";
                   BookMark[25] = "tb018";

                   //赋值任意数据到书签的位置
                   string str = "大同333";
                   doc.Bookmarks.get_Item(ref BookMark[0]).Range.Text = "7788";
                   doc.Bookmarks.get_Item(ref BookMark[1]).Range.Text = str;
                   doc.Bookmarks.get_Item(ref BookMark[2]).Range.Text = "50";
                   doc.Bookmarks.get_Item(ref BookMark[3]).Range.Text = "2号";
                   doc.Bookmarks.get_Item(ref BookMark[4]).Range.Text = "6";
                   doc.Bookmarks.get_Item(ref BookMark[5]).Range.Text = "200";

                   //添加图片
                   doc.Bookmarks.get_Item(ref BookMark[7]).Select();
                   app.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                   app.Selection.InlineShapes.AddPicture(@"E:\dzy\picture\12.png", ref missing, ref missing, ref missing);

                   ////判断指定的图片是否存在
                   //if (File.Exists(@"..\..\sources\images\12.png"))
                   //{
                   //    File.Delete(@"..\..\sources\images\12.png");
                   //}

                   #region 表格操作
                   //文档中创建表格
                   Range range = doc.Bookmarks.get_Item(ref BookMark[25]).Range;//表格插入位置
                   Word.Table newTable = doc.Tables.Add(range, 12, 3, ref missing, ref missing);

                   //设置表格样式
                   newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
                   newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
                   newTable.Columns[1].Width = 100f;
                   newTable.Columns[2].Width = 220f;
                   newTable.Columns[3].Width = 105f;

                   //填充表格内容
                   newTable.Cell(1, 1).Range.Text = "产品详细信息表";
                   newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体

                   //合并单元格
                   newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
                   //app.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
                   //app.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

                   //填充表格内容
                   newTable.Cell(2, 1).Range.Text = "产品基本信息";
                   newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色

                   //合并单元格
                   newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
                   //app.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                   //填充表格内容
                   newTable.Cell(3, 1).Range.Text = "品牌名称:";
                   newTable.Cell(3, 2).Range.Text = "品牌产地";

                   //纵向合并单元格
                   newTable.Cell(3, 3).Select();//选中一行
                   object moveUnit = Word.WdUnits.wdLine;
                   object moveCount = 5;
                   object moveExtend = Word.WdMovementType.wdExtend;
                   app.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
                   app.Selection.Cells.Merge();
                   newTable.Cell(12, 1).Range.Text = "产品特殊属性";
                   newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));

                   //在表格中增加行
                   doc.Content.Tables[1].Rows.Add(ref missing);

                   //“落款”
                   doc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();
                   doc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            #endregion

                   //输出数据到表格
                   string sql = "select * from 工作面信息表";
                   DataTable dt = db.Query(sql);
                   for (int i = 0; i < dt.Rows.Count; i++)
                   {
                       DataRow dr = dt.Rows[i];
                       string mm = dr["支架柱数"].ToString();
                       doc.Bookmarks.get_Item(ref BookMark[i + 9]).Range.Text = mm;

                   }

                   //输出完毕后关闭doc对象
                   object IsSave = true;
                   doc.Close(ref IsSave, ref missing, ref missing);

                   MessageBox.Show("生成“" + FileName + "”成功!");
               }

               catch (Exception Ex)
               {
                   MessageBox.Show(Ex.ToString());
                   return;
               }
        }
Ejemplo n.º 32
0
        // Open a file (the file must exists) and activate it
        public void Open( string strFileName)
        {
            object fileName = strFileName;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            oDoc = oWordApplic.Documents.Open(ref fileName, ref missing,ref readOnly,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref isVisible,ref missing,ref missing,ref missing,ref missing);

            oDoc.Activate();
        }
Ejemplo n.º 33
0
        public void createTCWidthDocument()
        {
            List<List<string>> joistDataByMark = arrangedJoistDataByMark();

            Word.Application wordApp = new Word.Application();
            wordApp.Visible = false;

            Word.Document wordDoc = new Word.Document();

            wordDoc.Activate();

            wordDoc.Paragraphs.SpaceAfter = 0;
               ///
            Word.Selection selection = wordApp.Application.Selection;

            selection.Font.Name = "Calibri";
            selection.Font.Size = 11;
            selection.Font.Bold = 1;

            Word.Section section = selection.Sections.Add();

            Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;

            string jobNumber = joistDataByMark[0][6];

            string[] jobNumberArray = jobNumber.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);

            jobNumber = jobNumberArray[0] + "-" + jobNumberArray[1];

            headerRange.Text = "TOP CHORD WIDTHS: "+ joistDataByMark[0][5]  + " [NMBS: " + jobNumber + "]" + "     " + joistDataByMark[0][7] +
                "\r\n\r\n" + "  MARK         QUANTITY      DESCRIPTION              BASE LENGTH        TC WIDTH";

            Word.Range footerRange = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            footerRange.Fields.Add(footerRange, Word.WdFieldType.wdFieldPage);
            footerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

            selection.HomeKey(Word.WdUnits.wdStory, 0);
            //selection.Text = "TOP CHORD WIDTHS: \r\n";

               // selection.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
               // selection.MoveDown(Word.WdUnits.wdLine, 1);

            selection.Font.Bold = 0;

            Word.Table tableTCWidths = wordApp.ActiveDocument.Tables.Add(selection.Range,joistDataByMark.Count()+1,5);

            tableTCWidths.Cell(1, 1).Range.Text = "";
            tableTCWidths.Cell(1, 2).Range.Text = "";
            tableTCWidths.Cell(1, 3).Range.Text = "";
            tableTCWidths.Cell(1, 4).Range.Text = "";
            tableTCWidths.Cell(1, 5).Range.Text = "";

            for (int i = 1; i <= 5; i++)
            {
                tableTCWidths.Cell(1, i).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                //tableTCWidths.Cell(1, i).Range.Underline = Word.WdUnderline.wdUnderlineSingle;
                tableTCWidths.Cell(1, i).Range.Font.Bold = 1;
                //    tableNailBackSheetTitle.Cell(i,1).Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
            }

            int rowcounter = 0;
            int numRows = joistDataByMark.Count()+1;
            for (int row = 2; row <= numRows; row++)
            {
                for (int col = 1; col<=5; col++)
                {

                    tableTCWidths.Cell(row, col).Range.Text = joistDataByMark[row - 2][col - 1];

                }
            }

            for (int i = 1; i <= 4; i++)
            {
                    tableTCWidths.Cell(i, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            }

            tableTCWidths.Columns[1].Width = 50;
            tableTCWidths.Columns[2].Width = 60;
            tableTCWidths.Columns[3].Width = 95;
            tableTCWidths.Columns[4].Width = 80;
            tableTCWidths.Columns[5].Width = 60;

            for (int row =1; row<=joistDataByMark.Count()+1; row++)
            {
                tableTCWidths.Rows[row].Height = 7;
            }

            for (int row = 1; row <= joistDataByMark.Count() + 1; row++)
            {
                for (int col = 1; col <= 5; col++)
                {
                    tableTCWidths.Cell(row, col).Range.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    tableTCWidths.Cell(row, col).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                }
            }
            wordApp.Visible = true;
        }
Ejemplo n.º 34
0
        void RunSummary()
        {
            NotamFilter filter = new NotamFilter();
            
            filter.TypeFilter = NType;
            filter.FromDateFilter = FromDate;
            filter.ToDateFilter = ToDate;
            _notamService.Archive();
            List<Notam> notamList = _notamService.GetFilterNotams(filter);
            List<string> aeroList = notamList.Select(x => x.FirAero).ToList<string>();
            Dictionary<string, string> aeroDic = _aerodomService.GetAddressList(aeroList);
            object fileName = System.Configuration.ConfigurationManager.AppSettings.Get("DocTemplatePath").ToString();
            Word.Application word = new Word.Application();
            Word.Document doc = new Word.Document();
            object missing = System.Type.Missing;
            try
            {
                doc = word.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                doc.Activate();
                string newFileName = fileName.ToString();
                newFileName = newFileName.Replace(".docx", "1.docx");
                doc.SaveAs(newFileName);
                Process.Start(newFileName.ToString());
                int icol = 2, irow = 1;
                var queryYear = notamList.GroupBy(item => item.Year).Select(group =>
                                        new
                                        {
                                            Year = group.Key,
                                            nums = group.OrderBy(x => x.Number)
                                        }).OrderBy(group => group.nums.First().Number);
                Word.Table newTable = doc.Application.ActiveDocument.Tables[1];
                //                newTable.Rows.Add(newTable.Rows[1]);
                foreach (var yearItem in queryYear)
                {
                    newTable.Cell(irow, 1).Range.Text = "20" + yearItem.Year + ":";
                    foreach (var nt in yearItem.nums)
                    {
                        if (icol > 14)
                        {
                            icol = 2;
                            irow++;
                            newTable.Rows.Add(ref missing);

                        }
                        if (nt.Number!=null)
                            newTable.Cell(irow, icol).Range.Text = nt.Number.ToString();
                        doc.Save();
                        icol++;
                    }
                    irow++;
                    icol = 2;
                    newTable.Rows.Add(ref missing);
                    doc.Save();
                }
                

                //add0519
                var queryAero = notamList.Where(x => x.FirAero!=null).GroupBy(item => item.FirAero).Select(group =>
                        new
                        {
                            Aero = group.Key,
                            Addr = aeroDic.ContainsKey(group.Key) ? aeroDic[group.Key]:"",
                            nums = group.OrderBy(x => x.Number)
                        }).OrderBy(group => group.Addr);
                Word.Table secTable = doc.Application.ActiveDocument.Tables[2];
                irow = 1;
                //                newTable.Rows.Add(newTable.Rows[1]);
                
                foreach (var aeroItem in queryAero)
                {
                    secTable.Rows.Add(ref missing);
                    irow++;
                    secTable.Cell(irow, 3).Range.Font.Size = 11;
                    secTable.Cell(irow, 3).Range.Font.Bold = 1;
                    secTable.Cell(irow, 3).Range.Font.Italic = 1;
                    string strAeroCity = aeroItem.Addr;
                    secTable.Cell(irow, 3).Range.Text = strAeroCity + "." + aeroItem.Aero;
                    doc.Save();

                    foreach (var nt in aeroItem.nums)
                    {
                        secTable.Rows.Add(ref missing);
                        irow++;
                        secTable.Cell(irow, 1).Range.Font.Bold = 0;
                        secTable.Cell(irow, 1).Range.Font.Italic = 0;
                        secTable.Cell(irow, 1).Range.Font.Size = 10;
                        if (nt.Number!=null)
                            secTable.Cell(irow, 1).Range.Text = nt.Type+ nt.Number.ToString();
                        secTable.Cell(irow, 2).Range.Font.Bold = 0;
                        secTable.Cell(irow, 2).Range.Font.Italic = 0;
                        secTable.Cell(irow, 2).Range.Font.Size = 10;
                        if (nt.FromDate!=null)
                            secTable.Cell(irow, 2).Range.Text = nt.FromDate.Substring(0, 6);
                        string str = nt.FromDate + "/" + nt.ToDate + "/" + nt.PermEst + "\n";
                        string iteme = nt.EFreeText;
                        secTable.Cell(irow, 3).Range.Font.Bold = 0;
                        secTable.Cell(irow, 3).Range.Font.Italic = 0;
                        secTable.Cell(irow, 3).Range.Font.Size = 9;
                        secTable.Cell(irow, 3).Range.Text = str + iteme;
                        doc.Save();

                    }
                }


                doc.Save();
                MessageBox.Show("Summary created successfully.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }
Ejemplo n.º 35
0
        // Open a new document
        public void Open( )
        {
            object missing = System.Reflection.Missing.Value;
            oDoc = oWordApplic.Documents.Add(ref missing, ref missing,ref missing, ref missing);

            oDoc.Activate();
        }
Ejemplo n.º 36
0
        public static bool CreateWordsDocuments(object docPath, string savaAs, string docName, DataRowView[] candidats, string presedinte, string membru1, string membru2)
        {
            int candiLength = candidats.Length;
            Console.WriteLine("LENGTH" + candiLength);

            object missing = Missing.Value;
            //      Word.Document[] adocs = new Word.Document[candidats.Length];

            Word.Document aDoc = null;
            Word.Application wordApp = null;

            try{
                for (int i = 0; i < candiLength; ++i)
                {

                    aDoc = new Word.Document();
                    wordApp = new Word.Application();
                    DataRow candidat = candidats[i].Row;
                    List<int> processesbeforegen = getRunningProcesses();
                    string savePath =(string) savaAs + docName + " " + candidat["Nume"] + "_" + candidat["Prenume"] ;

                    if (File.Exists((string)docPath))
                    {
                        Console.WriteLine("Fajlnal vagyok");

                        object readOnly = false; //default
                        object isVisible = false;

                        wordApp.Visible = false;

                        aDoc = wordApp.Documents.Open(ref docPath, ref missing, ref readOnly,
                                                    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);

                        aDoc.Activate();

                        Console.WriteLine("megnyitva");

                        //Find and replace:
                        FindAndReplace(wordApp, "{NrMatricol}", candidat["NrMatricol"]);
                        FindAndReplace(wordApp, "{Nume}", candidat["Nume"]);
                        FindAndReplace(wordApp, "{Prenume}", candidat["Prenume"]);
                        FindAndReplace(wordApp, "{Tata}", candidat["Tata"]);
                        FindAndReplace(wordApp, "{Mama}", candidat["Mama"]);
                        FindAndReplace(wordApp, "{CNP>", candidat["CNP"]);
                        FindAndReplace(wordApp, "{DataNasterii}", candidat["DataNasterii"]);
                        FindAndReplace(wordApp, "{LoculNasterii}", candidat["LoculNasterii"]);
                        FindAndReplace(wordApp, "{Strada}", candidat["Strada"]);
                        FindAndReplace(wordApp, "{Nr}", candidat["Nr"]);
                        FindAndReplace(wordApp, "{Bloc}", candidat["Bloc"]);
                        FindAndReplace(wordApp, "{Scara}", candidat["Scara"]);
                        FindAndReplace(wordApp, "{Ap}", candidat["Ap"]);
                        FindAndReplace(wordApp, "{Localitate}", candidat["Localitate"]);
                        FindAndReplace(wordApp, "{Judet}", candidat["Judet"]);
                        FindAndReplace(wordApp, "{Cp}", candidat["Cp"]);
                        FindAndReplace(wordApp, "{Telefon}", candidat["Telefon"]);
                        FindAndReplace(wordApp, "{Studii}", candidat["Studii"]);
                        FindAndReplace(wordApp, "{Profesia}", candidat["Profesia"]);
                        FindAndReplace(wordApp, "{LocMunca}", candidat["LocMunca"]);
                        FindAndReplace(wordApp, "{Presedinte}", presedinte);
                        FindAndReplace(wordApp, "{Membru1}", membru1);
                        FindAndReplace(wordApp, "{Membru2}", membru2);

                        Console.WriteLine("cserelgetes");

                        object saveFullPath = savePath;

                        aDoc.SaveAs2(ref saveFullPath, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing);

                        //Close Document:

                        aDoc.Close(ref missing, ref missing, ref missing);
                        wordApp.Quit(false);

                        Marshal.FinalReleaseComObject(wordApp);

                        aDoc = null;
                        wordApp = null;
                        List<int> processesaftergen = getRunningProcesses();
                        Console.WriteLine("COUNT > " + processesbeforegen.Count + "  " + processesaftergen.Count);
                        killProcesses(processesbeforegen, processesaftergen);
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("file dose not exist.");
                        return false;
                    }
                }

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Error occured at Report!\n"+ex.Message);
                return false;
            }
            finally
            {
                if (aDoc != null) aDoc.Close(ref missing, ref missing, ref missing);
                if (wordApp != null)
                {
                    wordApp.Quit(ref missing, ref missing, ref missing);
                    Marshal.FinalReleaseComObject(wordApp);
                }

            }

            return true;
        }
Ejemplo n.º 37
0
        private void WordOpen(string strFileName)
        {
            object fileName = strFileName;
            object readOnly = false;
            object isVisible = true;
            

            _WordDoc = _WordApplication.Documents.Open(ref fileName, ref missing, ref readOnly,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

            _WordDoc.Activate();
        }
Ejemplo n.º 38
0
 /// <summary>
 /// 打开指定文件
 /// </summary>
 /// <param name="FileName">文件名(包含路径)</param>
 /// <param name="IsReadOnly">打开后是否只读</param>
 /// <param name="IsVisibleWin">打开后是否可视</param>
 /// <returns>打开是否成功</returns>
 public bool OpenAndActive(string FileName, bool IsReadOnly, bool IsVisibleWin)
 {
     if (string.IsNullOrEmpty(FileName))
     {
         return false;
     }
     try
     {
         _wordDocument = OpenOneDocument(FileName, missing, IsReadOnly, missing, missing, missing, missing, missing, missing, missing, missing, IsVisibleWin, missing, missing, missing, missing);
         _wordDocument.Activate();
         return true;
     }
     catch
     {
         return false;
     }
 }
Ejemplo n.º 39
0
 public void openWord()
 {
     this.wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
     this.wordApp.Visible = false;
     object missing = System.Reflection.Missing.Value;
     this.wordDoc = wordApp.Documents.Open(this.outputPath,ref missing,ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
     wordDoc.Activate();
 }
Ejemplo n.º 40
0
        public void Open(string strFileName)
        {
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName.ToLower().Equals("winword"))
                    p.Kill();
            }

            object fileName = strFileName;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            oWordApplic = new Word.ApplicationClass();
            oDoc = oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

            oDoc.Activate();
        }
Ejemplo n.º 41
0
        public static bool CreateWordsDocumentToOne(object docPath, string savaAs, string docName,DataRowView[] candidats,string presedinte,string membru1, string membru2)
        {
            int candiLength = candidats.Length;
               Console.WriteLine("LENGTH" + candiLength);

               object missing = Missing.Value;
             //      Word.Document[] adocs = new Word.Document[candidats.Length];

               string output = savaAs + docName + "-" + "candidats.docx";

               Application createEmptyDocApp = null;
               Word.Document createEmptyDoc = null;

               Word._Application wordAppForOutput = null;
               Word._Document wordDocument = null;

               Word.Document aDoc = null;
               Word.Application wordApp = null;

               try
               {
               if (File.Exists(output))
                   File.Delete(output);

               if (!File.Exists(output))
               {
                   createEmptyDocApp = new Application();
                   createEmptyDoc = createEmptyDocApp.Documents.Add();

                   createEmptyDocApp.ActiveDocument.SaveAs(output, ref missing, ref missing,
                                                                          ref missing, ref missing, ref missing, ref missing,
                                                                          ref missing, ref missing, ref missing, ref missing);
                   createEmptyDoc.Close();
                   if (createEmptyDocApp != null)
                   {
                       createEmptyDocApp.Quit();
                       Marshal.FinalReleaseComObject(createEmptyDocApp);
                   }

                   createEmptyDoc = null;
                   createEmptyDocApp = null;

               }
               else
               {
                   return false;
               }

               object pageBreak = Word.WdBreakType.wdPageBreak;
               wordAppForOutput = new Word.Application();

               wordAppForOutput.Visible = false;

               wordDocument = wordAppForOutput.Documents.Open(
                                             output
                                             , false, false, ref missing,
                                                        ref missing, ref missing, ref missing, ref missing,
                                                        ref missing, ref missing, ref missing, true,
                                                        ref missing, ref missing, ref missing, ref missing);

               wordDocument.Activate();

               for (int i = 0; i < candiLength; ++i)
               {

                   aDoc = new Word.Document();
                   wordApp = new Word.Application();
                   DataRow candidat = candidats[i].Row;
                   List<int> processesbeforegen = getRunningProcesses();
                   // string savePath =(string) savaAs + docName + " " + candidat["Nume"] + "_" + candidat["Prenume"] ;
                   string savePath = savaAs + "tempDoc";

                   if (File.Exists((string)docPath))
                   {
                       Console.WriteLine("Fajlnal vagyok");

                       object readOnly = false; //default
                       object isVisible = false;

                       wordApp.Visible = false;

                       aDoc = wordApp.Documents.Open(ref docPath, ref missing, ref readOnly,
                                                   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);

                       aDoc.Activate();

                       Console.WriteLine("megnyitva");

                       //Find and replace:
                       FindAndReplace(wordApp, "{NrMatricol}", candidat["NrMatricol"]);
                       FindAndReplace(wordApp, "{Nume}", candidat["Nume"]);
                       FindAndReplace(wordApp, "{Prenume}", candidat["Prenume"]);
                       FindAndReplace(wordApp, "{Tata}", candidat["Tata"]);
                       FindAndReplace(wordApp, "{Mama}", candidat["Mama"]);
                       FindAndReplace(wordApp, "{CNP>", candidat["CNP"]);
                       FindAndReplace(wordApp, "{DataNasterii}", candidat["DataNasterii"]);
                       FindAndReplace(wordApp, "{LoculNasterii}", candidat["LoculNasterii"]);
                       FindAndReplace(wordApp, "{Strada}", candidat["Strada"]);
                       FindAndReplace(wordApp, "{Nr}", candidat["Nr"]);
                       FindAndReplace(wordApp, "{Bloc}", candidat["Bloc"]);
                       FindAndReplace(wordApp, "{Scara}", candidat["Scara"]);
                       FindAndReplace(wordApp, "{Ap}", candidat["Ap"]);
                       FindAndReplace(wordApp, "{Localitate}", candidat["Localitate"]);
                       FindAndReplace(wordApp, "{Judet}", candidat["Judet"]);
                       FindAndReplace(wordApp, "{Cp}", candidat["Cp"]);
                       FindAndReplace(wordApp, "{Telefon}", candidat["Telefon"]);
                       FindAndReplace(wordApp, "{Studii}", candidat["Studii"]);
                       FindAndReplace(wordApp, "{Profesia}", candidat["Profesia"]);
                       FindAndReplace(wordApp, "{LocMunca}", candidat["LocMunca"]);
                       FindAndReplace(wordApp, "{Presedinte}", presedinte);
                       FindAndReplace(wordApp, "{Membru1}", membru1);
                       FindAndReplace(wordApp, "{Membru2}", membru2);

                       Console.WriteLine("cserelgetes");

                       object saveFullPath = savePath;

                       aDoc.SaveAs2(ref saveFullPath, ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing,
                       ref missing, ref missing, ref missing);

                       //Close Document:

                       aDoc.Close(ref missing, ref missing, ref missing);
                       wordApp.Quit(false);

                       Marshal.FinalReleaseComObject(wordApp);
                       string PathToMerge = savePath + ".docx";
                       if (File.Exists(PathToMerge))
                       {
                           wordAppForOutput.Selection.InsertFile(PathToMerge, ref missing, true, ref missing, ref missing);
                           wordAppForOutput.Selection.InsertBreak(ref pageBreak);
                           File.Delete(PathToMerge);
                       }
                       else
                       {
                           Console.WriteLine("dosent exist the file");
                       }

                       aDoc = null;
                       wordApp = null;
                       List<int> processesaftergen = getRunningProcesses();
                       Console.WriteLine("COUNT > " + processesbeforegen.Count + "  " + processesaftergen.Count);
                       killProcesses(processesbeforegen, processesaftergen);
                   }
                   else
                   {
                       System.Windows.MessageBox.Show("file dose not exist.");
                       return false;
                   }
               }

               // Clean up!
               wordDocument.SaveAs(output, ref missing, ref missing,
                                            ref missing, ref missing, ref missing,
                                            ref missing, ref missing, ref missing, ref missing, ref missing);
               wordDocument.Close(ref missing, ref missing, ref missing);
               wordAppForOutput.Quit(ref missing, ref missing, ref missing);
               Marshal.FinalReleaseComObject(wordAppForOutput);
               wordDocument = null;
               wordAppForOutput = null;
               }
               catch (Exception ex)
               {
               System.Windows.MessageBox.Show("Error occured at Report!");
               return false;
               }
               finally
               {
               if (createEmptyDoc != null) createEmptyDoc.Close(ref missing, ref missing, ref missing);
               if (createEmptyDocApp != null)
               {
                   createEmptyDocApp.Quit(ref missing, ref missing, ref missing);
                   Marshal.FinalReleaseComObject(createEmptyDocApp);
               }

               if (wordDocument != null) wordDocument.Close(ref missing, ref missing, ref missing);
               if (wordAppForOutput != null)
               {
                   wordAppForOutput.Quit(ref missing, ref missing, ref missing);
                   Marshal.FinalReleaseComObject(wordAppForOutput);
               }

               if (aDoc != null) aDoc.Close(ref missing, ref missing, ref missing);
               if (wordApp != null)
               {
                   wordApp.Quit(ref missing, ref missing, ref missing);
                   Marshal.FinalReleaseComObject(wordApp);
               }

               }

               return true;
        }
Ejemplo n.º 42
0
        private void CopyBodyToMeeting(AppointmentItem ai, ref MeetingItem meetingItem)
        {
            ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem enter");
            Word.Document Doc = new Word.Document();
            Word.Document Doc2 = new Word.Document();
            //Word.Application App1;
            //Word.Selection Sel;

            Doc = ai.GetInspector.WordEditor as Word.Document;
            // Word.Application App2;
            // Word.Selection Sel2;

            if (Doc != null)
            {
                ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length));
                Doc.Activate();
                Doc.Select();
                //App1 = Doc.Windows.Application;
                //Sel = App1.Selection;
                //Sel.WholeStory();
                //Sel.Copy();
                Doc.Range().WholeStory();
                Doc.Range().Copy();

                Doc2 = meetingItem.GetInspector.WordEditor as Word.Document;
                if (Doc2 != null)
                {
                    Doc2.Activate();
                    object start = 0;
                    Range newRang = Doc2.Range(ref start, ref start);
                    int ioo = Doc2.Sections.Count;
                    Section sec = Doc2.Sections[1];

                    sec.Range.InsertBreak(Type.Missing);//插入换行符
                    try
                    {
                        //sec.Range.PasteAndFormat(WdRecoveryType.wdPasteDefault);
                        sec.Range.PasteAndFormat(WdRecoveryType.wdFormatOriginalFormatting);
                        meetingItem.Save();
                        ThisAddIn.g_log.Info(string.Format("meetingItem doc length is {0}.", Doc2.Content.Text.Length));

                        if (meetingItem.Body == null || meetingItem.Body.Length < 100)
                        {
                            Doc2.Activate();
                            ((_Inspector)(meetingItem.GetInspector)).Activate();
                            ThisAddIn.g_log.Info("meetingItems's body is null Or body length is short,Activate over");
                        }
                    }
                    catch (System.Exception ex)
                    {
                        ThisAddIn.g_log.Info("CopyBodyToMeeting comes Exception " + ex.ToString());
                    }
                }
                else
                {
                    ThisAddIn.g_log.Info("Doc is null");
                }
            }
            if (Doc != null)
            {
                Marshal.ReleaseComObject(Doc);
                Doc = null;
            }
            if (Doc2 != null)
            {
                Marshal.ReleaseComObject(Doc2);
                Doc2 = null;
            }
            //Doc = null;
            //Doc2 = null;
            ////App1 = null;
            ////Sel = null;
            ////            App2 = null;
            ////            Sel2 = null;

            ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem exit");
        }
Ejemplo n.º 43
0
        /// <summary>
        /// 调用模板生成word
        /// </summary>
        /// <param name="templateFile">模板文件</param>
        /// <param name="fileName">生成的具有模板样式的新文件</param>
        public void mgmsExportWord(string templateFile, string newfileName)
        {
            #region 生成word应用程序对象
            object obj = System.Reflection.Missing.Value;
            Word.Application app = new Word.Application();

            //模板文件
            string TemplateFile = templateFile;

            //生成的具有模板样式的新文件
            string newFileName = newfileName;

            //模板文件拷贝到新文件
            File.Copy(TemplateFile, newFileName);

            //生成documnet对象
            //Word.Document doc=app.Documents.Add(ref obj,ref obj,ref obj,ref,obj,ref obj);
            Word.Document doc = new Word.Document();
            object Obj_FileName = newFileName;
            object Visible = false;
            object ReadOnly = false;
            object missing = System.Reflection.Missing.Value;

            //打开文件
            doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref Visible,
                ref missing, ref missing, ref missing,
                ref missing);
            #endregion

            try
            {

                //生成word程序对象

                doc.Activate();

                //声明书签数组
                object[] BookMark = new object[70];

                #region 锚杆锚索标签定位

                //赋值书签名
                BookMark[0] ="mgmstitle";
                BookMark[1] = "mgmstimestart";
                BookMark[2] ="mgmstimeend";
                BookMark[3] ="mgmstabletime";
                BookMark[4] ="mgmstableman";
                BookMark[5] ="mgmssensor01";
                BookMark[6] ="mgmssensor02";
                BookMark[7] ="mgmssensor03";
                BookMark[8] ="mgmssensor04";
                BookMark[9] ="mgmssensor05";
                BookMark[10] = "mgmssensor06";
                BookMark[11] = "mgmssensor07";
                BookMark[12] = "mgmssensor08";
                BookMark[13] = "mgmssensor09";
                BookMark[14] = "mgmsmintime01";
                BookMark[15] = "mgmsmintime02";
                BookMark[16] = "mgmsmintime03";
                BookMark[17] = "mgmsmintime04";
                BookMark[18] = "mgmsmintime05";
                BookMark[19] = "mgmsmintime06";
                BookMark[20] = "mgmsmintime07";
                BookMark[21] = "mgmsmintime08";
                BookMark[22] = "mgmsmintime09";
                BookMark[23] = "mgmsmaxtime01";
                BookMark[24] = "mgmsmaxtime02";
                BookMark[25] = "mgmsmaxtime03";
                BookMark[26] = "mgmsmaxtime04";
                BookMark[27] = "mgmsmaxtime05";
                BookMark[28] = "mgmsmaxtime06";
                BookMark[29] = "mgmsmaxtime07";
                BookMark[30] = "mgmsmaxtime08";
                BookMark[31] = "mgmsmaxtime09";
                BookMark[32] = "mgmsaverage01";
                BookMark[33] = "mgmsaverage02";
                BookMark[34] = "mgmsaverage03";
                BookMark[35] = "mgmsaverage04";
                BookMark[36] = "mgmsaverage05";
                BookMark[37] = "mgmsaverage06";
                BookMark[38] = "mgmsaverage07";
                BookMark[39] = "mgmsaverage08";
                BookMark[40] = "mgmsaverage09";
                BookMark[41] = "mgmsminvalue01";
                BookMark[42] = "mgmsminvalue02";
                BookMark[43] = "mgmsminvalue03";
                BookMark[44] = "mgmsminvalue04";
                BookMark[45] = "mgmsminvalue05";
                BookMark[46] = "mgmsminvalue06";
                BookMark[47] = "mgmsminvalue07";
                BookMark[48] = "mgmsminvalue08";
                BookMark[49] = "mgmsminvalue09";
                BookMark[50] = "mgmsmaxvalue01";
                BookMark[51] = "mgmsmaxvalue02";
                BookMark[52] = "mgmsmaxvalue03";
                BookMark[53] = "mgmsmaxvalue04";
                BookMark[54] = "mgmsmaxvalue05";
                BookMark[55] = "mgmsmaxvalue06";
                BookMark[56] = "mgmsmaxvalue07";
                BookMark[57] = "mgmsmaxvalue08";
                BookMark[58] = "mgmsmaxvalue09";
                BookMark[59] = "mgmsalamevent01";
                BookMark[60] = "mgmsalamevent02";
                BookMark[61] = "mgmsalamevent03";
                BookMark[62] = "mgmsalamevent04";
                BookMark[63] = "mgmsalamevent05";
                BookMark[64] = "mgmsalamevent06";
                BookMark[65] = "mgmsalamevent07";
                BookMark[66] = "mgmsalamevent08";
                BookMark[67] = "mgmsalamevent09";
                BookMark[68] = "lbimagemgms";

                #endregion

                //-----------数据煤矿名称读取操作----------
                string strsqltitle = "select 煤矿名称 from 煤矿基本信息表 ";
                DataTable dt = db.Query(strsqltitle);
                DataRow dr = dt.Rows[0];
                string inform = dr["煤矿名称"].ToString();
                //----------------------------------------------------------
                //获取当前系统时间不显示秒
                DateTime currentTime = System.DateTime.Now;
                string strnowtime = currentTime.ToString("f");

                //获取当前用户
                string currentuser = login.REAL_NAME;

                #region 锚杆锚索导出报表
                //---------------------取锚杆锚索时间段-------------------
                string date_begin_hourmgms = (comboBox12.Text == "") ? "0" : comboBox12.Text;
                string date_begin_minmgms = (comboBox10.Text == "") ? "0" : comboBox10.Text;
                string date_over_hourmgms = (comboBox11.Text == "") ? "23" : comboBox11.Text;
                string date_over_minmgms = (comboBox9.Text == "") ? "59" : comboBox9.Text;

                string date_beginmgms = dateTimePicker6.Text.ToString();
                date_beginmgms += " " + date_begin_hourmgms + ":" + date_begin_minmgms;
                date_beginmgms += ":00";
                string date_overmgms = dateTimePicker5.Text.ToString();
                date_overmgms += " " + date_over_hourmgms + ":" + date_over_minmgms;
                date_overmgms += ":00";
                DateTime d_beginmgms = DateTime.Parse(date_beginmgms);
                DateTime d_overmgms = DateTime.Parse(date_overmgms);

                //----------------------------------------------------------------
                //string strmgmsstarttime = dateTimePicker6.Text.ToString() + " " + comboBox12.Text.ToString() + ":" + comboBox10.Text.ToString();
                //string strmgmsendtime = dateTimePicker5.Text.ToString() + " " + comboBox11.Text.ToString() + ":" + comboBox9.Text.ToString();

                //----赋值锚杆锚索数据到公共书签的位置---------------------
                doc.Bookmarks.get_Item(ref BookMark[0]).Range.Text = inform;
                doc.Bookmarks.get_Item(ref BookMark[1]).Range.Text = date_beginmgms;
                doc.Bookmarks.get_Item(ref BookMark[2]).Range.Text = date_overmgms;
                doc.Bookmarks.get_Item(ref BookMark[3]).Range.Text = strnowtime;
                doc.Bookmarks.get_Item(ref BookMark[4]).Range.Text = currentuser;
                //-------------------------------------------------------------

                //---------------取锚杆锚索传感器编号与所选传感器列表相对应----------
                string mgmscgqbh = "锚杆锚索传感器编号='";
                for (int i = 0; i < dataGridView3.Rows.Count; i++)
                {

                    if (i == dataGridView3.Rows.Count - 1)
                        mgmscgqbh += dataGridView3.Rows[i].Cells["传感器编号"].Value.ToString() + "'";
                    else
                        mgmscgqbh += dataGridView3.Rows[i].Cells["传感器编号"].Value.ToString() + "' or 锚杆锚索传感器编号='";

                }
                //------------------------------------------------------------------------------------

                //--------------------锚杆锚索应力max、min、avg值实现----------------
                string sqlmgmsdata = "SELECT  锚杆锚索传感器编号, min([锚杆锚索data]) as mindata ,round(avg([锚杆锚索data]),2) as avgdata,max([锚杆锚索data]) as maxdata FROM 锚杆锚索传感器信息表 WHERE ( [锚杆锚索观测时间] Between  #" + d_beginmgms + "# And #" + d_overmgms + "#) and( " + mgmscgqbh + ") Group by 锚杆锚索传感器编号";

                DataTable mgmsdr = db.Query(sqlmgmsdata);//存放从锚杆锚索传感器信息表中取出的数据

                int row_num=0;
                for (int i = 0; i < dataGridView3.Rows.Count; i++)
                {
                    for (int j = 0; j < mgmsdr.Rows.Count; j++)
                    {
                        if (mgmsdr.Rows[j]["锚杆锚索传感器编号"].ToString() == dataGridView3.Rows[i].Cells["传感器编号"].Value.ToString())
                        {
                            string sql_pstion = "select 传感器安装位置 from 传感器信息表 where 传感器编号 ='" + dataGridView3.Rows[i].Cells["传感器编号"].Value.ToString() + "' ";
                            string pstion = (string)db.QueryScalar(sql_pstion);
                            doc.Bookmarks.get_Item(ref BookMark[row_num + 5]).Range.Text = dataGridView3.Rows[i].Cells["传感器编号"].Value.ToString() + @" \ " + pstion;
                            doc.Bookmarks.get_Item(ref BookMark[row_num + 32]).Range.Text = mgmsdr.Rows[j]["avgdata"].ToString();

                            string sqlmgmstime = "SELECT  锚杆锚索传感器编号,锚杆锚索观测时间 FROM 锚杆锚索传感器信息表 WHERE ( [锚杆锚索观测时间] Between  #" + d_beginmgms + "# And #" + d_overmgms + "#) and 锚杆锚索传感器编号='" + mgmsdr.Rows[j]["锚杆锚索传感器编号"].ToString() + "' and ([锚杆锚索data]=" + mgmsdr.Rows[j]["mindata"].ToString() + ") ";
                            DataTable mgmstimedt = db.Query(sqlmgmstime);//存放最小值观测时间
                            doc.Bookmarks.get_Item(ref BookMark[row_num + 14]).Range.Text = mgmsdr.Rows[j]["mindata"].ToString() + "/" + mgmstimedt.Rows[0]["锚杆锚索观测时间"].ToString();
                            sqlmgmstime = "SELECT  锚杆锚索传感器编号,锚杆锚索观测时间 FROM 锚杆锚索传感器信息表 WHERE ( [锚杆锚索观测时间] Between  #" + d_beginmgms + "# And #" + d_overmgms + "#) and 锚杆锚索传感器编号='" + mgmsdr.Rows[j]["锚杆锚索传感器编号"].ToString() + "' and ([锚杆锚索data]=" + mgmsdr.Rows[j]["maxdata"].ToString() + ") ";
                            DataTable mgmstimedt_max = db.Query(sqlmgmstime);//存放最小值观测时间
                            doc.Bookmarks.get_Item(ref BookMark[row_num + 23]).Range.Text = mgmsdr.Rows[j]["maxdata"].ToString() + "/" + mgmstimedt_max.Rows[0]["锚杆锚索观测时间"].ToString();

                            string mgmssqlalamvalue = "select 传感器编号,最大报警值1,最小报警值1 from 报警值信息表 where 传感器编号='" + mgmsdr.Rows[j]["锚杆锚索传感器编号"].ToString() + "'";
                            DataTable mgmsalamdr = db.Query(mgmssqlalamvalue); //存放从报警表中取的最大值、最小值预制数据
                            double min_alarm = double.NegativeInfinity;
                            double max_alarm = double.PositiveInfinity;
                            if (mgmsalamdr.Rows.Count > 0)
                            {
                                doc.Bookmarks.get_Item(ref BookMark[row_num + 41]).Range.Text = mgmsalamdr.Rows[0]["最小报警值1"].ToString();
                                doc.Bookmarks.get_Item(ref BookMark[row_num + 50]).Range.Text = mgmsalamdr.Rows[0]["最大报警值1"].ToString();
                                if (mgmsalamdr.Rows[0]["最小报警值1"].ToString()!="")
                                    min_alarm = double.Parse(mgmsalamdr.Rows[0]["最小报警值1"].ToString());
                                if (mgmsalamdr.Rows[0]["最大报警值1"].ToString() != "")
                                    max_alarm = double.Parse(mgmsalamdr.Rows[0]["最大报警值1"].ToString());

                            }
                             string sqlalameventmgms = "";
                            if (double.IsPositiveInfinity(max_alarm) && double.IsNegativeInfinity(min_alarm))
                                sqlalameventmgms = "select 锚杆锚索传感器编号,锚杆锚索data,锚杆锚索观测时间 from 锚杆锚索传感器信息表 where 锚杆锚索传感器编号='" + mgmsdr.Rows[j]["锚杆锚索传感器编号"].ToString() + "' and ( [锚杆锚索观测时间] Between  #" + d_beginmgms + "# And #" + d_overmgms + "#) and (1>2)";

                            else if (double.IsPositiveInfinity(max_alarm) && !double.IsNegativeInfinity(min_alarm))
                                sqlalameventmgms = "select 锚杆锚索传感器编号,锚杆锚索data,锚杆锚索观测时间 from 锚杆锚索传感器信息表 where 锚杆锚索传感器编号='" + mgmsdr.Rows[j]["锚杆锚索传感器编号"].ToString() + "' and ( [锚杆锚索观测时间] Between  #" + d_beginmgms + "# And #" + d_overmgms + "#) and (锚杆锚索data <" + min_alarm + ")";
                           //"锚杆锚索传感器编号='" + listBox4.Items[p].ToString()+"'"
                            else if (!double.IsPositiveInfinity(max_alarm) && double.IsNegativeInfinity(min_alarm))
                                sqlalameventmgms = "select 锚杆锚索传感器编号,锚杆锚索data,锚杆锚索观测时间 from 锚杆锚索传感器信息表 where 锚杆锚索传感器编号='" + mgmsdr.Rows[j]["锚杆锚索传感器编号"].ToString() + "' and ( [锚杆锚索观测时间] Between  #" + d_beginmgms + "# And #" + d_overmgms + "#) and (锚杆锚索data >" + max_alarm + ")";
                           else
                                sqlalameventmgms = "select 锚杆锚索传感器编号,锚杆锚索data,锚杆锚索观测时间 from 锚杆锚索传感器信息表 where 锚杆锚索传感器编号='" + mgmsdr.Rows[j]["锚杆锚索传感器编号"].ToString() + "' and ( [锚杆锚索观测时间] Between  #" + d_beginmgms + "# And #" + d_overmgms + "#) and (锚杆锚索data >" + max_alarm + " or 锚杆锚索data <" + min_alarm + ")";

                            DataTable mgmsalramnodt = db.Query(sqlalameventmgms);//存锚杆锚索传感器编号符合条
                            {
                                if (mgmsalramnodt.Rows.Count == 1)
                                    doc.Bookmarks.get_Item(ref BookMark[row_num + 59]).Range.Text = mgmsalramnodt.Rows[0]["锚杆锚索data"].ToString() + "/" + mgmsalramnodt.Rows[0]["锚杆锚索观测时间"].ToString() + " ";
                                else if (mgmsalramnodt.Rows.Count > 1)
                                    doc.Bookmarks.get_Item(ref BookMark[row_num + 59]).Range.Text = "共发生" + mgmsalramnodt.Rows.Count.ToString() + "个报警事件";
                                else
                                    doc.Bookmarks.get_Item(ref BookMark[row_num + 59]).Range.Text = "无";

                            }
                            row_num++;
                            break;
                        }
                    }

                }
                //--------------------------------------------------------------------

                //------------------读取最小值检测时间实现---------------------------------------
                //MessageBox.Show(mgmsmindata.Length.ToString());
                //for (int i = 0; i < min_num; i++)
                //{
                //    //MessageBox.Show(multipleQuery.mgmsmindata[i]);
                //    string sqlmgmstime = "SELECT  锚杆锚索传感器编号,锚杆锚索观测时间 FROM 锚杆锚索传感器信息表 WHERE 锚杆锚索传感器编号='" + mgmsmindata[i,0] + "' and ([锚杆锚索data]=" + mgmsmindata[i,1] + ") ";
                //    DataTable mgmstimedt = db.Query(sqlmgmstime);//存放最小值观测时间
                //    doc.Bookmarks.get_Item(ref BookMark[i + 14]).Range.Text = mgmsmindata[i,1] + "/" + mgmstimedt.Rows[0]["锚杆锚索观测时间"].ToString();
                //    sqlmgmstime = "SELECT  锚杆锚索传感器编号,锚杆锚索观测时间 FROM 锚杆锚索传感器信息表 WHERE 锚杆锚索传感器编号='" + mgmsmindata[i, 0] + "' and ([锚杆锚索data]=" + mgmsmindata[i, 2] + ") ";
                //    DataTable mgmstimedt_max = db.Query(sqlmgmstime);//存放最小值观测时间
                //    doc.Bookmarks.get_Item(ref BookMark[i + 23]).Range.Text = mgmsmindata[i, 2] + "/" + mgmstimedt_max.Rows[0]["锚杆锚索观测时间"].ToString();

                //}
                //---------------------------------------------------------------------------------

                ////--------------------读取最大值检测时间实现------------------------------------------
                //for (int i = 0; i < listBox4.Items.Count; i++)
                //{
                //    string sqlmgmstime = "SELECT  锚杆锚索传感器编号,锚杆锚索观测时间 FROM 锚杆锚索传感器信息表 WHERE 锚杆锚索传感器编号='" + listBox4.Items[i].ToString() + "' and( " + mgmscgqbh + ")";
                //    DataTable mgmstimedt = db.Query(sqlmgmstime);//存放最大值观测时间
                //    doc.Bookmarks.get_Item(ref BookMark[i + 23]).Range.Text = mgmsmaxdata[i] + "/" + mgmstimedt.Rows[0]["锚杆锚索观测时间"].ToString();

                //}
                ////------------------------------------------------------------------------------------

                ////-------------------------------最大最小报警值实现----------------------------------------

                //string mgmsalamcgqbh = "传感器编号='";
                //for (int i = 0; i < listBox4.Items.Count; i++)
                //{
                //    if (i == listBox4.Items.Count - 1)
                //        mgmsalamcgqbh += listBox4.Items[i].ToString() + "'";
                //    else
                //        mgmsalamcgqbh += listBox4.Items[i].ToString() + "' or 传感器编号='";

                //}
                //string mgmssqlalamvalue = "select 传感器编号,最大报警值1,最小报警值1 from 报警值信息表 where(" + mgmsalamcgqbh + ")";
                //DataTable mgmsalamdr = db.Query(mgmssqlalamvalue); //存放从报警表中取的最大值、最小值预制数据

                ////-----------------新建一个数据表名字为alarmmgms存储数据为报警最大值与最小值及锚杆锚索传感器编号---------------
                //DataTable dt_alarmmgms = new DataTable("alarmmgms");

                //dt_alarmmgms.Columns.Add("传感器编号", System.Type.GetType("System.String"));
                ////dt_alarm.Columns.Add("通道", System.Type.GetType("System.String"));

                //dt_alarmmgms.Columns.Add("最大报警值", System.Type.GetType("System.Double"));
                //dt_alarmmgms.Columns.Add("最小报警值", System.Type.GetType("System.Double"));
                ////------------------------------------------------------------------------------------------------------

                //for (int k = 0; k < listBox4.Items.Count; k++)
                //{
                //    DataRow dr_alarmmgms = dt_alarmmgms.NewRow();//读报警值表存放最大报警值、最小、及其编号
                //    dr_alarmmgms["传感器编号"] = listBox4.Items[k].ToString();
                //    dr_alarmmgms["最大报警值"] = double.PositiveInfinity;
                //    dr_alarmmgms["最小报警值"] = double.NegativeInfinity;
                //    for (int m = 0; m < mgmsalamdr.Rows.Count; m++)
                //    {
                //        if (mgmsalamdr.Rows[m]["传感器编号"].ToString() == listBox4.Items[k].ToString())
                //        {
                //            doc.Bookmarks.get_Item(ref BookMark[k + 41]).Range.Text = mgmsalamdr.Rows[m]["最小报警值1"].ToString();
                //            doc.Bookmarks.get_Item(ref BookMark[k + 50]).Range.Text = mgmsalamdr.Rows[m]["最大报警值1"].ToString();
                //            //mgmsalameventmax = (float)mgmsalamdr.Rows[m]["最大报警值1"];
                //            ////MessageBox.Show(mgmsalameventmax.ToString());
                //            //mgmsalameventmin = (float)mgmsalamdr.Rows[m]["最小报警值1"];
                //            //sensor[m] = mgmsalamdr.Rows[m]["传感器编号"].ToString();
                //            //---------------------最大、最小存值----------------
                //            dr_alarmmgms["最大报警值"] = (float)mgmsalamdr.Rows[m]["最大报警值1"];
                //            dr_alarmmgms["最小报警值"] = (float)mgmsalamdr.Rows[m]["最小报警值1"];
                //            //----------------------------------------------
                //        }

                //    }
                //    dt_alarmmgms.Rows.Add(dr_alarmmgms);
                //}

                ////--------------------------报警事件的个数-----------------------------

                //for (int n = 0; n < listBox4.Items.Count; n++)
                //{

                //    if (dt_alarmmgms.Rows.Count > 0)
                //    {
                //        //string sensorevent = "锚杆锚索传感器编号='" + sensor[n] + "'";
                //        //MessageBox.Show(sensorevent);
                //        //--------------------判断是否设置报警值的上下限--------------------------
                //        string mgmsselect_str = "";

                //        if (double.IsPositiveInfinity((double)dt_alarmmgms.Rows[n]["最大报警值"]) && double.IsNegativeInfinity((double)dt_alarmmgms.Rows[n]["最小报警值"]))
                //            mgmsselect_str = "1>1";
                //        else if ((double)dt_alarmmgms.Rows[n]["最大报警值"] == -1 && (double)dt_alarmmgms.Rows[n]["最小报警值"] != -1)
                //            mgmsselect_str = "锚杆锚索data<" + (double)dt_alarmmgms.Rows[n]["最小报警值"];
                //        //"锚杆锚索传感器编号='" + listBox4.Items[p].ToString()+"'"
                //        else if ((double)dt_alarmmgms.Rows[n]["最大报警值"] != -1 && (double)dt_alarmmgms.Rows[n]["最小报警值"] == -1)
                //        {
                //            mgmsselect_str = "锚杆锚索data>" + (double)dt_alarmmgms.Rows[n]["最大报警值"];
                //            //MessageBox.Show(mgmsselect_str);
                //        }
                //        else
                //            mgmsselect_str = "锚杆锚索data>" + (double)dt_alarmmgms.Rows[n]["最大报警值"] + " or " + "锚杆锚索data<" + (double)dt_alarmmgms.Rows[n]["最小报警值"];
                //        //MessageBox.Show(dt_alarm.Rows[n]["传感器编号"].ToString());
                //        //--------------------------------------------------------------------------------------------

                //        //--------------------------------取已设报警值的锚杆锚索传感器编号-----------------
                //        string mgmsalamsensorno = "锚杆锚索传感器编号='" + listBox4.Items[n].ToString() + "'";
                //        //for (int i = 0; i <= dt_alarmmgms.Rows.Count; i++)
                //        //{
                //        //    if (i == dt_alarmmgms.Rows.Count - 1)
                //        //    {
                //        //        mgmsalamsensorno += dt_alarmmgms.Rows[i]["传感器编号"].ToString() + "'";
                //        //        //MessageBox.Show(alamsensono);
                //        //    }
                //        //    //else
                //        //    // alamsensono += dt_alarm.Rows[i]["传感器编号"].ToString() + "' or 锚杆锚索传感器编号='";

                //        //}
                //        //---------------------------------------------------------------------

                //        string sqlalameventmgms = "select 锚杆锚索传感器编号,锚杆锚索data,锚杆锚索观测时间 from 锚杆锚索传感器信息表 where(" + mgmsalamsensorno + ") and ( [锚杆锚索观测时间] Between  #" + d_beginmgms + "# And #" + d_overmgms + "#) ";
                //        DataTable mgmsalramnodt = db.Query(sqlalameventmgms);//存锚杆锚索传感器编号符合条件的报警值
                //        if (mgmsselect_str != "")
                //        {
                //            //if(double.IsPositiveInfinity(num);)
                //            DataRow[] alarmmgms = mgmsalramnodt.Select(mgmsselect_str); //存所有报警值
                //            // DataRow[] alammin = alamnodt.Select("锚杆锚索data<" + mgmsalameventmin);

                //            if (alarmmgms.Length == 1)
                //                doc.Bookmarks.get_Item(ref BookMark[n + 59]).Range.Text = alarmmgms[0]["锚杆锚索data"].ToString() + "/" + alarmmgms[0]["锚杆锚索观测时间"].ToString() + " ";
                //            else if (alarmmgms.Length > 1)
                //                doc.Bookmarks.get_Item(ref BookMark[n + 59]).Range.Text = "共发生" + alarmmgms.Length.ToString() + "个报警事件";
                //            else
                //                doc.Bookmarks.get_Item(ref BookMark[n + 59]).Range.Text = "无";
                //        }
                //    }

                //}

                //-----------------------添加图片-----------------------------------------
                doc.Bookmarks.get_Item(ref BookMark[68]).Select();
                app.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                app.Selection.InlineShapes.AddPicture(@"D:\c.bmp", ref missing, ref missing, ref missing);

                ////判断指定的图片是否存在
                //if (File.Exists(@"..\..\sources\images\12.png"))
                //{
                //    File.Delete(@"..\..\sources\images\12.png");
                //}

                //-------------------------------------------------------------------------------------

                #endregion

                MessageBox.Show("生成“" + newFileName + "”成功!");
            }

            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
                return;
            }

            finally
            {
                //输出完毕后关闭doc对象
                object IsSave = true;
                doc.Close(ref IsSave, ref missing, ref missing);
            }
        }
Ejemplo n.º 44
0
 /// <summary>
 /// 新建并打开一个文档(默认缺省值)
 /// </summary>
 public void CreateAndActive()
 {
     _wordDocument = CreateOneDocument(missing, missing, missing, missing);
     _wordDocument.Activate();
 }
Ejemplo n.º 45
0
        public void dblcExportWord(string templateFile, string newfileName)
        {
            #region 生成word应用程序对象

            object obj = System.Reflection.Missing.Value;
            Word.Application app = new Word.Application();

            //模板文件
            string TemplateFile = templateFile;

            //生成的具有模板样式的新文件
            string newFileName = newfileName;

            //模板文件拷贝到新文件
            File.Copy(TemplateFile, newFileName);

            //生成documnet对象
            //Word.Document doc=app.Documents.Add(ref obj,ref obj,ref obj,ref,obj,ref obj);
            Word.Document doc = new Word.Document();
            object Obj_FileName = newFileName;
            object Visible = false;
            object ReadOnly = false;
            object missing = System.Reflection.Missing.Value;

            //打开文件
            doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref Visible,
                ref missing, ref missing, ref missing,
                ref missing);
            #endregion

            try
            {

                //生成word程序对象

                doc.Activate();

                //-----------数据煤矿名称读取操作----------
                string strsqltitle = "select 煤矿名称 from 煤矿基本信息表 ";
                DataTable dt = db.Query(strsqltitle);
                DataRow dr = dt.Rows[0];
                string inform = dr["煤矿名称"].ToString();
                //----------------------------------------------------------
                //获取当前系统时间不显示秒
                DateTime currentTime = System.DateTime.Now;
                string strnowtime = currentTime.ToString("f");

                //获取当前用户
                string currentuser = login.REAL_NAME;

                #region 导出报表
                //---------------------取时间段-------------------
                string date_begin_hourdblc = (comboBox1.Text == "") ? "0" : comboBox1.Text;
                string date_begin_mindblc = (comboBox3.Text == "") ? "0" : comboBox3.Text;
                string date_over_hourdblc = (comboBox2.Text == "") ? "23" : comboBox2.Text;
                string date_over_mindblc = (comboBox4.Text == "") ? "59" : comboBox4.Text;

                string date_begindblc = dateTimePicker3.Text.ToString();
                date_begindblc += " " + date_begin_hourdblc + ":" + date_begin_mindblc;
                date_begindblc += ":00";
                string date_overdblc = dateTimePicker4.Text.ToString();
                date_overdblc += " " + date_over_hourdblc + ":" + date_over_mindblc;
                date_overdblc += ":00";
                DateTime d_begindblc = DateTime.Parse(date_begindblc);
                DateTime d_overdblc = DateTime.Parse(date_overdblc);

                //----赋值dblc数据到公共书签的位置---------------------
                doc.Bookmarks.get_Item(ref BookMark_db[0]).Range.Text = inform;
                doc.Bookmarks.get_Item(ref BookMark_db[1]).Range.Text = date_begindblc;
                doc.Bookmarks.get_Item(ref BookMark_db[2]).Range.Text = date_overdblc;
                doc.Bookmarks.get_Item(ref BookMark_db[3]).Range.Text = strnowtime;
                doc.Bookmarks.get_Item(ref BookMark_db[4]).Range.Text = currentuser;
                //-------------------------------------------------------------

                //---------------取传感器编号与所选传感器列表相对应----------
                string cgqbh = "";
                //int row_num = 0;
                int i;
                for (i = 0; i < dataGridView2.Rows.Count; i++)
                {
                    cgqbh = dataGridView2.Rows[i].Cells["传感器编号"].Value.ToString();
                    int dblcid = -1;
                    dblcfillword(cgqbh, ref doc, i, d_begindblc, d_overdblc, out dblcid);

                    string sql = "SELECT  顶板离层传感器编号,离层data1 as data1,离层data2 as data2 FROM 顶板离层传感器信息表 WHERE  顶板离层ID=" + dblcid;
                    DataTable dtdblc = db.Query(sql);
                    if (dtdblc.Rows.Count > 0)
                    {
                        doc.Bookmarks.get_Item(ref BookMark_db[i + 14]).Range.Text = dtdblc.Rows[0]["data" + Tools.conn_order(cgqbh, "深基点").ToString()].ToString();
                        doc.Bookmarks.get_Item(ref BookMark_db[i + 23]).Range.Text = dtdblc.Rows[0]["data" + Tools.conn_order(cgqbh, "浅基点").ToString()].ToString();
                    }

                }

                //------------------------------------------------------------------------------------
                doc.Bookmarks.get_Item(ref BookMark_db[59]).Select();
                app.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //app.Selection.ParagraphFormat.AutoAdjustRightIndent=;
                InlineShape lipt = app.Selection.InlineShapes.AddPicture(@"D:\b.bmp", ref missing, ref missing, ref missing);

                ////-----------------------添加图片-----------------------------------------
                //doc.Bookmarks.get_Item(ref BookMark_zz[47]).Select();
                //app.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //app.Selection.InlineShapes.AddPicture(@"E:\dzy\picture\12.png", ref missing, ref missing, ref missing);

                //////判断指定的图片是否存在
                ////if (File.Exists(@"..\..\sources\images\12.png"))
                ////{
                ////    File.Delete(@"..\..\sources\images\12.png");
                ////}

                ////-------------------------------------------------------------------------------------

                #endregion

                MessageBox.Show("生成“" + newFileName + "”成功!");
            }

            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
                return;
            }

            finally
            {
                //输出完毕后关闭doc对象
                object IsSave = true;
                doc.Close(ref IsSave, ref missing, ref missing);
            }
        }
Ejemplo n.º 46
0
        public void zzylExportWord(string templateFile, string newfileName)
        {
            #region 生成word应用程序对象

            object obj = System.Reflection.Missing.Value;
            Word.Application app = new Word.Application();

            //模板文件
            string TemplateFile = templateFile;

            //生成的具有模板样式的新文件
            string newFileName = newfileName;

            //模板文件拷贝到新文件
            File.Copy(TemplateFile, newFileName);

            //生成documnet对象
            //Word.Document doc=app.Documents.Add(ref obj,ref obj,ref obj,ref,obj,ref obj);
            Word.Document doc = new Word.Document();
            object Obj_FileName = newFileName;
            object Visible = false;
            object ReadOnly = false;
            object missing = System.Reflection.Missing.Value;

            //打开文件
            doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref Visible,
                ref missing, ref missing, ref missing,
                ref missing);
            #endregion

            try
            {

                //生成word程序对象

                doc.Activate();

                //-----------数据煤矿名称读取操作----------
                string strsqltitle = "select 煤矿名称 from 煤矿基本信息表 ";
                DataTable dt = db.Query(strsqltitle);
                DataRow dr = dt.Rows[0];
                string inform = dr["煤矿名称"].ToString();
                //----------------------------------------------------------
                //获取当前系统时间不显示秒
                DateTime currentTime = System.DateTime.Now;
                string strnowtime = currentTime.ToString("f");

                //获取当前用户
                string currentuser = login.REAL_NAME;

                #region zzyl导出报表
                //---------------------取zzyl时间段-------------------
                string date_begin_hourzzyl = (comboBox5.Text == "") ? "0" : comboBox5.Text;
                string date_begin_minzzyl = (comboBox7.Text == "") ? "0" : comboBox7.Text;
                string date_over_hourzzyl = (comboBox6.Text == "") ? "23" : comboBox6.Text;
                string date_over_minzzyl = (comboBox8.Text == "") ? "59" : comboBox8.Text;

                string date_beginzzyl = dateTimePicker1.Text.ToString();
                date_beginzzyl += " " + date_begin_hourzzyl + ":" + date_begin_minzzyl;
                date_beginzzyl += ":00";
                string date_overzzyl = dateTimePicker2.Text.ToString();
                date_overzzyl += " " + date_over_hourzzyl + ":" + date_over_minzzyl;
                date_overzzyl += ":00";
                DateTime d_beginzzyl = DateTime.Parse(date_beginzzyl);
                DateTime d_overzzyl = DateTime.Parse(date_overzzyl);

                //----赋值zzyl数据到公共书签的位置---------------------
                doc.Bookmarks.get_Item(ref BookMark_zz[0]).Range.Text = inform;
                doc.Bookmarks.get_Item(ref BookMark_zz[1]).Range.Text = date_beginzzyl;
                doc.Bookmarks.get_Item(ref BookMark_zz[2]).Range.Text = date_overzzyl;
                doc.Bookmarks.get_Item(ref BookMark_zz[3]).Range.Text = strnowtime;
                doc.Bookmarks.get_Item(ref BookMark_zz[4]).Range.Text = currentuser;
                //-------------------------------------------------------------

                //---------------取支柱压力传感器编号与所选传感器列表相对应----------
                string cgqbh = "";
                int row_num = 0;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    cgqbh = dataGridView1.Rows[i].Cells["传感器编号"].Value.ToString();

                    //------------------------判断时间段内有数据做导出---------------------------------

                    //-----------------------------------------------------------------------------------

                    if ((bool)dataGridView1.Rows[i].Cells[1].FormattedValue) //前柱
                    {
                        fillword(cgqbh, "前柱", ref doc, row_num, d_beginzzyl, d_overzzyl);
                        row_num++;

                    }

                    if ((bool)dataGridView1.Rows[i].Cells[2].FormattedValue) //后柱
                    {

                        fillword(cgqbh, "后柱", ref doc, row_num, d_beginzzyl, d_overzzyl);
                        row_num++;

                    }

                    if ((bool)dataGridView1.Rows[i].Cells[3].FormattedValue) //前悬梁
                    {
                        fillword(cgqbh, "前悬梁", ref doc, row_num, d_beginzzyl, d_overzzyl);

                        row_num++;
                    }

                }

                //------------------------------------------------------------------------------------

                //-----------------------添加图片-----------------------------------------
                doc.Bookmarks.get_Item(ref BookMark_zz[68]).Select();
                app.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //app.Selection.ParagraphFormat.AutoAdjustRightIndent=;
                InlineShape lipt=app.Selection.InlineShapes.AddPicture(@"D:\zzyl.bmp", ref missing, ref missing, ref missing);
                //将图片设置为四周环绕型
                //Word.Shape s = (Word.Shape)lipt.ConvertToShape();
                //s.WrapFormat.Type = WdWrapType.wdWrapSquare;

                ////判断指定的图片是否存在
                //if (File.Exists(@"..\..\sources\images\12.png"))
                //{
                //    File.Delete(@"..\..\sources\images\12.png");
                //}

                //-------------------------------------------------------------------------------------

                #endregion

                MessageBox.Show("生成“" + newFileName + "”成功!");
            }

            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
                return;
            }

            finally
            {
                if (File.Exists(@"D:/zzyl.bmp"))
                {
                    //如果存在则删除
                    File.Delete(@"D:/zzyl.bmp");
                }

                //输出完毕后关闭doc对象
                object IsSave = true;
                doc.Close(ref IsSave, ref missing, ref missing);
            }
        }
Ejemplo n.º 47
0
        private void _Search(List<string> pathToFile, string stringToSearch, string pathToSave = null)
        {
            logger.Info("Clean the return List of coincidences");
            FileInfo.Clear();
            logger.Info("initializing paramenter objects");

            object oMissing = System.Reflection.Missing.Value;
            object oTrue = true;
            object oFalse = false;

            try
            {
                logger.Info("instantiating word app");
                word = new Word.Application();
                logger.Info("instantiating document of word app");
                doc = new Word.Document();

                logger.Info("reading each files on path ={0}", pathToFile);
                foreach (string item in pathToFile)
                {
                    object fileName = item;
                    logger.Info("opening the file");
                    doc = word.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                    doc.Activate();
                    logger.Info("file opened and activates");

                    FileInfo fiIn = new FileInfo();
                    fiIn.FileName = item;
                    fiIn.FileNameOut = string.Format(@"{0}\{1}.pdf", pathToSave, Guid.NewGuid().ToString());

                    logger.Info("searching the text on each paragraphs");
                    foreach (Word.Paragraph Paragraph in doc.Paragraphs)
                    {
                        Word.Range rng = Paragraph.Range;

                        rng.Find.Text = stringToSearch.Trim();
                        rng.Find.ClearFormatting();
                        rng.Find.Forward = true;
                        rng.Find.Replacement.ClearFormatting();
                        rng.Find.Wrap = Word.WdFindWrap.wdFindStop;

                        rng.Find.Execute(
                                        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                        while (rng.Find.Found)
                        {
                            rng.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
                            rng.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdWhite;

                            MatchesInfo maIn = new MatchesInfo();
                            maIn.Page = (int)rng.get_Information(Microsoft.Office.Interop.Word.WdInformation.wdActiveEndAdjustedPageNumber);
                            maIn.Line = (int)rng.get_Information(Microsoft.Office.Interop.Word.WdInformation.wdFirstCharacterLineNumber);

                            fiIn.MatchesList.Add(maIn);
                            logger.Info("text matching and highlight");

                            rng.Find.Execute(
                                        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                        }
                    }

                    FileInfo.Add(fiIn);

                    if (!string.IsNullOrEmpty(pathToSave))
                    {
                        logger.Info("exporting the file");
                        doc.ExportAsFixedFormat(
                                fiIn.FileNameOut,
                                Word.WdExportFormat.wdExportFormatPDF,
                                OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen,
                                BitmapMissingFonts: true, DocStructureTags: false);
                        logger.Info("file exported");
                    }

                    object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
                    object originalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;
                    object routeDocument = false;
                    ((Word._Document)doc).Close(ref saveOption, ref originalFormat, ref routeDocument);
                }
            }
            catch (Exception ex)
            {
                //TODO: Manipular errores;
                logger.Info("An exception has detected");
                logger.Error(ex);
                throw new Exception("");
                throw;
            }
            finally
            {
                ((Word._Application)word).Quit(ref oFalse, ref oMissing, ref oMissing);
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// 调用模板生成word
        /// </summary>
        /// <param name="templateFile">模板文件</param>
        /// <param name="fileName">生成的具有模板样式的新文件</param>
        public void zkylExportWord(string templateFile, string newfileName)
        {
            #region 生成word应用程序对象
            object obj = System.Reflection.Missing.Value;
            Word.Application app = new Word.Application();

            //模板文件
            string TemplateFile = templateFile;

            //生成的具有模板样式的新文件
            string newFileName = newfileName;

            //模板文件拷贝到新文件
            File.Copy(TemplateFile, newFileName);

            //生成documnet对象
            //Word.Document doc=app.Documents.Add(ref obj,ref obj,ref obj,ref,obj,ref obj);
            Word.Document doc = new Word.Document();
            object Obj_FileName = newFileName;
            object Visible = false;
            object ReadOnly = false;
            object missing = System.Reflection.Missing.Value;

            //打开文件
            doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref Visible,
                ref missing, ref missing, ref missing,
                ref missing);
            #endregion

            try
            {

                doc.Activate();

                //声明书签数组
                object[] BookMarkzkyl = new object[70];

                #region 钻孔应力标签定位

                //赋值书签名
                BookMarkzkyl[0] = "zkyllbtitle";
                BookMarkzkyl[1] = "zkyltimestart";
                BookMarkzkyl[2] = "zkyltimeend";
                BookMarkzkyl[3] = "zkyltabledate";
                BookMarkzkyl[4] = "zkyltableman";
                BookMarkzkyl[5] = "zkylsensor01";
                BookMarkzkyl[6] = "zkylsensor02";
                BookMarkzkyl[7] = "zkylsensor03";
                BookMarkzkyl[8] = "zkylsensor04";
                BookMarkzkyl[9] = "zkylsensor05";
                BookMarkzkyl[10] = "zkylsensor06";
                BookMarkzkyl[11] = "zkylsensor07";
                BookMarkzkyl[12] = "zkylsensor08";
                BookMarkzkyl[13] = "zkylsensor09";
                BookMarkzkyl[14] = "zkylmintime01";
                BookMarkzkyl[15] = "zkylmintime02";
                BookMarkzkyl[16] = "zkylmintime03";
                BookMarkzkyl[17] = "zkylmintime04";
                BookMarkzkyl[18] = "zkylmintime05";
                BookMarkzkyl[19] = "zkylmintime06";
                BookMarkzkyl[20] = "zkylmintime07";
                BookMarkzkyl[21] = "zkylmintime08";
                BookMarkzkyl[22] = "zkylmintime09";
                BookMarkzkyl[23] = "zkylmaxtime01";
                BookMarkzkyl[24] = "zkylmaxtime02";
                BookMarkzkyl[25] = "zkylmaxtime03";
                BookMarkzkyl[26] = "zkylmaxtime04";
                BookMarkzkyl[27] = "zkylmaxtime05";
                BookMarkzkyl[28] = "zkylmaxtime06";
                BookMarkzkyl[29] = "zkylmaxtime07";
                BookMarkzkyl[30] = "zkylmaxtime08";
                BookMarkzkyl[31] = "zkylmaxtime09";
                BookMarkzkyl[32] = "zkylaverage01";
                BookMarkzkyl[33] = "zkylaverage02";
                BookMarkzkyl[34] = "zkylaverage03";
                BookMarkzkyl[35] = "zkylaverage04";
                BookMarkzkyl[36] = "zkylaverage05";
                BookMarkzkyl[37] = "zkylaverage06";
                BookMarkzkyl[38] = "zkylaverage07";
                BookMarkzkyl[39] = "zkylaverage08";
                BookMarkzkyl[40] = "zkylaverage09";
                BookMarkzkyl[41] = "zkylminvalue01";
                BookMarkzkyl[42] = "zkylminvalue02";
                BookMarkzkyl[43] = "zkylminvalue03";
                BookMarkzkyl[44] = "zkylminvalue04";
                BookMarkzkyl[45] = "zkylminvalue05";
                BookMarkzkyl[46] = "zkylminvalue06";
                BookMarkzkyl[47] = "zkylminvalue07";
                BookMarkzkyl[48] = "zkylminvalue08";
                BookMarkzkyl[49] = "zkylminvalue09";
                BookMarkzkyl[50] = "zkylmaxvalue01";
                BookMarkzkyl[51] = "zkylmaxvalue02";
                BookMarkzkyl[52] = "zkylmaxvalue03";
                BookMarkzkyl[53] = "zkylmaxvalue04";
                BookMarkzkyl[54] = "zkylmaxvalue05";
                BookMarkzkyl[55] = "zkylmaxvalue06";
                BookMarkzkyl[56] = "zkylmaxvalue07";
                BookMarkzkyl[57] = "zkylmaxvalue08";
                BookMarkzkyl[58] = "zkylmaxvalue09";
                BookMarkzkyl[59] = "zkylalamevent01";
                BookMarkzkyl[60] = "zkylalamevent02";
                BookMarkzkyl[61] = "zkylalamevent03";
                BookMarkzkyl[62] = "zkylalamevent04";
                BookMarkzkyl[63] = "zkylalamevent05";
                BookMarkzkyl[64] = "zkylalamevent06";
                BookMarkzkyl[65] = "zkylalamevent07";
                BookMarkzkyl[66] = "zkylalamevent08";
                BookMarkzkyl[67] = "zkylalamevent09";
                BookMarkzkyl[68] = "lbimagezkyl00";
                #endregion

                //-----------数据煤矿名称读取操作----------
                string strsqltitle = "select 煤矿名称 from 煤矿基本信息表 ";
                DataTable dt = db.Query(strsqltitle);
                DataRow dr = dt.Rows[0];
                string inform = dr["煤矿名称"].ToString();
                //----------------------------------------------------------
                //获取当前系统时间不显示秒
                DateTime currentTime = System.DateTime.Now;
                string strnowtime = currentTime.ToString("f");

                //获取当前用户
                string currentuser = login.REAL_NAME;

                #region 钻孔应力导出报表
                //---------------------取钻孔应力时间段-------------------
                string date_begin_hourzkyl = (comboBox16.Text == "") ? "0" : comboBox16.Text;
                string date_begin_minzkyl = (comboBox15.Text == "") ? "0" : comboBox15.Text;
                string date_over_hourzkyl = (comboBox14.Text == "") ? "23" : comboBox14.Text;
                string date_over_minzkyl = (comboBox13.Text == "") ? "59" : comboBox13.Text;

                string date_beginzkyl = dateTimePicker8.Text.ToString();
                date_beginzkyl += " " + date_begin_hourzkyl + ":" + date_begin_minzkyl;
                date_beginzkyl += ":00";
                string date_overzkyl = dateTimePicker7.Text.ToString();
                date_overzkyl += " " + date_over_hourzkyl + ":" + date_over_minzkyl;
                date_overzkyl += ":00";
                DateTime d_beginzkyl = DateTime.Parse(date_beginzkyl);
                DateTime d_overzkyl = DateTime.Parse(date_overzkyl);
                //----------------------------------------------------------------

                //----赋值钻孔应力数据到公共书签的位置---------------------
                doc.Bookmarks.get_Item(ref BookMarkzkyl[0]).Range.Text = inform;
                doc.Bookmarks.get_Item(ref BookMarkzkyl[1]).Range.Text = date_beginzkyl;
                doc.Bookmarks.get_Item(ref BookMarkzkyl[2]).Range.Text = date_overzkyl;
                doc.Bookmarks.get_Item(ref BookMarkzkyl[3]).Range.Text = strnowtime;
                doc.Bookmarks.get_Item(ref BookMarkzkyl[4]).Range.Text = currentuser;
                //-------------------------------------------------------------

                //---------------取钻孔应力传感器编号与所选传感器列表相对应----------
                string zkylcgqbh = "钻孔应力传感器编号='";
                for (int i = 0; i < dataGridView4.Rows.Count; i++)
                {

                    if (i == dataGridView4.Rows.Count - 1)
                        zkylcgqbh += dataGridView4.Rows[i].Cells["传感器编号"].Value.ToString() + "'";
                    else
                        zkylcgqbh += dataGridView4.Rows[i].Cells["传感器编号"].Value.ToString() + "' or 钻孔应力传感器编号='";

                }
                //------------------------------------------------------------------------------------

                //--------------------钻孔应力应力max、min、avg值实现----------------
                string sqlzkyldata = "SELECT  钻孔应力传感器编号, min([钻孔应力data]) as mindata ,round(avg([钻孔应力data]),2) as avgdata,max([钻孔应力data]) as maxdata FROM 钻孔应力传感器信息表 WHERE ( [钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) and( " + zkylcgqbh + ") Group by 钻孔应力传感器编号";

                DataTable zkyldr = db.Query(sqlzkyldata);//存放从钻孔应力传感器信息表中取出的数据

                int row_num = 0;
                for (int i = 0; i < dataGridView4.Rows.Count; i++)
                {
                    for (int j = 0; j < zkyldr.Rows.Count; j++)
                    {
                        if (zkyldr.Rows[j]["钻孔应力传感器编号"].ToString() == dataGridView4.Rows[i].Cells["传感器编号"].Value.ToString())
                        {
                            string sql_pstion = "select 传感器安装位置 from 传感器信息表 where 传感器编号 ='" + dataGridView4.Rows[i].Cells["传感器编号"].Value.ToString() + "' ";
                            string pstion = (string)db.QueryScalar(sql_pstion);
                            doc.Bookmarks.get_Item(ref BookMarkzkyl[row_num + 5]).Range.Text = dataGridView4.Rows[i].Cells["传感器编号"].Value.ToString() + @" / " + pstion;
                            doc.Bookmarks.get_Item(ref BookMarkzkyl[row_num + 32]).Range.Text = zkyldr.Rows[j]["avgdata"].ToString();

                            string sqlzkyltime = "SELECT  钻孔应力传感器编号,钻孔应力观测时间 FROM 钻孔应力传感器信息表 WHERE ( [钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) and 钻孔应力传感器编号='" + zkyldr.Rows[j]["钻孔应力传感器编号"].ToString() + "' and ([钻孔应力data]=" + zkyldr.Rows[j]["mindata"].ToString() + ") ";
                            DataTable zkyltimedt = db.Query(sqlzkyltime);//存放最小值观测时间
                            doc.Bookmarks.get_Item(ref BookMarkzkyl[row_num + 14]).Range.Text = zkyldr.Rows[j]["mindata"].ToString() + "/" + zkyltimedt.Rows[0]["钻孔应力观测时间"].ToString();
                            sqlzkyltime = "SELECT  钻孔应力传感器编号,钻孔应力观测时间 FROM 钻孔应力传感器信息表 WHERE ( [钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) and 钻孔应力传感器编号='" + zkyldr.Rows[j]["钻孔应力传感器编号"].ToString() + "' and ([钻孔应力data]=" + zkyldr.Rows[j]["maxdata"].ToString() + ") ";
                            DataTable zkyltimedt_max = db.Query(sqlzkyltime);//存放最小值观测时间
                            doc.Bookmarks.get_Item(ref BookMarkzkyl[row_num + 23]).Range.Text = zkyldr.Rows[j]["maxdata"].ToString() + "/" + zkyltimedt_max.Rows[0]["钻孔应力观测时间"].ToString();

                            string zkylsqlalamvalue = "select 传感器编号,最大报警值1,最小报警值1 from 报警值信息表 where 传感器编号='" + zkyldr.Rows[j]["钻孔应力传感器编号"].ToString() + "'";
                            DataTable zkylalamdr = db.Query(zkylsqlalamvalue); //存放从报警表中取的最大值、最小值预制数据
                            double min_alarm = double.NegativeInfinity;
                            double max_alarm = double.PositiveInfinity;
                            if (zkylalamdr.Rows.Count > 0)
                            {
                                doc.Bookmarks.get_Item(ref BookMarkzkyl[row_num + 41]).Range.Text = zkylalamdr.Rows[0]["最小报警值1"].ToString();
                                doc.Bookmarks.get_Item(ref BookMarkzkyl[row_num + 50]).Range.Text = zkylalamdr.Rows[0]["最大报警值1"].ToString();
                                if (zkylalamdr.Rows[0]["最小报警值1"].ToString() != "")
                                    min_alarm = double.Parse(zkylalamdr.Rows[0]["最小报警值1"].ToString());
                                if (zkylalamdr.Rows[0]["最大报警值1"].ToString() != "")
                                    max_alarm = double.Parse(zkylalamdr.Rows[0]["最大报警值1"].ToString());

                            }
                            string sqlalameventzkyl = "";
                            if (double.IsPositiveInfinity(max_alarm) && double.IsNegativeInfinity(min_alarm))
                                sqlalameventzkyl = "select 钻孔应力传感器编号,钻孔应力data,钻孔应力观测时间 from 钻孔应力传感器信息表 where 钻孔应力传感器编号='" + zkyldr.Rows[j]["钻孔应力传感器编号"].ToString() + "' and ( [钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) and (1>2)";

                            else if (double.IsPositiveInfinity(max_alarm) && !double.IsNegativeInfinity(min_alarm))
                                sqlalameventzkyl = "select 钻孔应力传感器编号,钻孔应力data,钻孔应力观测时间 from 钻孔应力传感器信息表 where 钻孔应力传感器编号='" + zkyldr.Rows[j]["钻孔应力传感器编号"].ToString() + "' and ( [钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) and (钻孔应力data <" + min_alarm + ")";
                            //"钻孔应力传感器编号='" + listBox4.Items[p].ToString()+"'"
                            else if (!double.IsPositiveInfinity(max_alarm) && double.IsNegativeInfinity(min_alarm))
                                sqlalameventzkyl = "select 钻孔应力传感器编号,钻孔应力data,钻孔应力观测时间 from 钻孔应力传感器信息表 where 钻孔应力传感器编号='" + zkyldr.Rows[j]["钻孔应力传感器编号"].ToString() + "' and ( [钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) and (钻孔应力data >" + max_alarm + ")";
                            else
                                sqlalameventzkyl = "select 钻孔应力传感器编号,钻孔应力data,钻孔应力观测时间 from 钻孔应力传感器信息表 where 钻孔应力传感器编号='" + zkyldr.Rows[j]["钻孔应力传感器编号"].ToString() + "' and ( [钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) and (钻孔应力data >" + max_alarm + " or 钻孔应力data <" + min_alarm + ")";

                            DataTable zkylalramnodt = db.Query(sqlalameventzkyl);//存钻孔应力传感器编号符合条
                            {
                                if (zkylalramnodt.Rows.Count == 1)
                                    doc.Bookmarks.get_Item(ref BookMarkzkyl[row_num + 59]).Range.Text = zkylalramnodt.Rows[0]["钻孔应力data"].ToString() + "/" + zkylalramnodt.Rows[0]["钻孔应力观测时间"].ToString() + " ";
                                else if (zkylalramnodt.Rows.Count > 1)
                                    doc.Bookmarks.get_Item(ref BookMarkzkyl[row_num + 59]).Range.Text = "共发生" + zkylalramnodt.Rows.Count.ToString() + "个报警事件";
                                else
                                    doc.Bookmarks.get_Item(ref BookMarkzkyl[row_num + 59]).Range.Text = "无";

                            }
                            row_num++;
                            break;
                        }
                    }

                }

                ////---------------取钻孔应力传感器编号与所选传感器列表相对应----------
                //string zkylcgqbh = "钻孔应力传感器编号='";
                //for (int i = 0; i < listBox6.Items.Count; i++)
                //{
                //    if (i == listBox6.Items.Count - 1)
                //        zkylcgqbh += listBox6.Items[i].ToString() + "'";
                //    else
                //        zkylcgqbh += listBox6.Items[i].ToString() + "' or 钻孔应力传感器编号='";

                //}
                ////-----------------------------------------------------------------------------------

                ////------------------------判断时间段内有数据做导出---------------------------------

                //string zkylsqljudgedata = "SELECT * FROM 钻孔应力传感器信息表 WHERE ([钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) and " + zkylcgqbh + " order by 钻孔应力观测时间";
                //OleDbDataReader drzkyludgedata = db.Query_reader(zkylsqljudgedata);

                //if (drzkyludgedata.HasRows) //判断记录集是否包含一行或多行
                //{

                //}

                //else
                //{
                //    MessageBox.Show("此时间段内无数据,请选择其它时间段!");
                //    drzkyludgedata.Close();
                //    return;

                //}

                ////-----------------------------------------------------------------------------------

                ////--------------------钻孔应力应力max、min、avg值实现----------------
                //if (listBox6.Items.Count > 0)
                //{
                //    string sqlzkyldata = "SELECT  钻孔应力传感器编号, min([钻孔应力data]) as mindata ,round(avg([钻孔应力data]),2) as avgdata,max([钻孔应力data]) as maxdata FROM 钻孔应力传感器信息表 WHERE ( [钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) and( " + zkylcgqbh + ") Group by 钻孔应力传感器编号";

                //    DataTable zkyldr = db.Query(sqlzkyldata);//存放从钻孔应力传感器信息表中取出的数据

                //    for (int i = 0; i < listBox6.Items.Count; i++)
                //    {

                //        for (int j = 0; j < zkyldr.Rows.Count; j++)
                //        {
                //            if (zkyldr.Rows[j]["钻孔应力传感器编号"].ToString() == listBox6.Items[i].ToString())
                //            {
                //                doc.Bookmarks.get_Item(ref BookMarkzkyl[i + 5]).Range.Text = listBox6.Items[i].ToString();
                //                doc.Bookmarks.get_Item(ref BookMarkzkyl[i + 32]).Range.Text = zkyldr.Rows[j]["avgdata"].ToString();
                //                zkylmindata[i] = zkyldr.Rows[j]["mindata"].ToString();//取压力最小值
                //                zkylmaxdata[i] = zkyldr.Rows[j]["maxdata"].ToString(); //取压力最大值

                //            }
                //        }

                //    }
                //}
                //else MessageBox.Show("请选择要导出数据的传感器!");
                ////--------------------------------------------------------------------

                ////------------------读取最小值检测时间实现---------------------------------------
                //for (int i = 0; i < listBox6.Items.Count; i++)
                //{
                //    //MessageBox.Show(multipleQuery.zkylmindata[i]);
                //    string sqlzkyltime = "SELECT  钻孔应力传感器编号,钻孔应力观测时间 FROM 钻孔应力传感器信息表 WHERE 钻孔应力传感器编号='" + listBox6.Items[i].ToString() + "' and ([钻孔应力data]=" + zkylmindata[i] + ") ";
                //    DataTable zkyltimedt = db.Query(sqlzkyltime);//存放最小值观测时间
                //    doc.Bookmarks.get_Item(ref BookMarkzkyl[i + 14]).Range.Text = zkylmindata[i] + "/" + zkyltimedt.Rows[0]["钻孔应力观测时间"].ToString();

                //}
                ////---------------------------------------------------------------------------------

                ////--------------------读取最大值检测时间实现------------------------------------------
                //for (int i = 0; i < listBox6.Items.Count; i++)
                //{
                //    string sqlzkyltime = "SELECT  钻孔应力传感器编号,钻孔应力观测时间 FROM 钻孔应力传感器信息表 WHERE 钻孔应力传感器编号='" + listBox6.Items[i].ToString() + "' and( " + zkylcgqbh + ")";
                //    DataTable zkyltimedt = db.Query(sqlzkyltime);//存放最大值观测时间
                //    doc.Bookmarks.get_Item(ref BookMarkzkyl[i + 23]).Range.Text = zkylmaxdata[i] + "/" + zkyltimedt.Rows[0]["钻孔应力观测时间"].ToString();

                //}
                ////------------------------------------------------------------------------------------

                ////-------------------------------最大最小报警值实现----------------------------------------

                //string zkylalamcgqbh = "传感器编号='";
                //for (int i = 0; i < listBox6.Items.Count; i++)
                //{
                //    if (i == listBox6.Items.Count - 1)
                //        zkylalamcgqbh += listBox6.Items[i].ToString() + "'";
                //    else
                //        zkylalamcgqbh += listBox6.Items[i].ToString() + "' or 传感器编号='";

                //}
                //string zkylsqlalamvalue = "select 传感器编号,最大报警值1,最小报警值1 from 报警值信息表 where(" + zkylalamcgqbh + ")";
                //DataTable zkylalamdr = db.Query(zkylsqlalamvalue); //存放从报警表中取的最大值、最小值预制数据

                ////-----------------新建一个数据表名字为alarmmgms存储数据为报警最大值与最小值及钻孔应力传感器编号---------------
                //DataTable dt_alarmzkyl = new DataTable("alarmmgms");

                //dt_alarmzkyl.Columns.Add("传感器编号", System.Type.GetType("System.String"));
                ////dt_alarm.Columns.Add("通道", System.Type.GetType("System.String"));

                //dt_alarmzkyl.Columns.Add("最大报警值", System.Type.GetType("System.Double"));
                //dt_alarmzkyl.Columns.Add("最小报警值", System.Type.GetType("System.Double"));
                ////------------------------------------------------------------------------------------------------------

                //for (int k = 0; k < listBox6.Items.Count; k++)
                //{
                //    DataRow dr_alarmzkyl = dt_alarmzkyl.NewRow();//读报警值表存放最大报警值、最小、及其编号
                //    dr_alarmzkyl["传感器编号"] = listBox6.Items[k].ToString();
                //    dr_alarmzkyl["最大报警值"] = double.PositiveInfinity;
                //    dr_alarmzkyl["最小报警值"] = double.NegativeInfinity;
                //    for (int m = 0; m < zkylalamdr.Rows.Count; m++)
                //    {
                //        if (zkylalamdr.Rows[m]["传感器编号"].ToString() == listBox6.Items[k].ToString())
                //        {
                //            doc.Bookmarks.get_Item(ref BookMarkzkyl[k + 41]).Range.Text = zkylalamdr.Rows[m]["最小报警值1"].ToString();
                //            doc.Bookmarks.get_Item(ref BookMarkzkyl[k + 50]).Range.Text = zkylalamdr.Rows[m]["最大报警值1"].ToString();
                //            //mgmsalameventmax = (float)zkylalamdr.Rows[m]["最大报警值1"];
                //            ////MessageBox.Show(mgmsalameventmax.ToString());
                //            //mgmsalameventmin = (float)zkylalamdr.Rows[m]["最小报警值1"];
                //            //sensor[m] = zkylalamdr.Rows[m]["传感器编号"].ToString();
                //            //---------------------最大、最小存值----------------
                //            dr_alarmzkyl["最大报警值"] = float.Parse((string)zkylalamdr.Rows[m]["最大报警值1"]);
                //            dr_alarmzkyl["最小报警值"] =float.Parse((string)zkylalamdr.Rows[m]["最小报警值1"]);
                //            //----------------------------------------------
                //        }

                //    }
                //    dt_alarmzkyl.Rows.Add(dr_alarmzkyl);
                //}

                ////--------------------------报警事件的个数-----------------------------

                //for (int n = 0; n < listBox6.Items.Count; n++)
                //{

                //    if (dt_alarmzkyl.Rows.Count > 0)
                //    {
                //        //string sensorevent = "钻孔应力传感器编号='" + sensor[n] + "'";
                //        //MessageBox.Show(sensorevent);
                //        //--------------------判断是否设置报警值的上下限--------------------------
                //        string zkylselect_str = "";
                //        if (double.IsNegativeInfinity((double)dt_alarmzkyl.Rows[n]["最小报警值"]) && double.IsPositiveInfinity((double)dt_alarmzkyl.Rows[n]["最大报警值"]))
                //            zkylselect_str = "1>1";
                //        else if ((double)dt_alarmzkyl.Rows[n]["最大报警值"] == -1 && (double)dt_alarmzkyl.Rows[n]["最小报警值"] != -1)
                //            zkylselect_str = "钻孔应力data<" + (double)dt_alarmzkyl.Rows[n]["最小报警值"];
                //        //"钻孔应力传感器编号='" + listBox6.Items[p].ToString()+"'"
                //        else if ((double)dt_alarmzkyl.Rows[n]["最大报警值"] != -1 && (double)dt_alarmzkyl.Rows[n]["最小报警值"] == -1)
                //        {
                //            zkylselect_str = "钻孔应力data>" + (double)dt_alarmzkyl.Rows[n]["最大报警值"];
                //            //MessageBox.Show(select_str);
                //        }
                //        else
                //            zkylselect_str = "钻孔应力data>" + (double)dt_alarmzkyl.Rows[n]["最大报警值"] + " or " + "钻孔应力data<" + (double)dt_alarmzkyl.Rows[n]["最小报警值"];
                //        //MessageBox.Show(dt_alarm.Rows[n]["传感器编号"].ToString());
                //        //--------------------------------------------------------------------------------------------

                //        //--------------------------------取已设报警值的钻孔应力传感器编号-----------------
                //        string zkylalamsensorno = "钻孔应力传感器编号='" + listBox6.Items[n].ToString() + "'";

                //        //---------------------------------------------------------------------

                //        string sqlalameventzkyl = "select 钻孔应力传感器编号,钻孔应力data,钻孔应力观测时间 from 钻孔应力传感器信息表 where(" + zkylalamsensorno + ") and ( [钻孔应力观测时间] Between  #" + d_beginzkyl + "# And #" + d_overzkyl + "#) ";
                //        DataTable zkylalramnodt = db.Query(sqlalameventzkyl);//存钻孔应力传感器编号符合条件的报警值
                //        if (zkylselect_str != "")
                //        {
                //            DataRow[] alarmzkyl = zkylalramnodt.Select(zkylselect_str); //存所有报警值
                //            // DataRow[] alammin = alamnodt.Select("钻孔应力data<" + mgmsalameventmin);

                //            if (alarmzkyl.Length == 1)
                //                doc.Bookmarks.get_Item(ref BookMarkzkyl[n + 59]).Range.Text = alarmzkyl[0]["钻孔应力data"].ToString() + " " + alarmzkyl[0]["钻孔应力观测时间"].ToString() + " ";
                //            else if (alarmzkyl.Length > 1)
                //                doc.Bookmarks.get_Item(ref BookMarkzkyl[n + 59]).Range.Text = "共发生" + alarmzkyl.Length.ToString() + "个报警事件";
                //            else
                //                doc.Bookmarks.get_Item(ref BookMarkzkyl[n + 59]).Range.Text = "无";
                //        }
                //    }

                //}

                //-----------------------添加图片-----------------------------------------
                doc.Bookmarks.get_Item(ref BookMarkzkyl[68]).Select();
                app.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                app.Selection.InlineShapes.AddPicture(@"D:\d.bmp", ref missing, ref missing, ref missing);

                ////判断指定的图片是否存在
                //if (File.Exists(@"..\..\sources\images\12.png"))
                //{
                //    File.Delete(@"..\..\sources\images\12.png");
                //}

                //-------------------------------------------------------------------------------------

                #endregion

                MessageBox.Show("生成“" + newFileName + "”成功!");
            }

            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
                return;
            }

            finally
            {
                //输出完毕后关闭doc对象
                object IsSave = true;
                doc.Close(ref IsSave, ref missing, ref missing);
            }
        }
Ejemplo n.º 49
0
        private void CopyBody(AppointmentItem ai, MailItem mailItem)
        {
            ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem enter");
            Word.Document Doc = new Word.Document();
            Word.Document Doc2 = new Word.Document();
            Word.Application App1;
            Word.Selection Sel;
            Doc = ai.GetInspector.WordEditor as Word.Document;
            Word.Application App2;
            Word.Selection Sel2;

            if (Doc != null)
            {
                ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length));
                Doc.Activate();
                Doc.Select();
                App1 = Doc.Windows.Application;
                Sel = App1.Selection;
                Sel.WholeStory();
                Sel.Copy();

                Doc2 = mailItem.GetInspector.WordEditor as Word.Document;
                if (Doc2 != null)
                {
                    Doc2.Activate();
                    Doc2.Select();
                    App2 = Doc2.Windows.Application;
                    Sel2 = App2.Selection;
                    Sel2.WholeStory();

                    try
                    {
                        Sel2.PasteAndFormat(WdRecoveryType.wdPasteDefault);
                    }
                    catch (System.Exception ex)
                    {
                        ThisAddIn.g_log.Error(string.Format("copy to body exception, {0}", ex.ToString()));
                    }

                    mailItem.Save();
                    ThisAddIn.g_log.Info(string.Format("mailItem doc length is {0}.", Doc2.Content.Text.Length));

                    if (mailItem.Body == null || mailItem.Body.Length < 100)
                    {
                        Doc2.Activate();
                        ((_Inspector)(mailItem.GetInspector)).Activate();
                    }
                }
            }

            Doc = null;
            Doc2 = null;
            App1 = null;
            App2 = null;
            Sel = null;
            Sel2 = null;
            ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem exit");
        }
Ejemplo n.º 50
0
        private void CopyBodyToMeeting(AppointmentItem ai, ref MeetingItem meetingItem)
        {
            ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem enter");
            Word.Document Doc = new Word.Document();
            Word.Document Doc2 = new Word.Document();
            Word.Application App1;
            Word.Selection Sel;

            Doc = ai.GetInspector.WordEditor as Word.Document;

            if (Doc != null)
            {
                ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length));
                Doc.Activate();
                Doc.Select();
                App1 = Doc.Windows.Application;
                Sel = App1.Selection;
                Sel.WholeStory();
                Sel.Copy();

                Doc2 = meetingItem.GetInspector.WordEditor as Word.Document;
                if (Doc2 != null)
                {
                    Doc2.Activate();
                    object start = 0;
                    Range newRang = Doc2.Range(ref start, ref start);

                    int ioo = Doc2.Sections.Count;
                    Section sec = Doc2.Sections[1];

                    sec.Range.InsertBreak(Type.Missing);//插入换行符
                    sec.Range.PasteAndFormat(WdRecoveryType.wdPasteDefault);

                    meetingItem.Save();
                    ThisAddIn.g_log.Info(string.Format("meetingItem doc length is {0}.", Doc2.Content.Text.Length));
                    //ThisAddIn.g_log.Info(string.Format("mailItem body length is {0}.", meetingItem.Body.Length));

                    if (meetingItem.Body == null || meetingItem.Body.Length < 100)
                    {
                        Doc2.Activate();
                        ((_Inspector)(meetingItem.GetInspector)).Activate();
                    }
                }
            }
            Doc = null;
            Doc2 = null;
            App1 = null;
            Sel = null;

            ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem exit");
        }
Ejemplo n.º 51
0
        public void processWord(string saved_path, bool newSmry)
        {
            word_app = createWordApp();
            this.insertBookmark(saved_doc_list);
            object strFileName = saved_path;
            Object Nothing = System.Reflection.Missing.Value;
            object readOnly = false;
            object isVisible = false;

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

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

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

            word_app = null;
            word_show = null;
        }