private void btnEdit_Click(object sender, EventArgs e)
        {
            //creating instance of word application
            Microsoft.Office.Interop.Word._Application w = new Microsoft.Office.Interop.Word.Application();
            object path = @"C:\table.doc";
            object read = "ReadWrite";
            object readOnly = false;
            object o = System.Reflection.Missing.Value;
            //opening document
            Microsoft.Office.Interop.Word._Document oDoc = w.Documents.Open(ref path, ref o, ref readOnly, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);

            try
            {
                //loop for each paragraph in document
                foreach (Microsoft.Office.Interop.Word.Paragraph p in oDoc.Paragraphs)
                {
                    Microsoft.Office.Interop.Word.Range rng = p.Range;
                    Microsoft.Office.Interop.Word.Style styl = rng.get_Style() as Microsoft.Office.Interop.Word.Style;
                    //checking if document containg table
                    if ((bool)rng.get_Information(Microsoft.Office.Interop.Word.WdInformation.wdWithInTable)
                                        == true)
                    {
                        //loop for each cell in table
                        foreach (Microsoft.Office.Interop.Word.Cell c in rng.Cells)
                        {
                            if (rng.Cells.Count > 0)
                            {
                                //checking for desired field in table
                                if (c.Range.Text.ToString().Contains("ID"))
                                    //editing values in tables.
                                    c.Next.Range.Text = "1";
                                if (c.Range.Text.ToString().Contains("Name"))
                                    c.Next.Range.Text = "Haider";
                                if (c.Range.Text.ToString().Contains("Address"))
                                    c.Next.Range.Text = "Allahabad";
                            }
                        }
                        //saving document
                        oDoc.Save();
                    }
                }
                //closing document
                oDoc.Close(ref o, ref o, ref o);
            }
            catch (Exception ex)
            {
                oDoc.Close(ref o, ref o, ref o);
                ClientScript.RegisterStartupScript(this.GetType(), "error", "javascript:;alert('" + ex.Message + "')");
            }
        }
        /*Setting up a printable invoice for the required Customer
         */
        public void print()
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            Microsoft.Office.Interop.Word.Document doc = app.Documents.Add("E:/CarRentalSystem/Invoice.docx");

            doc.Variables["Name"].Value = lbl_Forename.Text + " " + lbl_Surname.Text;

            doc.Variables["Address"].Value = lbl_Address.Text;

            doc.Variables["Town"].Value = lbl_Town.Text;

            doc.Variables["County"].Value = lbl_County.Text;

            doc.Variables["Phone_No"].Value = lbl_Phone.Text;

            doc.Variables["Date"].Value = lbl_Date.Text;

            doc.Variables["Balance"].Value = lbl_Acc_Balance.Text;

            doc.Variables["Id"].Value =  lbl_Customer_Id.Text;
            doc.Fields.Update();

            doc.SaveAs2("E:/CarRentalSystem/Invoice.docx2");

            doc.PrintOut();

            doc.Close();

            app.Quit();
        }
 public void Initialize() {
     this.HostItemHost = ((Microsoft.VisualStudio.Tools.Applications.Runtime.IHostItemProvider)(this.RuntimeCallback.GetService(typeof(Microsoft.VisualStudio.Tools.Applications.Runtime.IHostItemProvider))));
     this.DataHost = ((Microsoft.VisualStudio.Tools.Applications.Runtime.ICachedDataProvider)(this.RuntimeCallback.GetService(typeof(Microsoft.VisualStudio.Tools.Applications.Runtime.ICachedDataProvider))));
     object hostObject = null;
     this.HostItemHost.GetHostObject("Microsoft.Office.Interop.Word.Application", "Application", out hostObject);
     this.Application = ((Microsoft.Office.Interop.Word.Application)(hostObject));
     Globals.ThisAddIn = this;
     System.Windows.Forms.Application.EnableVisualStyles();
     this.InitializeCachedData();
     this.InitializeControls();
     this.InitializeComponents();
     this.InitializeData();
     this.BeginInitialization();
 }
Beispiel #4
1
        public void PrintReport()
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue = true;
            Object oFalse = false;

            oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            string activePrinter = oWord.ActivePrinter;
            if (string.IsNullOrEmpty(this.m_PrinterName) == false)
            {
                oWord.ActivePrinter = m_PrinterName;
            }

            Object oFile = this.m_ReportSaveFileName;
            Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref oFile, ref oMissing, ref oTrue,
                 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.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterMiddleBin;

            doc.PrintOut(ref oFalse, 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, ref oMissing, ref oMissing, ref oMissing);

            oWord.ActivePrinter = activePrinter;
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            //using Word = Microsoft.Office.Interop.Word;

            object fileName = Path.Combine(@"D:\VS2010Workspace\WordDocReplaceTest\WordDocReplaceTest\bin\Release", "TestDoc.docx");
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application { Visible = false };

            Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref fileName, ReadOnly: false, Visible: true);

            aDoc.Activate();

            Microsoft.Office.Interop.Word.Find fnd = wordApp.ActiveWindow.Selection.Find;

            fnd.ClearFormatting();
            fnd.Replacement.ClearFormatting();
            fnd.Forward = true;
            fnd.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;

            fnd.Text = "{替换前内容}";
            fnd.Replacement.Text = "替换后内容-updated";

            fnd.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            aDoc.Save();

            aDoc.Close(ref missing, ref missing, ref missing);
            wordApp.Quit(ref missing, ref missing, ref missing);
        }
Beispiel #6
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        fileName = FileUpload1.PostedFile.FileName;
        myfullPath = Server.MapPath("Files/" + fileName);
        FileUpload1.SaveAs(Server.MapPath("Files/" + fileName));
        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        object miss = System.Reflection.Missing.Value;

        object path = Server.MapPath("Files/" + fileName);
        object readOnly = true;
        Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
        string totaltext = "";
        for (int i = 0; i < docs.Paragraphs.Count; i++)
        {
            totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
        }

        PreviewTheoryTextBox.Text = totaltext;

        //kratao to onoma tou arxeiou doc se label pou den fainetai
        LabelToKeepFileName.Text = fileName;
        docs.Close();
        word.Quit();
        FileUpload1.Visible = false;
    }
        public static void SaveDocAsXPS(string fileName)
        {
            Microsoft.Office.Interop.Word.Application oWord;
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue = true;
            Object oFalse = false;

            oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;

            string currentPrinter = oWord.ActivePrinter;
            oWord.ActivePrinter = "Microsoft XPS Document Writer";

            Object docFileName = fileName;
            Object xpsFileName = fileName.Replace(".doc", ".xps");

            Object fileFormat = "wdFormatDocument";

            if (System.IO.File.Exists(docFileName.ToString()) == true)
            {
                Microsoft.Office.Interop.Word.Document doc = oWord.Documents.Open(ref docFileName, 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);

                object oOutputFile = xpsFileName;
                doc.PrintOut(ref oFalse, ref oFalse, ref oMissing, ref oOutputFile, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            }

            oWord.ActivePrinter = currentPrinter;
            oWord.Quit(ref oFalse, ref oMissing, ref oMissing);
        }
Beispiel #8
0
        private static string RevisarOrtografia(string texto)
        {
            var app = new Microsoft.Office.Interop.Word.Application();
            string corregido = string.Empty;
            if (!String.IsNullOrEmpty(texto))
            {
                app.Visible = false;
                object template = Missing.Value;
                object newTemplate = Missing.Value;
                object documentType = Missing.Value;
                object visible = false;

                Microsoft.Office.Interop.Word._Document doc1 = app.Documents.Add(ref template, ref newTemplate,
                                                                                 ref documentType, ref visible);
                doc1.Words.First.InsertBefore(texto);
                object optional = Missing.Value;
                doc1.CheckSpelling(
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional,
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);

                object first = 0;
                object last = doc1.Characters.Count - 1;
                corregido = doc1.Range(ref first, ref last).Text;
            }
            object saveChanges = false;
            object originalFormat = Missing.Value;
            object routeDocument = Missing.Value;
            app.Application.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
            return corregido;
        }
Beispiel #9
0
        public void CreateAWord()
        {
            //实例化word应用对象
            this._wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
            Object myNothing = System.Reflection.Missing.Value;

            this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing);
        }
        public SpellCheck()
        {
            this.m_WordApp =  new Microsoft.Office.Interop.Word.Application();
            this.m_WordApp.Visible = false;
            this.m_WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oTrue);

            InitializeComponent();
        }
 private WordApplication()
 {
     this.m_WordApp = new Microsoft.Office.Interop.Word.Application();
     this.m_WordApp.Visible = false;
     this.m_Documents = this.m_WordApp.Documents;
     this.m_Document = this.m_Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oTrue);
     this.m_WordSuggestionList = new List<string>();
 }
Beispiel #12
0
        void OpenFile(string filepath, int selectionstart)
        {
            cache["lastdir"] = Path.GetDirectoryName(filepath);
            string fileext = Path.GetExtension(filepath).ToLower();
            if (fileext == ".doc" || fileext == ".docx")
            {
                object oMissing = System.Reflection.Missing.Value;
                object isReadOnly = true;
                Microsoft.Office.Interop.Word._Application oWord;
                Microsoft.Office.Interop.Word._Document oDoc;

                oWord = new Microsoft.Office.Interop.Word.Application();
                oWord.Visible = false;
                object fileName = filepath;
                oDoc = oWord.Documents.Open(ref fileName,
                ref oMissing, ref isReadOnly, 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);

                this.rtbxMain.Text = oDoc.Content.Text;
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                if (MessageBox.Show("转换为RTF文档并重新打开?", "转换格式", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string newrtfpath = filepath + ".rtf";
                    this.rtbxMain.SaveFile(newrtfpath, RichTextBoxStreamType.RichText);
                    MessageBox.Show("转换为rtf成功.\r\n保存位置:" + newrtfpath, "转换格式");
                    OpenFile(newrtfpath, selectionstart);
                    return;
                }
            }
            else
            {
                FileStream fs = File.Open(filepath, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs, Encoding.Default, true);

                if (fileext == ".rtf")
                {
                    this.rtbxMain.Rtf = sr.ReadToEnd();
                    this.rtbxMain.Font = new Font("微软雅黑", 14f);
                }
                else
                {
                    rtbxMain.Text = sr.ReadToEnd();
                }
                sr.Close();
                fs.Close();
                fs.Dispose();
                sr.Dispose();
            }
            rtbxMain.SelectionStart = selectionstart;
            currentfilepath = filepath;
            this.Text = Path.GetFileNameWithoutExtension(currentfilepath);
            this.Icon = ((System.Drawing.Icon)(new System.ComponentModel.ComponentResourceManager(typeof(MainForm)).GetObject("$this.Icon")));
            tsmiReplaceWindowsTitle.Text = "隐藏标题";
            this.tsmiCurrentFilename.Text = this.Text;
            this.notifyIcon1.Text = this.Text;
        }
        public static DocumentWrapper OpenDocument(String path)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            DocumentWrapper wrapper = new DocumentWrapper();
            wrapper.Application = app;
            wrapper.Document = app.Documents.Open(path);

            return wrapper;
        }
 protected override void Initialize() {
     base.Initialize();
     this.Application = this.GetHostItem<Microsoft.Office.Interop.Word.Application>(typeof(Microsoft.Office.Interop.Word.Application), "Application");
     Globals.ThisAddIn = this;
     global::System.Windows.Forms.Application.EnableVisualStyles();
     this.InitializeCachedData();
     this.InitializeControls();
     this.InitializeComponents();
     this.InitializeData();
 }
Beispiel #15
0
 public void Dispose()
 {
     this._wordApplication.Quit();
     System.Runtime.InteropServices.Marshal.ReleaseComObject(this._wordApplication);
     System.Runtime.InteropServices.Marshal.ReleaseComObject(this._wordDocument);
     this._wordApplication = null;
     this._wordDocument = null;
     GC.Collect();
     GC.Collect();
 }
 public static String DoInteropDemo(String filePath)
 {
     var wordApp = new Microsoft.Office.Interop.Word.Application();
     Microsoft.Office.Interop.Word.Document doc =
         wordApp.Documents.Open(filePath, ReadOnly: true);
     dynamic docProperties = doc.BuiltInDocumentProperties;
     string authorName = docProperties["Author"].Value;
     doc.Close(SaveChanges: false);
     return authorName;
 }
Beispiel #17
0
        /// <summary>
        /// Implements the OnConnection method of the IDTExtensibility2 interface.
        /// Receives notification that the Add-in is being loaded.
        /// </summary>
        /// <param name="application">Root object of the host application.</param>
        /// <param name="connectMode"> Describes how the Add-in is being loaded.</param>
        /// <param name="addInInst">Object representing this Add-in.</param>
        /// <param name="custom"></param>
        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            _application = (Application) application;
            _presenter = new ApplicationPresenter(_application);
            _addInInstance = addInInst;

            if (connectMode != ext_ConnectMode.ext_cm_Startup)
            {
                OnStartupComplete(ref custom);
            }
        }
Beispiel #18
0
 private void btn_Read_Click(object sender, EventArgs e)
 {
     object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
     string[] P_str_Names = txt_Excel.Text.Split(',');//存储所有选择的Excel文件名
     object P_obj_Name;//存储遍历到的Excel文件名
     Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();//实例化Word对象
     if (txt_Word.Text.EndsWith("\\"))//判断路径是否以\结尾
         P_obj_WordName = txt_Word.Text + DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc";//记录Word文件路径及名称
     else
         P_obj_WordName = txt_Word.Text + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc";//记录Word文件路径及名称
     Microsoft.Office.Interop.Word.Table table;//声明Word表格对象
     Microsoft.Office.Interop.Word.Document document = new Microsoft.Office.Interop.Word.Document();//声明Word文档对象
     document = word.Documents.Add(ref missing, ref missing, ref missing, ref missing);//新建Word文档
     Microsoft.Office.Interop.Word.Range range ;//声明范围对象
     int P_int_Rows = 0, P_int_Columns = 0;//存储工作表中数据的行数和列数
     object P_obj_start = 0, P_obj_end = 0;//分别记录创建表格的开始和结束范围
     object P_obj_Range = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd;//定义要合并的范围位置
     for (int i = 0; i < P_str_Names.Length - 1; i++)//遍历所有选择的Excel文件名
     {
         P_obj_Name = P_str_Names[i];//记录遍历到的Excel文件名
         List<string> P_list_SheetName = CBoxBind(P_obj_Name.ToString());//获取指定Excel中的所有工作表
         for (int j = 0; j < P_list_SheetName.Count; j++)//遍历所有工作表
         {
             range = document.Range(ref missing, ref missing);//获取Word范围
             range.InsertAfter(P_obj_Name + "——" + P_list_SheetName[j] + "工作表");//插入文本
             range.Font.Name = "宋体";//设置字体
             range.Font.Size = 10;//设置字体大小
             DataSet myds = CBoxShowCount(P_obj_Name.ToString(), P_list_SheetName[j]);//获取工作表中的所有数据
             P_int_Rows = myds.Tables[0].Rows.Count;//记录工作表的行数
             P_int_Columns = myds.Tables[0].Columns.Count;//记录工作表的列数
             range.Collapse(ref P_obj_Range);//合并范围
             if (P_int_Rows > 0 && P_int_Columns > 0)//判断如果工作表中有记录
             {
                 //在指定范围处添加一个指定行数和列数的表格
                 table = range.Tables.Add(range, P_int_Rows, P_int_Columns, ref missing, ref missing);
                 for (int r = 0; r < P_int_Rows; r++)//遍历行
                 {
                     for (int c = 0; c < P_int_Columns; c++)//遍历列
                     {
                         table.Cell(r + 1, c + 1).Range.InsertAfter(myds.Tables[0].Rows[r][c].ToString());//将遍历到的数据添加到Word表格中
                     }
                 }
             }
             object P_obj_Format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;//定义Word文档的保存格式
             word.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;//设置保存时不显示对话框
             //保存Word文档
             document.SaveAs(ref P_obj_WordName, ref P_obj_Format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
         }
     }
     document.Close(ref missing, ref missing, ref missing);//关闭Word文档
     word.Quit(ref missing, ref missing, ref missing);//退出Word应用程序
     MessageBox.Show("已经成功将多个Excel文件的内容读取到了一个Word文档中!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
Beispiel #19
0
        public ReporterMSWord(ReportData inputData
            , string templatePath, string outputFilePath, Margins margins)
        {
            // absolute output file path
            string absOutputFilePath = string.Empty;
            if (Path.IsPathRooted(outputFilePath))
                absOutputFilePath = outputFilePath;
            else
                absOutputFilePath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), outputFilePath));
            // absolute template path
            string absTemplatePath = string.Empty;
            if (Path.IsPathRooted(templatePath))
                absTemplatePath = templatePath;
            else
                absTemplatePath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), templatePath));

            // does output directory exists
            string outDir = Path.GetDirectoryName(absOutputFilePath);
            if (!Directory.Exists(outDir))
            {
                try { Directory.CreateDirectory(outDir); }
                catch (System.UnauthorizedAccessException /*ex*/)
                { throw new UnauthorizedAccessException(string.Format("User not allowed to write under {0}", Directory.GetParent(outDir).FullName)); }
                catch (Exception ex)
                { throw new Exception(string.Format("Directory {0} does not exist, and could not be created.", outDir), ex); }
            }
            // html file path
            string htmlFilePath = Path.ChangeExtension(absOutputFilePath, "html");
            BuildAnalysisReport(inputData, absTemplatePath, htmlFilePath);
            // opens word
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            wordApp.Visible = true;
            Microsoft.Office.Interop.Word.Document wordDoc = wordApp.Documents.Open(htmlFilePath, false, true, NoEncodingDialog: true);
            // embed pictures (unlinking images)
            for (int i = 1; i <= wordDoc.InlineShapes.Count; ++i)
            {
                if (null != wordDoc.InlineShapes[i].LinkFormat && !wordDoc.InlineShapes[i].LinkFormat.SavePictureWithDocument)
                    wordDoc.InlineShapes[i].LinkFormat.SavePictureWithDocument = true;
            }
            // set margins (unit?)
            wordDoc.PageSetup.TopMargin = wordApp.CentimetersToPoints(margins.Top);
            wordDoc.PageSetup.BottomMargin = wordApp.CentimetersToPoints(margins.Bottom);
            wordDoc.PageSetup.RightMargin = wordApp.CentimetersToPoints(margins.Right);
            wordDoc.PageSetup.LeftMargin = wordApp.CentimetersToPoints(margins.Left);
            // set print view 
            wordApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
            wordDoc.SaveAs(absOutputFilePath, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault);
            _log.Info(string.Format("Saved doc report to {0}", outputFilePath));
            // delete image directory
            DeleteImageDirectory();
            // delete html report
            File.Delete(htmlFilePath);
        }
        /// <summary>
        /// Закрытие приложения
        /// </summary>
        public void QuitApplication()
        {
            if (application != null)
            {
                range = null;
                table = null;
                document = null;
                application.Quit();
                application = null;                
            }

        }
Beispiel #21
0
 private void btn_Read_Click(object sender, EventArgs e)
 {
     Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();//实例化Word对象
     Microsoft.Office.Interop.Word.Table table;//声明Word表格对象
     int P_int_TableCount = 0, P_int_Row = 0, P_int_Column = 0;//定义3个变量,分别用来存储表格数量、表格中的行数、列数
     string P_str_Content;//存储Word表格的单元格内容
     object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
     string[] P_str_Names = txt_Word.Text.Split(',');//存储所有选择的Word文件名
     object P_obj_Name;//存储遍历到的Word文件名
     Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//实例化Excel对象
     //打开指定的Excel文件
     Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Open(txt_Excel.Text, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
     Microsoft.Office.Interop.Excel.Worksheet newWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add(missing, missing, missing, missing);//创建新工作表
     for (int i = 0; i < P_str_Names.Length - 1; i++)//遍历所有选择Word文件名
     {
         P_obj_Name = P_str_Names[i];//记录遍历到的Word文件名
         //打开Word文档
         Microsoft.Office.Interop.Word.Document document = word.Documents.Open(ref P_obj_Name, 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);
         P_int_TableCount = document.Tables.Count;//获取Word文档中表格的数量
         if (P_int_TableCount > 0)//判断表格数量是否大于0
         {
             for (int j = 1; j <= P_int_TableCount; j++)//遍历所有表格
             {
                 table = document.Tables[j];//记录遍历到的表格
                 P_int_Row = table.Rows.Count;//获取表格行数
                 P_int_Column = table.Columns.Count;//获取表格列数
                 for (int row = 1; row <= P_int_Row; row++)//遍历表格中的行
                 {
                     for (int column = 1; column <= P_int_Column; column++)//遍历表格中的列
                     {
                         P_str_Content = table.Cell(row, column).Range.Text;//获取遍历到的单元格内容
                         newWorksheet.Cells[i + row, column] = P_str_Content.Substring(0, P_str_Content.Length - 2);//将遍历到的单元格内容添加到Excel单元格中
                     }
                 }
             }
         }
         else
         {
             if (P_int_Row == 0)//判断前面是否已经填充过表格
                 newWorksheet.Cells[i + P_int_Row + 1, 1] = document.Content.Text;//直接将Word文档内容添加到工作表中
             else
                 newWorksheet.Cells[i + P_int_Row, 1] = document.Content.Text;//直接将Word文档内容添加到工作表中
         }
         document.Close(ref missing, ref missing, ref missing);//关闭Word文档
     }
     excel.Application.DisplayAlerts = false;//不显示提示对话框
     workbook.Save();//保存工作表
     workbook.Close(false, missing, missing);//关闭工作表
     word.Quit(ref missing, ref missing, ref missing);//退出Word应用程序
     MessageBox.Show("已经成功将多个Word文档的内容合并到了Excel的同一个数据表中!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
        public void ReadExcel()
        {
            //Application excel = new Application();
            //var sheet = excel.Worksheets[1];
            //sheet.Shapes.AddOLEObject

            object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();//创建word对象
            word.Visible = true;//显示出来
            Microsoft.Office.Interop.Word.Document dcu = word.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);//创建一个新的空文档,格式为默认的
            dcu.Activate();//激活当前文档
            object type = @"Excel.Sheet.12";//插入的excel 格式,这里我用的是excel 2010,所以是.12
            object filename = @"D:\Life.xlsx";//插入的excel的位置
            word.Selection.InlineShapes.AddOLEObject(ref type, ref filename, ref oMissing, ref oMissing);//执行插入操作

            //Console.ReadKey();
        }
        // Will print discharge paper's for the patient
        private void dischargePatient_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();//you need this
            var myWordDoc = app.Documents.Open(@"F:\PIMS_Final\PIMS DISCHARGE FORM.docx", ReadOnly: false, Visible: true);//filepath of document
            app.Visible = true;

            Microsoft.Office.Interop.Word.Find fndlastName = myWordDoc.ActiveWindow.Selection.Find;
            fndlastName.Text = "@lname";
            fndlastName.Replacement.Text = Program.currentPatient.directory.lName.ToString();
            fndlastName.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            Microsoft.Office.Interop.Word.Find fndfirstName = myWordDoc.ActiveWindow.Selection.Find;
            fndfirstName.Text = "@fname";
            fndfirstName.Replacement.Text = Program.currentPatient.directory.fName.ToString();
            fndfirstName.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            /*
            Microsoft.Office.Interop.Word.Find fndfirstName = myWordDoc.ActiveWindow.Selection.Find;
            fndfirstName.Text = "@fname";
            fndfirstName.Replacement.Text = Program.currentPatient.directory.fName.ToString();
            fndfirstName.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            Microsoft.Office.Interop.Word.Find fndfirstName = myWordDoc.ActiveWindow.Selection.Find;
            fndfirstName.Text = "@fname";
            fndfirstName.Replacement.Text = Program.currentPatient.directory.fName.ToString();
            fndfirstName.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            Microsoft.Office.Interop.Word.Find fndfirstName = myWordDoc.ActiveWindow.Selection.Find;
            fndfirstName.Text = "@fname";
            fndfirstName.Replacement.Text = Program.currentPatient.directory.fName.ToString();
            fndfirstName.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            Microsoft.Office.Interop.Word.Find fndfirstName = myWordDoc.ActiveWindow.Selection.Find;
            fndfirstName.Text = "@fname";
            fndfirstName.Replacement.Text = Program.currentPatient.directory.fName.ToString();
            fndfirstName.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            Microsoft.Office.Interop.Word.Find fndfirstName = myWordDoc.ActiveWindow.Selection.Find;
            fndfirstName.Text = "@fname";
            fndfirstName.Replacement.Text = Program.currentPatient.directory.fName.ToString();
            fndfirstName.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            */
            myWordDoc.SaveAs2(@"F:\PIMS_Final\" + Program.currentPatient.directory.lName + "." + Program.currentPatient.directory.fName + ".Discharge Form.docx");
            myWordDoc.PrintPreview();

            updateMyPatient();
        }
        public void CreateDocument()
        {
            string filePath = Path.GetTempFileName() + ".docx";
            try
            {
                //Create an instance for word app
                winword = new Microsoft.Office.Interop.Word.Application();

                //Set animation status for word application
                //winword. ShowAnimation = false;

                //Set status for word application is to be visible or not.
                winword.Visible = false;

                //Create a new document
                document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                this.PrintTree(ClasificacionSingleton.Clasificacion, 0);

                foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                {
                    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdGray50;
                    footerRange.Font.Size = 12;
                    footerRange.Text = DateTimeUtilities.ToLongDateFormat(DateTime.Now);
                }

                //Save the document
                object filename = filePath;
                document.SaveAs2(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                MessageBox.Show("Estructura generada satisfactoriamente!");

                System.Diagnostics.Process.Start(filePath);
            }
            catch (Exception ex)
            {
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                ErrorUtilities.SetNewErrorMessage(ex, methodName + " Exception,PdfTreeStructure", "MateriasSGA");
            }
        }
Beispiel #25
0
        public void DocGereration(string FileName)
        {
            var WordApp = new Microsoft.Office.Interop.Word.Application();
            WordApp.Visible = false;
            var doc = WordApp.Documents.Open(FileName);
            string fio = this.lname_text.Text + " " +
                this.fname_text.Text + " " +
                this.sname_text.Text; 
            DocForm.Form("{FIO}", fio, doc);
            DocForm.Form("{Berzday}", this.datarozdenia_text.Text, doc);
            DocForm.Form("{NUM}", this.num_spec_text.Text, doc);
            DocForm.Form("{SPEH}", this.name_spec_text.Text, doc);
            DocForm.Form("{OSNOVA}", this.oplata_text.Text, doc);
            DocForm.Form("{N}", this.num_pricaz_text.Text, doc);
            DocForm.Form("{D}", this.data_pricaz_text.Text, doc);
            DocForm.Form("{SROC}", this.oconhanie_text.Text, doc);

            WordApp.Visible = true;
        }
Beispiel #26
0
 public void GetFileCount(string path,out int FileCount)
 {
     FileCount = 1;
     object tempFileName = path;
     FileInfo fi = new FileInfo(path);
     string astdt = fi.Extension;
     object strFileName = fi.Name;
     object flg = false;
     object oMissing = System.Reflection.Missing.Value;
     switch (astdt.ToLower())
     {
         case ".doc":
         case ".docx":
             astdt = "pdf";
             Microsoft.Office.Interop.Word._Application oWord;
             Microsoft.Office.Interop.Word._Document oDoc;
             oWord = new Microsoft.Office.Interop.Word.Application();
             //oWord.Visible = true;
             oDoc = oWord.Documents.Open(ref tempFileName,
             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);
             try
             {
                 // 计算Word文档页数
                 Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
                 FileCount = oDoc.ComputeStatistics(stat, ref oMissing);
                 return;
             }
             catch (Exception ex)
             {
                 if (oDoc == null) XLog.XTrace.WriteLine(ex.Message);
                 throw (ex);
             }
             finally
             {
                 oDoc.Close(ref flg, ref oMissing, ref oMissing);
                 oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
             }
         default:
             break;
     }
 }
Beispiel #27
0
        public static string GetText(string filePath)
        {
            var rangeText = "ERROR: Failed to get text";

            var assembly = Assembly.GetExecutingAssembly();
            var binPath = System.IO.Path.GetDirectoryName(assembly.Location);

            var inputFile = Path.Combine(binPath, filePath);

            //  create & define filename object with temp.doc
            object inputDocFilename = inputFile;

            if (File.Exists((string)inputDocFilename))
            {
                object readOnly = false;
                object isVisible = false;

                //  create missing object
                object missing = Missing.Value;

                //  create Word application object
                var wordApp = new Microsoft.Office.Interop.Word.Application();

                wordApp.Visible = false;

                var inputDocument = wordApp.Documents.Open(ref inputDocFilename, 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);

                inputDocument.Activate();

                rangeText = inputDocument.Range().Text;

                inputDocument.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);

                wordApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
            }

            return rangeText;
        }
Beispiel #28
0
        public string Addsupervisordata(WordTableInfo Info)
        {
            Common.Common.load_supervisor();
            object missingValue = System.Reflection.Missing.Value;
            object myTrue = false;                  //不显示Word窗口
            //object fileName = Environment.CurrentDirectory + "\\" + "chief_supervisor.doc";
            object fileName1 = Environment.CurrentDirectory + "\\" + "supervisor.doc";
            string newfile = Common.Common.strAddfilesPath+ "\\" + Info.Teacher + Info.Time.Trim() + Info.Supervisor + ".doc";
            Microsoft.Office.Interop.Word._Application oWord1 = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word._Document oDoc1;
            oDoc1 = oWord1.Documents.Open(ref fileName1, ref missingValue,
               ref myTrue, ref missingValue, ref missingValue, ref missingValue,
               ref missingValue, ref missingValue, ref missingValue,
               ref missingValue, ref missingValue, ref missingValue,
               ref missingValue, ref missingValue, ref missingValue,
               ref missingValue);
            Microsoft.Office.Interop.Word.Table newtable1 = oDoc1.Tables[1];
            oWord1.Selection.TypeText("广东医学院教师课堂教学质量评价表" + "(" + Info.Teachingtype + ")");
            newtable1.Cell(1, 2).Range.Text = Info.Teacher;
            newtable1.Cell(1, 4).Range.Text = Info.Perfession;
            newtable1.Cell(1, 6).Range.Text = Info.Time.Substring(0, Info.Time.IndexOf(" "));
            newtable1.Cell(2, 2).Range.Text = Info.Class;
            newtable1.Cell(2, 4).Range.Text = Info.Classroom + Info.Time.Substring(Info.Time.IndexOf(" ") + 1);
            newtable1.Cell(3, 2).Range.Text = Info.Subject;
            object bSaveChange = true;
            oDoc1.Close(ref bSaveChange, ref missingValue, ref missingValue);
            oDoc1 = null;
            oWord1 = null;

            closefile();
            if (!System.IO.File.Exists(Common.Common.strAddfilesPath))
            {
                Directory.CreateDirectory(Common.Common.strAddfilesPath);
            }
            System.IO.File.Copy(fileName1.ToString(), newfile, true);

            File.Delete(fileName1.ToString());
            return newfile;
               // sent_email(Supervisor, Time, Subject, newfile);
            // movetofile(newfile);
            //File.Move(newfile, cCommon.strAddfilesPath);
        }
Beispiel #29
0
        //首席
        public string Addchiefsupervisordata(WordTableInfo Info)
        {
            Common.Common.load_cheif_supervisor();
            object missingValue = System.Reflection.Missing.Value;
            object myTrue = false;                  //不显示Word窗口
            object fileName = Environment.CurrentDirectory + "\\" + "chief_supervisor.doc";//WORD文档所在路径
            string newfile =  Common.Common.strAddfilesPath + Info.Teacher + Info.Time.Trim() + Info.Supervisor + ".doc";//存储路径名称
            // object fileName1 = Environment.CurrentDirectory + "\\" + "supervisor.doc";
            Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word._Document oDoc;
            oDoc = oWord.Documents.Open(ref fileName, ref missingValue,
               ref myTrue, ref missingValue, ref missingValue, ref missingValue,
               ref missingValue, ref missingValue, ref missingValue,
               ref missingValue, ref missingValue, ref missingValue,
               ref missingValue, ref missingValue, ref missingValue,
               ref missingValue);
            Microsoft.Office.Interop.Word.Table newtable = oDoc.Tables[1];//获取word文档中的表格
            newtable.Cell(1, 2).Range.Text = Info.Teacher;
            newtable.Cell(1, 6).Range.Text = Info.Time.Substring(0, Info.Time.IndexOf(" "));
            newtable.Cell(2, 6).Range.Text = Info.Classroom + Info.Time.Substring(Info.Time.IndexOf(" ") + 1);
            newtable.Cell(4, 2).Range.Text = Info.Class;
            newtable.Cell(5, 2).Range.Text = Info.Subject;
            object bSaveChange = true;
            oDoc.Close(ref bSaveChange, ref missingValue, ref missingValue);
            oDoc = null;
            oWord = null;

            closefile();
            if (!System.IO.File.Exists(Common.Common.strAddfilesPath))
            {
                Directory.CreateDirectory(Common.Common.strAddfilesPath);
            }

            System.IO.File.Copy(fileName.ToString(), newfile, true);

            File.Delete(fileName.ToString());
            //sent_email(Supervisor, Time, Subject, newfile);
            //movetofile(newfile);
            return newfile;
        }
        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                //creating object for missing value
                object missing = System.Reflection.Missing.Value;
                //object for end of file
                object endofdoc = "\\endofdoc";

                //creating instance of word application
                Microsoft.Office.Interop.Word._Application w = new Microsoft.Office.Interop.Word.Application();
                //creating instance of word document
                Microsoft.Office.Interop.Word._Document doc;
                //setting status of application to visible
                w.Visible = true;
                //creating new document
                doc = w.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                //adding paragraph to document
                Microsoft.Office.Interop.Word.Paragraph para1;
                para1 = doc.Content.Paragraphs.Add(ref missing);
                object styleHeading1 = "Heading 1";
                para1.Range.set_Style(ref styleHeading1);
                para1.Range.Text = "Heading One";
                para1.Range.Font.Bold = 1;
                para1.Format.SpaceAfter = 24;
                para1.Range.InsertParagraphAfter();
                //creating second paragraph
                Microsoft.Office.Interop.Word.Paragraph para2;
                para2 = doc.Content.Paragraphs.Add(ref missing);
                para2.Range.Text = "Heading OneHeading OneHeading OneHeading OneHeading OneHeading OneHeading" + '\n' + "OneHeading OneHeading OneHeading OneHeading OneHeading OneHeading One";
                para2.Range.Font.Bold = 1;
                para2.Format.SpaceAfter = 24;
                para2.Range.InsertParagraphAfter();
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "error", "javascript:;alert('" + ex.Message + "')");
            }
        }
Beispiel #31
0
        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            if (dataGridView1.Rows.Count != 0)
            {
                int            index = dataGridView1.CurrentRow.Index;
                OpenFileDialog ofd   = new OpenFileDialog();
                ofd.FileName = dataGridView1.Rows[index].Cells[4].Value.ToString();
                Pre_arrangeList temp_Pre_arrangeList = new Pre_arrangeList();
                temp_Pre_arrangeList            = pre_arrangeList[index];
                temp_Pre_arrangeList.ReviseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                List <Pre_arrangeList> Re_pre_arrangeList = new List <Pre_arrangeList>();
                Re_pre_arrangeList.Add(temp_Pre_arrangeList);
                temp_Pre_Command.Pre_arrangeList_ReviseData(Re_pre_arrangeList);

                m_word = new Microsoft.Office.Interop.Word.Application();
                Object filename              = dataGridView1.Rows[index].Cells[0].Value;
                Object filefullname          = dataGridView1.Rows[index].Cells[4].Value.ToString();
                Object confirmConversions    = Type.Missing;
                Object readOnly              = Type.Missing;
                Object addToRecentFiles      = Type.Missing;
                Object passwordDocument      = Type.Missing;
                Object passwordTemplate      = Type.Missing;
                Object revert                = Type.Missing;
                Object writePasswordDocument = Type.Missing;
                Object writePasswordTemplate = Type.Missing;
                Object format                = Type.Missing;
                Object encoding              = Type.Missing;
                Object visible               = Type.Missing;
                Object openConflictDocument  = Type.Missing;
                Object openAndRepair         = Type.Missing;
                Object documentDirection     = Type.Missing;
                Object noEncodingDialog      = Type.Missing;

                for (int i = 1; i <= m_word.Documents.Count; i++)
                {
                    String str = m_word.Documents[i].FullName.ToString();
                    if (str == filefullname.ToString())
                    {
                        MessageBox.Show("请勿重复打开该文档");
                        return;
                    }
                }
                try
                {
                    m_word.Documents.Open(ref filefullname,
                                          ref confirmConversions, ref readOnly, ref addToRecentFiles,
                                          ref passwordDocument, ref passwordTemplate, ref revert,
                                          ref writePasswordDocument, ref writePasswordTemplate,
                                          ref format, ref encoding, ref visible, ref openConflictDocument,
                                          ref openAndRepair, ref documentDirection, ref noEncodingDialog
                                          );
                    m_word.Visible = true;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("打开Word文档出错");
                }
            }
            button2.Enabled = true;
        }
Beispiel #32
0
        //returns paths
        public async Task <List <string> > generateTicketsAndSave(List <Participant> participants, List <Event> events, CompanyData companyData)
        {
            if (MSdoc == null)
            {
                MSdoc = new Microsoft.Office.Interop.Word.Application();
            }
            pdfConverter = new PDFConverter(MSdoc);
            List <string> ticketsPaths = new List <string>();

            foreach (Event ev in events)
            {
                Dictionary <int, string> eventImagesPaths = new Dictionary <int, string>();
                List <ImageEntity>       imageEntities    = await imageEntityServices.GetEventImageEntities(ev);

                foreach (ImageEntity ie in imageEntities)
                {
                    string imagePath = await imageEntityServices.downloadEventImage(ie, imagesSavingPath);

                    eventImagesPaths.Add(Int32.Parse(ie.imageNumber.ToString()), imagePath);
                }
                eventsImagesPaths.Add(ev.eventName, eventImagesPaths);
            }
            List <ImageEntity> companyImageEntity = await imageEntityServices.GetCompanyImageEntities();

            string companyImagePath = "";

            if (companyImageEntity.Count > 0)
            {
                companyImagePath = await imageEntityServices.downloadCompanyImage(companyImageEntity[0], imagesSavingPath);
            }
            foreach (Participant participant in participants)
            {
                Event  participantEvent     = events.FindLast(e => e.id.ToString().Equals(participant.eventId));
                string eventDate            = formatEventDate(participantEvent.date_From);
                string eventImagePath       = "";
                bool   gotEventImagePath    = eventsImagesPaths[participantEvent.eventName].TryGetValue(1, out eventImagePath);
                string sponsorsImagePath    = "";
                bool   gotSponsorsImagePath = eventsImagesPaths[participantEvent.eventName].TryGetValue(2, out eventImagePath);
                if (!gotEventImagePath)
                {
                    eventImagePath = "";
                }
                if (!gotSponsorsImagePath)
                {
                    sponsorsImagePath = "";
                }

                System.Drawing.Image image = GenerateCompanyCredentialsImage(companyData.companyName,
                                                                             companyData.address, companyData.email, companyData.phoneNumber, participantEvent.webPage);
                string ticketPath = createTicket(
                    participant.firstName,
                    participant.lastName,
                    participant.companyName,
                    participant.participationFormat,
                    participantEvent.eventName,
                    eventDate,
                    participantEvent.date_From.Month,
                    participantEvent.venueName,
                    participantEvent.venueAdress,
                    participant.ticketBarcode,
                    System.Drawing.Color.Black,
                    participantEvent.eventName + participant.participantId,
                    companyImagePath,
                    eventImagePath,
                    sponsorsImagePath,
                    ""
                    );
                ticketsPaths.Add(ticketPath);
            }
            if (MSdoc != null)
            {
                object Unknown = Type.Missing;
                MSdoc.Documents.Close(ref Unknown, ref Unknown, ref Unknown);
                MSdoc.Quit(ref Unknown, ref Unknown, ref Unknown);
            }
            return(ticketsPaths);
        }
Beispiel #33
0
        public static void contratTravail(string raison, string spécialité, string wilaya, string Rc, string matricule_fiscal, string matricule, string nom, string prenom, string date_naissance, string wilaya_naissance, string adresse, string date_embauche, string poste, string salaire, string gérant, string chemin, string chemin1)
        {
            Microsoft.Office.Interop.Word.Application _ApplicationWord = new Microsoft.Office.Interop.Word.Application();
            _ApplicationWord.Visible = false;
            string path      = chemin1 + "\\Modeles\\REF-CONTRAT DE TRAVAIL .docx";
            object oFileName = (object)@path;
            object Faux      = (object)false;
            object Vrai      = (object)true;
            object M         = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word._Document _MonDocument = _ApplicationWord.Documents.Add(ref oFileName, ref Faux, ref M, ref Vrai);

            object Nom   = (object)"adresse";
            object Nom1  = (object)"DateEmbauche";
            object Nom2  = (object)"DateEmbauche1";
            object Nom3  = (object)"DateNaissance";
            object Nom4  = (object)"gérant";
            object Nom5  = (object)"matricule";
            object Nom6  = (object)"NomPrénom";
            object Nom7  = (object)"poste";
            object Nom8  = (object)"raison";
            object Nom9  = (object)"raison1";
            object Nom10 = (object)"raison2";
            object Nom11 = (object)"raison3";
            object Nom12 = (object)"raison4";
            object Nom13 = (object)"raison5";
            object Nom14 = (object)"raison6";
            object Nom15 = (object)"raison7";
            object Nom16 = (object)"RcMatriculeFiscal";
            object Nom17 = (object)"salaire";
            object Nom18 = (object)"salaire1";
            object Nom19 = (object)"spécialité";
            object Nom20 = (object)"wilaya";
            object Nom21 = (object)"WilayaNaissance";
            object Nom22 = (object)"logo";

            Microsoft.Office.Interop.Word.Bookmark    _MonSignet;
            Microsoft.Office.Interop.Word.Range       _MonRange;
            Microsoft.Office.Interop.Word.InlineShape _MonImage;



            //récupére la liste de signets
            Microsoft.Office.Interop.Word.Bookmarks _MesSignets = _MonDocument.Bookmarks;


            if (_MesSignets.Exists("adresse"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(adresse);
            }
            if (_MesSignets.Exists("DateEmbauche"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom1);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(date_embauche);
            }
            if (_MesSignets.Exists("DateEmbauche1"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom2);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(date_embauche);
            }
            if (_MesSignets.Exists("DateNaissance"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom3);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(date_naissance);
            }
            if (_MesSignets.Exists("gérant"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom4);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(gérant);
            }
            if (_MesSignets.Exists("matricule"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom5);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(matricule);
            }
            if (_MesSignets.Exists("NomPrénom"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom6);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(" " + nom + " " + prenom + " ");
            }
            if (_MesSignets.Exists("poste"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom7);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(poste);
            }
            if (_MesSignets.Exists("raison"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom8);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("raison1"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom9);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("raison2"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom10);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("raison3"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom11);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("raison4"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom12);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("raison5"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom13);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("raison6"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom14);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("raison7"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom15);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("RcMatriculeFiscal"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom16);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(Rc + "/" + matricule_fiscal);
            }
            if (_MesSignets.Exists("salaire"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom17);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                double sal = (Convert.ToDouble(salaire)) * 12;
                _MonRange.InsertAfter(Convert.ToString(sal));
            }
            if (_MesSignets.Exists("salaire1"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom18);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(salaire);
            }
            if (_MesSignets.Exists("spécialité"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom19);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(spécialité);
            }
            if (_MesSignets.Exists("wilaya"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom20);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(wilaya);
            }
            if (_MesSignets.Exists("WilayaNaissance"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom21);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(wilaya_naissance);
            }
            if (_MesSignets.Exists("logo"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom22);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonImage = _MonRange.InlineShapes.AddPicture($@"{System.IO.Directory.GetCurrentDirectory()}\logo.png", ref Faux, ref Vrai, ref M);
            }



            oFileName = @chemin;
            try
            {
                _MonDocument.SaveAs(ref oFileName, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M);
            }
            catch (Exception e) { }
            _MonDocument.Close(ref M, ref M, ref M);
            _ApplicationWord.Application.Quit(ref M, ref M, ref M);
        }
Beispiel #34
0
        /// <summary>
        /// Creates a word doc and launches word
        /// </summary>
        /// <param name="fileName">name of the file to create</param>
        /// <returns>true on success</returns>
        private bool createAndLaunchWordDoc(String fileName)
        {
            bool retVal     = true;
            bool comCreated = false;

            Microsoft.Office.Interop.Word.Application wordApp = null;
            try
            {
                try
                {
                    wordApp = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                }
                catch (Exception e)
                {
                    Log.Exception(e);
                    wordApp = null;
                }

                if (wordApp == null)
                {
                    wordApp = new Microsoft.Office.Interop.Word.Application();
                }
                else
                {
                    comCreated = true;
                }

                Microsoft.Office.Interop.Word.Document adoc = wordApp.Documents.Add();
                object missing = System.Reflection.Missing.Value;
                object f       = fileName;
                adoc.SaveAs(
                    ref f,
                    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);

                adoc.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges, ref missing, ref missing);
                if (comCreated)
                {
                    Marshal.ReleaseComObject(wordApp);
                }

                wordApp = null;
                Process.Start(fileName);
                waitForWordWindow(fileName);
            }
            catch (Exception ex)
            {
                Log.Debug(ex.ToString());
                retVal = false;
            }
            finally
            {
                if (wordApp != null)
                {
                    Marshal.FinalReleaseComObject(wordApp);
                }
            }

            return(retVal);
        }
Beispiel #35
0
        private void save()
        {
            this.Enabled = true;
            Directory.CreateDirectory(".\\" + main.companyName + "\\wjgl\\6\\" + a0.Text + "");

            string temp = System.IO.Directory.GetCurrentDirectory();// d当前运行路径

            //    MessageBox.Show(temp);
            string OrignFile;//word模板路径

            OrignFile = "\\baseDB\\商标书式\\6 商标代理委托书\\商标代理委托书(示范文本).dot";

            //开始写入数据

            string parFilePath = temp + OrignFile;//文件路径
            object FilePath    = parFilePath;

            Microsoft.Office.Interop.Word._Application AppliApp = new Microsoft.Office.Interop.Word.Application();
            AppliApp.Visible = false;
            Microsoft.Office.Interop.Word._Document doc = AppliApp.Documents.Add(ref FilePath);
            object missing    = System.Reflection.Missing.Value;
            object isReadOnly = false;



            doc.Activate();

            //数据写入代码段


            object aa = temp + "\\" + main.companyName + "\\wjgl\\6\\" + a0.Text + "\\" + a0.Text + ".docx";

            object[] MyBM = new object[57]; //创建一个书签数组

            for (int i = 0; i < 4; i++)     //给书签数组赋值
            {
                MyBM[i] = "a" + (i + 1).ToString();
            }
            for (int i = 4; i < 42; i++)
            {
                MyBM[i] = "a5_" + (i - 3).ToString();
            }
            for (int i = 42; i < 55; i++)
            {
                MyBM[i] = "a" + (i - 36).ToString();
            }
            MyBM[46] = "a10_1";
            MyBM[55] = "a10_2";
            MyBM[56] = "a10_3";
            //给对应的书签位置写入数据
            doc.Bookmarks.get_Item(ref MyBM[0]).Range.Text = a1.Text;
            doc.Bookmarks.get_Item(ref MyBM[1]).Range.Text = a2.Text;
            doc.Bookmarks.get_Item(ref MyBM[2]).Range.Text = a3.Text;
            doc.Bookmarks.get_Item(ref MyBM[3]).Range.Text = a4.Text;

            if (a5.Text == "商标注册申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[4]).Range.Text = "✔";
            }
            else if (a5.Text == "商标异议申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[5]).Range.Text = "✔";
            }
            else if (a5.Text == "商标异议答辩")
            {
                doc.Bookmarks.get_Item(ref MyBM[6]).Range.Text = "✔";
            }
            else if (a5.Text == "更正商标申请/注意事项申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[7]).Range.Text = "✔";
            }
            else if (a5.Text == "变更商标申请人/注册人名义/地址 变更集体商标/证明商标管理规则/集体成员名单申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[8]).Range.Text = "✔";
            }
            else if (a5.Text == "变更商标代理人/文件接收人申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[9]).Range.Text = "✔";
            }
            else if (a5.Text == "删减商品/服务项目申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[10]).Range.Text = "✔";
            }
            else if (a5.Text == "商标续展注册申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[11]).Range.Text = "✔";
            }
            else if (a5.Text == "商标注册申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[12]).Range.Text = "✔";
            }
            else if (a5.Text == "转让/移转申请/注册商标申请书")
            {
                doc.Bookmarks.get_Item(ref MyBM[13]).Range.Text = "✔";
            }
            else if (a5.Text == "商标使用许可备案")
            {
                doc.Bookmarks.get_Item(ref MyBM[14]).Range.Text = "✔";
            }
            else if (a5.Text == "变更许可人/被许可人名称备案")
            {
                doc.Bookmarks.get_Item(ref MyBM[15]).Range.Text = "✔";
            }
            else if (a5.Text == "商标专用权质权登记申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[16]).Range.Text = "✔";
            }
            else if (a5.Text == "商标专用权质权登记事项变更申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[17]).Range.Text = "✔";
            }
            else if (a5.Text == "商标专用权质权登记期限延期申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[18]).Range.Text = "✔";
            }
            else if (a5.Text == "商标专用权质权登记证补发申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[19]).Range.Text = "✔";
            }
            else if (a5.Text == "商标专用权质权登记注销申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[20]).Range.Text = "✔";
            }
            else if (a5.Text == "商标注销申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[21]).Range.Text = "✔";
            }
            else if (a5.Text == "撤销连续三年不使用注册商标申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[22]).Range.Text = "✔";
            }
            else if (a5.Text == "撤销成为商品/服务通用名称注册商标申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[23]).Range.Text = "✔";
            }
            else if (a5.Text == "撤销连续三年不使用注册商标提供证据")
            {
                doc.Bookmarks.get_Item(ref MyBM[24]).Range.Text = "✔";
            }
            else if (a5.Text == "撤销成为商品/服务通用名称注册商标答辩")
            {
                doc.Bookmarks.get_Item(ref MyBM[25]).Range.Text = "✔";
            }
            else if (a5.Text == "补发变更/转让/续展证明申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[26]).Range.Text = "✔";
            }
            else if (a5.Text == "补发商标注册证申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[27]).Range.Text = "✔";
            }
            else if (a5.Text == "出具商标注册证明申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[28]).Range.Text = "✔";
            }
            else if (a5.Text == "出具优先权证明文件申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[29]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回商标注册申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[30]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回商标异议申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[31]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回变更商标申请人/注册人名义/地址 变更集体商标/证明商标管理规则/集体成员名单申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[32]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回变更商标代理人/文件接收人申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[33]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回删减商品/服务项目申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[34]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回商标续展注册申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[35]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回转让/移转申请/注册商标申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[36]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回商标使用许可备案")
            {
                doc.Bookmarks.get_Item(ref MyBM[37]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回商标注销申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[38]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回撤销连续三年不使用注册商标申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[39]).Range.Text = "✔";
            }
            else if (a5.Text == "撤回撤销成为商品/服务通用名称注册商标申请")
            {
                doc.Bookmarks.get_Item(ref MyBM[40]).Range.Text = "✔";
            }
            else
            {
                doc.Bookmarks.get_Item(ref MyBM[41]).Range.Text = a5.Text;
            }

            doc.Bookmarks.get_Item(ref MyBM[42]).Range.Text = a6.Text;
            doc.Bookmarks.get_Item(ref MyBM[43]).Range.Text = a7.Text;
            doc.Bookmarks.get_Item(ref MyBM[44]).Range.Text = a8.Text;
            doc.Bookmarks.get_Item(ref MyBM[45]).Range.Text = a9.Text;
            doc.Bookmarks.get_Item(ref MyBM[46]).Range.Text = a10_1.Text;
            doc.Bookmarks.get_Item(ref MyBM[55]).Range.Text = a10_2.Text;
            doc.Bookmarks.get_Item(ref MyBM[56]).Range.Text = a10_3.Text;

            /* doc.Bookmarks.get_Item(ref MyBM[47]).Range.Text = a11.Text;
             * doc.Bookmarks.get_Item(ref MyBM[48]).Range.Text = a12.Text;
             * doc.Bookmarks.get_Item(ref MyBM[49]).Range.Text = a13.Text;
             * doc.Bookmarks.get_Item(ref MyBM[50]).Range.Text = a14.Text;
             * doc.Bookmarks.get_Item(ref MyBM[51]).Range.Text = a15.Text;
             * doc.Bookmarks.get_Item(ref MyBM[52]).Range.Text = a16.Text;
             * doc.Bookmarks.get_Item(ref MyBM[53]).Range.Text = a17.Text;
             * doc.Bookmarks.get_Item(ref MyBM[54]).Range.Text = a18.Text;*/

            doc.SaveAs(ref aa);
            doc.Close();
            this.Enabled = true;
        }
Beispiel #36
0
 private void openFile(string newFilename)
 {
     oWord         = new Microsoft.Office.Interop.Word.Application();
     oWord.Visible = false;
     oDoc          = oWord.Documents.Open(newFilename, ReadOnly: false, Visible: true);
 }
        public static void exportWord(Dictionary <string, string> dataPrint, string fileName)
        {
            Microsoft.Office.Interop.Word.Application objWord = null;
            Microsoft.Office.Interop.Word.Document    objDoc  = null;
            object oBookMark = null;

            try
            {
                _wait = new WaitDialogForm("Đang xuất dữ liệu...", "Xin vui lòng chờ giây lát");
                object oMissing = System.Reflection.Missing.Value;
                object oFalse   = false;

                //init
                object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
                object oTemplate = Application.StartupPath + "\\Template\\" + fileName;

                Object beforeRow = Type.Missing;
                objWord         = new Microsoft.Office.Interop.Word.Application();
                objDoc          = objWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
                objWord.Visible = false;


                foreach (KeyValuePair <string, string> pair in dataPrint)
                {
                    objDoc.Bookmarks[pair.Key].Range.Text = pair.Value;
                }

                if (false)
                {
                    objWord.DisplayAlerts           = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
                    objWord.Options.PrintBackground = false;
                    PrintDialog printer = new PrintDialog();
                    if (!printer.PrinterSettings.IsValid)
                    {
                        if (printer.ShowDialog() == DialogResult.OK)
                        {
                            objWord.ActivePrinter = printer.PrinterSettings.PrinterName;
                            objWord.PrintOut();
                        }
                    }
                    else
                    {
                        objWord.PrintOut();
                    }
                    objWord.Quit(SaveChanges: false);
                }
                else
                {
                    objWord.Visible = true;
                }

                //objWord.Visible = true;
            }
            catch (Exception ex)
            {
                string exMsg = "Xuất Word không thành công!\n";
                XtraMessageBox.Show(exMsg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                clsMessage.MessageExclamation(exMsg + ex.Message);
            }
            finally
            {
                if (!_wait.IsDisposed)
                {
                    _wait.Close();
                }
                releaseObject(objDoc);
                releaseObject(objWord);
            }
        }
Beispiel #38
0
        public void BtnExportWord_CLick(object sender, EventArgs e)
        {
            mf.wsm.Visible = true;
            mf.wsm.Update();

            Microsoft.Office.Interop.Word._Application wordApp = null;
            try
            {
                wordApp = new Microsoft.Office.Interop.Word.Application();
            }
            catch
            {
                mf.wsm.Visible = false;
                MessageBox.Show("На ПК не установлен пакет Microsoft Office Word 2007 или позднее. Экспорт невозможен.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Microsoft.Office.Interop.Word.Document  wordDoc;
            Microsoft.Office.Interop.Word.Paragraph wordParag;


            wordDoc = wordApp.Documents.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            wordParag                            = wordDoc.Paragraphs.Add();
            wordParag.Range.Text                 = "Требования к параметрам настройки средств защиты информации в ИС \"" + IS.ISName + "\"";
            wordParag.Range.Font.Name            = "Times New Roman";
            wordParag.Range.Font.Size            = 18;
            wordParag.Range.Font.Bold            = 1;
            wordParag.Range.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordParag.Range.InsertParagraphAfter(); wordParag.Range.InsertParagraphAfter();
            using (KPSZIContext db = new KPSZIContext())
            {
                foreach (MeasureGroup mg in db.MeasureGroups.ToList())
                {
                    //Группа мер
                    bool isMeasureGroupInTable = false;
                    for (int i = mf.dgvConfigNMeasures.Rows.Count - 1; i >= 0; i--)
                    {
                        if (mf.dgvConfigNMeasures.Rows[i].Cells[0].Value.ToString().Contains(mg.ShortName + "."))
                        {
                            isMeasureGroupInTable = true;
                        }
                    }
                    if (!isMeasureGroupInTable)
                    {
                        continue;
                    }
                    wordParag.Range.Text                 = '\t' + mg.Name;
                    wordParag.Range.Font.Name            = "Times New Roman";
                    wordParag.Range.Font.Size            = 16;
                    wordParag.Range.Font.Bold            = 1;
                    wordParag.Range.Font.Italic          = 0;
                    wordParag.Range.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;

                    wordParag.Range.InsertParagraphAfter();

                    foreach (DataGridViewRow dgvr in mf.dgvConfigNMeasures.Rows)
                    {
                        if (dgvr.Cells[0].Value.ToString().Contains(mg.ShortName + "."))
                        {
                            //Мера
                            wordParag.Range.Text                 = '\t' + dgvr.Cells[0].Value.ToString();
                            wordParag.Range.Font.Name            = "Times New Roman";
                            wordParag.Range.Font.Size            = 14;
                            wordParag.Range.Font.Bold            = 1;
                            wordParag.Range.Font.Italic          = 0;
                            wordParag.Range.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;

                            wordParag.Range.InsertParagraphAfter();

                            //тип сзи
                            string         szis     = "";
                            string         measure  = dgvr.Cells[0].Value.ToString();
                            List <SZISort> szisorts = db.GisMeasures.ToList().Where(m => (m.MeasureGroup.ShortName + "." + m.Number + " " + m.Description) == measure).First().SZISorts.ToList();

                            var listOfSZIs = db.SZIs.ToList().Intersect(IS.listOfSZIs).ToList();
                            foreach (SZI sz in listOfSZIs)
                            {
                                SZI m = db.SZIs.Where(t => t.SZIId == sz.SZIId).First();
                                sz.SZISorts = m.SZISorts.ToList();
                            }
                            foreach (SZISort s in szisorts)
                            {
                                szis += s.Name + ": " + listOfSZIs.Where(szi => szi.SZISorts.Contains(s)).First().Name + "; ";
                            }
                            if (szis != "")
                            {
                                szis = szis.Substring(0, szis.Length - 2) + ".";

                                wordParag.Range.Text                 = '\t' + szis;
                                wordParag.Range.Font.Name            = "Times New Roman";
                                wordParag.Range.Font.Size            = 14;
                                wordParag.Range.Font.Bold            = 0;
                                wordParag.Range.Font.Italic          = 1;
                                wordParag.Range.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;

                                wordParag.Range.InsertParagraphAfter();
                            }


                            string[] configOptions = dgvr.Cells[1].Value.ToString().Split('\n');
                            for (int i = 0; i < configOptions.Length - 1; i++)
                            {
                                //Параметры
                                char divider = i == configOptions.Length - 2 ? '.' : ';';
                                wordParag.Range.Text                 = "\t– " + configOptions[i] + divider;
                                wordParag.Range.Font.Name            = "Times New Roman";
                                wordParag.Range.Font.Size            = 12;
                                wordParag.Range.Font.Bold            = 0;
                                wordParag.Range.Font.Italic          = 0;
                                wordParag.Range.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
                                wordParag.Range.InsertParagraphAfter();
                            }
                            wordParag.Range.InsertParagraphAfter();
                        }
                        else
                        {
                            continue;
                        }
                    }
                    wordParag.Range.InsertParagraphAfter();
                }
                wordApp.Visible = true;

                mf.wsm.Visible = false;
            }
        }
Beispiel #39
0
        private void button1_Click(object sender, EventArgs e)
        {
            string filename = Application.StartupPath + "\\bin\\" + Global.templateName + ".doc";

            Spire.Doc.Document document = new Spire.Doc.Document(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox   = document.TextBoxes[8];
            Spire.Doc.Documents.Paragraph paragraph = textBox.Body.AddParagraph();
            TextRange textRange = paragraph.AppendText(textBox1.Text);

            document.SaveToFile(filename, FileFormat.Docx);

            object filename1     = Environment.CurrentDirectory.ToString() + "\\bin\\" + Global.templateName + ".doc";
            string ImagePath     = pictureBox1.ImageLocation;
            string strKey        = "7.2.2温度曲线图";
            object MissingValue  = Type.Missing;
            bool   isFindSealLoc = false;

            Microsoft.Office.Interop.Word.Application wp = null;
            Microsoft.Office.Interop.Word.Document    wd = null;
            try
            {
                wp = new Microsoft.Office.Interop.Word.Application();
                wd = wp.Documents.Open(ref filename1, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue);
                wp.Selection.Find.ClearFormatting();
                wp.Selection.Find.Replacement.ClearFormatting();
                wp.Selection.Find.Text = strKey;
                object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                              ref MissingValue, ref MissingValue, ref MissingValue,
                                              ref MissingValue, ref MissingValue, ref MissingValue,
                                              ref MissingValue, ref objReplace, ref MissingValue,
                                              ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor           = wp.Selection.Range;
                    object LinkToFile       = false;
                    object SaveWithDocument = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape = wp.Selection.InlineShapes.AddPicture(
                        ImagePath, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                    Inlineshape.Select();
                    Microsoft.Office.Interop.Word.Shape shape = Inlineshape.ConvertToShape();
                    shape.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd != null)
                {
                    wd.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd);
                    wd = null;
                }
                if (wp != null)
                {
                    wp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp);
                    wp = null;
                }
                MessageBox.Show("导入成功!");
            }
            this.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            #region  除后台占用
            System.Diagnostics.Process myproc = new System.Diagnostics.Process();
            //得到所有打开的进程
            try
            {
                foreach (Process thisproc in Process.GetProcessesByName("WINWORD"))
                {
                    if (!thisproc.CloseMainWindow())
                    {
                        thisproc.Kill();
                    }
                }
            }
            catch (Exception ea)
            {
                MessageBox.Show("杀死" + "WINWORD" + "失败!");
            }
            #endregion

            try
            {
                #region 从Resource文件夹提取模板
                FileInfo f111 = new FileInfo(System.Windows.Forms.Application.StartupPath + "\\bin\\" + Global.templateName + ".doc");
                if (f111.Exists)
                {
                    f111.Delete();
                    FileInfo f222 = new FileInfo(System.Windows.Forms.Application.StartupPath + "\\bin\\" + "\\Resource\\" + Global.templateName + ".doc");
                    f222.CopyTo(System.Windows.Forms.Application.StartupPath + "\\bin\\" + Global.templateName + ".doc");
                }
                else
                {
                    FileInfo f222 = new FileInfo(System.Windows.Forms.Application.StartupPath + "\\bin\\" + "\\Resource\\" + Global.templateName + ".doc");
                    f222.CopyTo(System.Windows.Forms.Application.StartupPath + "\\bin\\" + Global.templateName + ".doc");
                }
                #endregion
            }
            catch (Exception)
            {
                MessageBox.Show("调取模板错误。");
            }

            try
            {
                object filename = Application.StartupPath + "\\bin\\" + Global.templateName;

                object G_Missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    wordDoc;
                wordDoc = wordApp.Documents.Open(filename);
                wordDoc.ActiveWindow.Visible = false;//打开word

                Microsoft.Office.Interop.Word.Range myRange = wordDoc.Range();

                Microsoft.Office.Interop.Word.Find f = myRange.Find;
                f.Text = "委托单位:";
                f.ClearFormatting();

                bool finded = f.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                        );

                myRange      = wordDoc.Range(myRange.End, myRange.End + 28);
                myRange.Text = textBox1.Text;

                Microsoft.Office.Interop.Word.Range myRange1 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f1       = myRange1.Find;
                f1.Text = "验证对象:";
                f1.ClearFormatting();

                bool finded1 = f1.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                          );

                myRange1      = wordDoc.Range(myRange1.End, myRange1.End + 28);
                myRange1.Text = textBox2.Text;

                Microsoft.Office.Interop.Word.Range myRange2 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f2       = myRange2.Find;
                f2.Text = "验证地点:";
                f2.ClearFormatting();

                bool finded2 = f2.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                          );

                myRange2      = wordDoc.Range(myRange2.End, myRange2.End + 24);
                myRange2.Text = textBox3.Text;

                Microsoft.Office.Interop.Word.Range myRange3 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f3       = myRange3.Find;
                f3.Text = "验证时间:";
                f3.ClearFormatting();

                bool finded3 = f3.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                          );

                myRange3      = wordDoc.Range(myRange3.End, myRange3.End + 4);
                myRange3.Text = textBox4.Text;

                Microsoft.Office.Interop.Word.Range myRange4 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f4       = myRange4.Find;
                f4.Text = "年";
                f4.ClearFormatting();

                bool finded4 = f4.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                          );

                myRange4      = wordDoc.Range(myRange4.End, myRange4.End + 2);
                myRange4.Text = textBox5.Text;

                Microsoft.Office.Interop.Word.Range myRange5 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f5       = myRange5.Find;
                f5.Text = "月";
                f5.ClearFormatting();

                bool finded5 = f5.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                          );

                myRange5      = wordDoc.Range(myRange5.End, myRange5.End + 2);
                myRange5.Text = textBox6.Text;

                Microsoft.Office.Interop.Word.Range myRange6 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f6       = myRange6.Find;
                f6.Text = "至 ";
                f6.ClearFormatting();

                bool finded6 = f6.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                          );

                myRange6      = wordDoc.Range(myRange6.End, myRange6.End + 4);
                myRange6.Text = textBox7.Text;

                Microsoft.Office.Interop.Word.Range myRange7 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f7       = myRange7.Find;
                f7.Text = "年 ";
                f7.ClearFormatting();

                bool finded7 = f7.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                          );

                myRange7      = wordDoc.Range(myRange7.End, myRange7.End + 1);
                myRange7.Text = textBox8.Text;

                Microsoft.Office.Interop.Word.Range myRange8 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f8       = myRange8.Find;
                f8.Text = "月 ";
                f8.ClearFormatting();

                bool finded8 = f8.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                          );

                myRange8      = wordDoc.Range(myRange8.End, myRange8.End + 1);
                myRange8.Text = textBox9.Text;

                Microsoft.Office.Interop.Word.Range myRange9 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f9       = myRange9.Find;
                f9.Text = "编写人员:";
                f9.ClearFormatting();

                bool finded9 = f9.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                          ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                          );

                myRange9      = wordDoc.Range(myRange9.End, myRange9.End + 16);
                myRange9.Text = textBox10.Text;

                Microsoft.Office.Interop.Word.Range myRange10 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f10       = myRange10.Find;
                f10.Text = "审核人员:";
                f10.ClearFormatting();

                bool finded10 = f10.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                            );

                myRange10      = wordDoc.Range(myRange10.End, myRange10.End + 14);
                myRange10.Text = textBox11.Text;

                Microsoft.Office.Interop.Word.Range myRange11 = wordDoc.Range();
                Microsoft.Office.Interop.Word.Find  f11       = myRange11.Find;
                f11.Text = "批准人员:";
                f11.ClearFormatting();

                bool finded11 = f11.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                            );

                myRange11      = wordDoc.Range(myRange11.End, myRange11.End + 14);
                myRange11.Text = textBox12.Text;

                wordDoc.Save();
                wordApp.Quit();
                wordApp = null;

                MessageBox.Show("成功调取模板并导入基本信息。");

                this.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("请检查模板。");
            }
        }
Beispiel #41
0
        //将word转换为html
        private void WordToHtmlFile(string WordFilePath, string strExtention, TextBox textBox, ComboBox comboBox)
        {
            try
            {
                Microsoft.Office.Interop.Word.Application wApp = new Microsoft.Office.Interop.Word.Application();
                //指定原文件和目标文件
                object   docPath = WordFilePath;
                string   htmlPath;
                FileInfo finfo = new FileInfo(WordFilePath);
                htmlPath = textBox.Text.TrimEnd(new char[] { '\\' }) + "\\" + finfo.Name.Substring(0, finfo.Name.LastIndexOf(".")) + strExtention;
                object Target = htmlPath;
                //缺省参数
                object Unknown = Type.Missing;
                //只读方式打开
                object readOnly = true;
                //打开doc文件
                Microsoft.Office.Interop.Word.Document document = wApp.Documents.Open(ref docPath, ref Unknown,
                                                                                      ref readOnly, ref Unknown, ref Unknown,
                                                                                      ref Unknown, ref Unknown, ref Unknown,
                                                                                      ref Unknown, ref Unknown, ref Unknown,
                                                                                      ref Unknown);
                // 指定格式
                object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML;
                switch (strExtention)
                {
                case ".htm":
                default:
                    format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML;
                    break;

                case ".pdf":
                    format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
                    break;

                case ".rtf":
                    format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;
                    break;
                }
                object encoding = comboBox.Text;
                switch (comboBox.Text)
                {
                case "GB2312":
                default:
                    document.WebOptions.Encoding = MsoEncoding.msoEncodingSimplifiedChineseGBK;
                    break;

                case "UTF8":
                    document.WebOptions.Encoding = MsoEncoding.msoEncodingUTF8;
                    break;
                }
                //转换格式
                document.SaveAs(ref Target, ref format,
                                ref Unknown, ref Unknown, ref Unknown,
                                ref Unknown, ref Unknown, ref Unknown,
                                ref Unknown, ref Unknown, ref Unknown);
                //document.SaveAs2(ref Target, ref format,
                //ref Unknown, ref Unknown, ref Unknown,
                //ref Unknown, ref Unknown, ref Unknown,
                //ref Unknown, ref Unknown, ref Unknown,
                //ref encoding, ref Unknown, ref Unknown,
                //ref Unknown, ref Unknown, ref Unknown);
                // 关闭文档和Word程序
                document.Close(ref Unknown, ref Unknown, ref Unknown);
                wApp.Quit(ref Unknown, ref Unknown, ref Unknown);
            }
            catch { //MessageBox.Show(e.Message);
            }
        }
Beispiel #42
0
        public void ExelAkt()
        {
            //Создаём новый Word.Application
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

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

            object fileName   = @"C:\Agenty\templates\akt.docx";
            object falseValue = false;
            object trueValue  = true;
            object missing    = Type.Missing;

            doc = app.Documents.Open(ref fileName, ref missing, ref trueValue,
                                     ref missing, ref missing, ref missing, ref missing, ref missing,
                                     ref missing, ref missing, ref missing, ref missing, ref missing,
                                     ref missing, ref missing, ref missing);

            //Указываем таблицу в которую будем помещать данные (таблица должна существовать в шаблоне документа!)
            Microsoft.Office.Interop.Word.Table tbl = app.ActiveDocument.Tables[1];
            tbl.Rows[2].Cells[1].Range.Text = (j).ToString();
            tbl.Rows[2].Cells[2].Range.Text = (sum).ToString();

            Yrread();

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

            //Задаём параметры замены и выполняем замену.

            object findText0    = "[акт]";
            object replaceWith0 = aktnYR;
            object replace0     = 2;

            app.Selection.Find.Execute(ref findText0, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith0,
                                       ref replace0, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.

            object findText    = "[договор]";
            object replaceWith = (yr[AG]).Dogovor;
            object replace     = 2;

            app.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
                                       ref replace, ref missing, ref missing, ref missing, ref missing);

            object findText1    = "[дата]";
            object replaceWith1 = dateYR;
            object replace1     = 2;

            app.Selection.Find.Execute(ref findText1, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith1,
                                       ref replace1, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.

            object findText2    = "[организация1]";
            object replaceWith2 = nashOrg;
            object replace2     = 2;

            app.Selection.Find.Execute(ref findText2, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith2,
                                       ref replace2, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.

            object findText3    = "[лицо1]";
            object replaceWith3 = nashvlic;
            object replace3     = 2;

            app.Selection.Find.Execute(ref findText3, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith3,
                                       ref replace3, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.

            object findText4    = "[основание1]";
            object replaceWith4 = nashOsn;
            object replace4     = 2;

            app.Selection.Find.Execute(ref findText4, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith4,
                                       ref replace4, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText5    = "[организация2]";
            object replaceWith5 = AG;
            object replace5     = 2;

            app.Selection.Find.Execute(ref findText5, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith5,
                                       ref replace5, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText6    = "[лицо2]";
            object replaceWith6 = (yr[AG]).Vlice;
            object replace6     = 2;

            app.Selection.Find.Execute(ref findText6, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith6,
                                       ref replace6, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText7    = "[основание2]";
            object replaceWith7 = (yr[AG]).Osnovanie;
            object replace7     = 2;

            app.Selection.Find.Execute(ref findText7, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith7,
                                       ref replace7, ref missing, ref missing, ref missing, ref missing);


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

            //Задаём параметры замены и выполняем замену.


            object findText8    = "[основание2]";
            object replaceWith8 = (yr[AG]).Osnovanie;
            object replace8     = 2;

            app.Selection.Find.Execute(ref findText8, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith8,
                                       ref replace8, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText9    = "[сумма]";
            object replaceWith9 = Math.Floor((sum / 100) * oplataYR);
            object replace9     = 2;

            app.Selection.Find.Execute(ref findText9, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith9,
                                       ref replace9, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText10    = "[сумма2]";
            object replaceWith10 = RusNumber.Str(Convert.ToInt32(Math.Floor((sum / 100) * oplataYR)));
            object replace10     = 2;

            app.Selection.Find.Execute(ref findText10, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith10,
                                       ref replace10, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText11    = "[сумма3]";
            object replaceWith11 = RusNumber.Kop(Math.Round(((sum / 100) * oplataYR), 2));
            object replace11     = 2;

            app.Selection.Find.Execute(ref findText11, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith11,
                                       ref replace11, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText12    = "[организация1]";
            object replaceWith12 = nashOrg;
            object replace12     = 2;

            app.Selection.Find.Execute(ref findText12, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith12,
                                       ref replace12, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText14    = "[организация2]";
            object replaceWith14 = AG;
            object replace14     = 2;

            app.Selection.Find.Execute(ref findText14, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith14,
                                       ref replace14, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText15    = "[фамилия1]";
            object replaceWith15 = nashPodp;
            object replace15     = 2;

            app.Selection.Find.Execute(ref findText15, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith15,
                                       ref replace15, ref missing, ref missing, ref missing, ref missing);

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

            //Задаём параметры замены и выполняем замену.


            object findText16    = "[фамилия2]";
            object replaceWith16 = (yr[AG]).Podpisant;
            object replace16     = 2;

            app.Selection.Find.Execute(ref findText16, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith16,
                                       ref replace16, ref missing, ref missing, ref missing, ref missing);

            //Открываем документ для просмотра.
            app.Visible = true;
            GC.Collect(); // убрать за  собой
        }
Beispiel #43
0
        public void ExelOtchet()
        {
            //Создаём новый Word.Application
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

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

            object fileName   = @"C:\Agenty\templates\otchet.docx";
            object falseValue = false;
            object trueValue  = true;
            object missing    = Type.Missing;

            doc = app.Documents.Open(ref fileName, ref missing, ref trueValue,
                                     ref missing, ref missing, ref missing, ref missing, ref missing,
                                     ref missing, ref missing, ref missing, ref missing, ref missing,
                                     ref missing, ref missing, ref missing);

            //Указываем таблицу в которую будем помещать данные (таблица должна существовать в шаблоне документа!)
            Microsoft.Office.Interop.Word.Table tbl = app.ActiveDocument.Tables[1];

            //Заполняем в таблицу - 10 записей.
            int i;

            for (i = 1; i <= exp.Count(); i++)
            {
                tbl.Rows.Add(ref missing); //Добавляем в таблицу строку.
                                           //Обычно саздаю только строку с заголовками и одну пустую для данных.
                tbl.Rows[i + 1].Cells[1].Range.Text = ((exp[i - 1]).a).ToString();
                tbl.Rows[i + 1].Cells[2].Range.Text = ((exp[i - 1]).c).ToString();
                tbl.Rows[i + 1].Cells[3].Range.Text = ((exp[i - 1]).d).ToString();
            }

            tbl.Rows.Add(ref missing); //Добавляем в таблицу строку.
                                       //Обычно саздаю только строку с заголовками и одну пустую для данных.
            tbl.Rows[i + 1].Cells[1].Range.Text = "Итого";
            tbl.Rows[i + 1].Cells[2].Range.Text = (i - 1).ToString();
            tbl.Rows[i + 1].Cells[3].Range.Text = (sum).ToString();


            Yrread();

            //Очищаем параметры поиска
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            //Задаём параметры замены и выполняем замену.
            object findText    = "[акт]";
            object replaceWith = aktnYR;
            object replace     = 2;

            app.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
                                       ref replace, ref missing, ref missing, ref missing, ref missing);


            //Очищаем параметры поиска
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            //Задаём параметры замены и выполняем замену.
            object findText1    = "[дата_акта]";
            object replaceWith1 = dateYR;
            object replace1     = 2;

            app.Selection.Find.Execute(ref findText1, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith1,
                                       ref replace1, ref missing, ref missing, ref missing, ref missing);

            //Очищаем параметры поиска
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            //Задаём параметры замены и выполняем замену.
            object findText2    = "[data]";
            object replaceWith2 = dateYR;
            object replace2     = 2;

            app.Selection.Find.Execute(ref findText2, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith2,
                                       ref replace2, ref missing, ref missing, ref missing, ref missing);

            //Очищаем параметры поиска
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            //Задаём параметры замены и выполняем замену.
            object findText3    = "[договор]";
            object replaceWith3 = (yr[AG]).Dogovor;
            object replace3     = 2;

            app.Selection.Find.Execute(ref findText3, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith3,
                                       ref replace3, ref missing, ref missing, ref missing, ref missing);


            //Очищаем параметры поиска
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            //Задаём параметры замены и выполняем замену.
            object findText4    = "[организация1]";
            object replaceWith4 = nashOrg;
            object replace4     = 2;

            app.Selection.Find.Execute(ref findText4, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith4,
                                       ref replace4, ref missing, ref missing, ref missing, ref missing);


            //Очищаем параметры поиска
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            //Задаём параметры замены и выполняем замену.
            object findText5    = "[организация2]";
            object replaceWith5 = AG;
            object replace5     = 2;

            app.Selection.Find.Execute(ref findText5, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith5,
                                       ref replace5, ref missing, ref missing, ref missing, ref missing);

            //Очищаем параметры поиска
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            //Задаём параметры замены и выполняем замену.
            object findText6    = "[фамилия1]";
            object replaceWith6 = nashPodp;
            object replace6     = 2;

            app.Selection.Find.Execute(ref findText6, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith6,
                                       ref replace6, ref missing, ref missing, ref missing, ref missing);

            //Очищаем параметры поиска
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            //Задаём параметры замены и выполняем замену.
            object findText7    = "[фамилия2]";
            object replaceWith7 = (yr[AG]).Podpisant;
            object replace7     = 2;

            app.Selection.Find.Execute(ref findText7, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith7,
                                       ref replace7, ref missing, ref missing, ref missing, ref missing);



            //Открываем документ для просмотра.
            app.Visible = true;
            GC.Collect(); // убрать за  собой
        }
Beispiel #44
0
        public string ReadMsWord()
        {
            // variable to store file path

            string filePath = null;
            string PathName = null;

            // execute if block when dialog result box click ok button

            DataTable GeneralInfo = BusinessLogicBridge.DataStore.getGeneralConfig();

            PathName = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            PathName = PathName + @"\" + GeneralInfo.Rows[0]["path_all_document"].ToString();

            filePath = DXWindowsApplication2.MainForm.CombinePaths(PathName, "Contract", "RentContract.doc");

            // create word application

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


            // create object of missing value

            object miss = System.Reflection.Missing.Value;

            // create object of selected file path

            object path = filePath;

            // set file path mode

            object readOnly = false;

            // open document

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);


            // select whole data from active window document

            docs.ActiveWindow.Selection.WholeStory();

            // handover the data to cllipboard

            docs.ActiveWindow.Selection.Copy();

            // clipboard create reference of idataobject interface which transfer the data

            System.Windows.Forms.IDataObject data = System.Windows.Forms.Clipboard.GetDataObject();

            //set data into richtextbox control in text format

            //richTextBox2.Text = data.GetData(DataFormats.Text).ToString();

            // read bitmap image from clipboard with help of iddataobject interface

            //Image img = (Image)data.GetData(DataFormats.Bitmap);

            // close the document

            docs.Close(ref miss, ref miss, ref miss);


            return(data.GetData(System.Windows.Forms.DataFormats.Text).ToString());
        }
        public static ChalLine CreateChalLine(IQuest quest, int row, Grid userControlGrid, Microsoft.Office.Interop.Word.Application wordApp = null)
        {
            var line = new ChalLine();

            line.Quest = quest;

            line.Chal.Grid_chal = MyGrids.GetChallenge(row, userControlGrid);

            MyStacks.Get(line.Chal.Row_1, 0, 0, line.Chal.Grid_chal);
            line.Chal.Row_1.Visibility = Visibility.Collapsed;

            MyLbls.Chal_answer(line.Chal.Answer, line.Chal.Row_1, quest.Text);

            if (quest is VocModel voc)
            {
                MyLbls.Get(line.Chal.PtBr, line.Chal.Row_1, voc.PtBr);
                line.Chal.PtBr.Foreground = Brushes.DarkBlue;
                MyLbls.Get(line.Chal.Definition, line.Chal.Row_1, voc.Definition);
            }

            var stk_2 = BuildSenChal(line, wordApp);

            UtilWPF.SetGridPosition(stk_2, 1, 0, line.Chal.Grid_chal);

            MyGrids.GetRow(line.Chal.Row_3, 2, 0, line.Chal.Grid_chal, new List <int>()
            {
                1, 1, 1, 1, 1, 1
            });
            line.Chal.Row_3.Visibility = Visibility.Collapsed;
            MyLbls.AvgScore(line.Chal.Avg_w, 0, 0, line.Chal.Row_3, line.Quest, 7, false);
            MyLbls.AvgScore(line.Chal.Avg_m, 0, 1, line.Chal.Row_3, line.Quest, 30, false);
            MyLbls.AvgScore(line.Chal.Avg_all, 0, 2, line.Chal.Row_3, line.Quest, 2000, false);
            MyLbls.Tries(line.Chal.Tries, 0, 3, line.Chal.Row_3, line.Quest);
            MyLbls.Get(line.Chal.Importante, 0, 4, line.Chal.Row_3, line.Quest.Importance.ToDesc());
            MyLbls.Chance(line.Chal.Chance, 0, 5, line.Chal.Row_3, line.Quest);
            line.Chal.Chance.Content.ToString().Insert(0, "was ");

            MyGrids.GetRow(line.Chal.Row_4, 3, 0, line.Chal.Grid_chal, new List <int>()
            {
                2, 1, 2, 1, 2
            });
            line.Chal.Row_4.Visibility = Visibility.Collapsed;

            MyBtns.Chal_remove_att(line);
            MyLbls.Chal_quest_id(line, 2);
            MyBtns.Chal_disable_quest(line);

            return(line);
        }
 public Application()
 {
     application = new Microsoft.Office.Interop.Word.Application();
 }
        public void CreateRegistrationCard(string registrationNumber, string dateRegistration, string surname, string name, string patronymic, string birthday, string passportSeries,
                                           string passportNumber, string whoGivePassport, string whenGivePassport, string town, string street, string building,
                                           string apartment, string mobilePhone, string homePhone, string email, bool pdf)
        {
            try
            {
                if (RegistryData.DirPath == "")
                {
                    RegistryData.DirPath = "C:\\Users\\" + SystemInformation.UserName + "\\Documents\\Отчёты";
                    if (!Directory.Exists(RegistryData.DirPath))
                    {
                        Directory.CreateDirectory(RegistryData.DirPath);
                    }
                }


                fileName = RegistryData.DirPath + "\\Регистрационная карточка " + surname + " " + name + " " + patronymic + " от " + DateTime.Now.ToString("HH.mm.ss_dd.MM.yyyy") + ".docx";

                using (DocX document = DocX.Create(fileName))   //формирование документа в формате docx
                {
                    document.MarginTop    = 56.6f;
                    document.MarginLeft   = 56.6f;
                    document.MarginRight  = 28.3f;
                    document.MarginBottom = 56.6f;

                    var title            = document.InsertParagraph();
                    var data             = document.InsertParagraph();
                    var text             = document.InsertParagraph();
                    var placeOfSignature = document.InsertParagraph();
                    var instruction      = document.InsertParagraph();

                    title.Append("Регистрационная карточка читателя \n библиотеки №127").Font(new Font("Times New Roman")).FontSize(16).Bold().SetLineSpacing(LineSpacingType.Line, 1.5f);
                    title.Alignment = Alignment.center;

                    data.Append("Регистрационный номер: " + registrationNumber + "\nДата заполнения: " + dateRegistration + "\nФамилия: " + surname + "\nИмя: " + name + "\nОтчество: " + patronymic + "\nДата рождения: " + birthday + "\nСерия и номер паспорта: " + passportSeries + " " + passportNumber + "\nКем выдан: " + whoGivePassport + "\nКогда выдан: " + whenGivePassport + "\nАдрес проживания: " + town + ", " + street + ", дом " + building + ", квартира " + apartment + "\nДомашний телефон: " + homePhone + "\nМобильный телефон: " + mobilePhone + "\nАдрес электронной почты: " + email + "\n")
                    .Font(new Font("Times New Roman")).FontSize(14).SetLineSpacing(LineSpacingType.Line, 1.5f);
                    data.Alignment = Alignment.left;

                    text.Append("\tПодтверждаю, что я ознакомлен и полностью согласен с условиями оказания мне библиотечных услуг библиотекой №127 изложенными в «Правилах пользования библиотекой №127», я согласен с тем, что библиотека может отказать мне в обслуживании в случае их нарушения. Также даю свое согласие на обработку моих персональных данных, указанных в настоящей регистрационной карточке.\n\tДанное согласие действует до моего прямого отказа от пользования услугами библиотеки, выраженного мною лично в устной или письменной форме.")
                    .Font(new Font("Times New Roman")).FontSize(14).SetLineSpacing(LineSpacingType.Line, 1.5f);
                    text.Alignment = Alignment.both;

                    placeOfSignature.Append("____________ / ____________").Font(new Font("Times New Roman")).FontSize(14).SetLineSpacing(LineSpacingType.Line, 1f);
                    placeOfSignature.Alignment = Alignment.right;

                    instruction.Append("\t\t\t\t\t\t\t\t\t\tПодпись                 Расшифровка").Font(new Font("Times New Roman")).FontSize(10).Bold();

                    document.Save();

                    if (pdf == true)    //формирование документа pdf
                    {
                        Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
                        var wordDocument = appWord.Documents.Open(fileName);
                        oldFileName = fileName;
                        fileName    = fileName.Remove(fileName.Length - 4);
                        wordDocument.ExportAsFixedFormat(fileName + "pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
                        wordDocument.Close();
                        appWord.Quit();
                        FileInfo fileWord = new FileInfo(oldFileName);
                        fileWord.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                RegistryData.ErrorMessage += "\n" + DateTime.Now.ToLongDateString() + " " + ex.Message;
            }
        }
        private static void ConvertTopdf2(string name, string pre, string filepath, string fname)
        {
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

            wordApp.Visible = false;

            // file from

            object filename = filepath + name + "." + pre;                               // input
            // file to
            object newFileName = filepath + "pdfFiles\\" + fname + "\\" + name + ".pdf"; // output

            if (!Directory.Exists(filepath + "pdfFiles\\" + fname))
            {
                Directory.CreateDirectory(filepath + "pdfFiles\\" + fname);
            }
            object missing = System.Type.Missing;

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

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

            // changes in paper size

            doc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4;

            // changes orietation paper
            doc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;

            // other changes
            doc.PageSetup.LeftMargin  = 10;
            doc.PageSetup.RightMargin = 10;


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

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

            wordApp.Quit(ref missing, ref missing, ref missing);
            using (ZipFile zip = ZipFile.Read(filepath + "pdfFiles\\" + fname + "\\" + fname + ".zip"))
            {
                ZipEntry z = zip[name + "." + pre];
                if (z == null)
                {
                    FileStream stream = new FileStream(filepath + "pdfFiles\\" + fname + "\\" + name + ".pdf", FileMode.Open, FileAccess.ReadWrite);
                    zip.AddEntry(name + ".pdf", stream);
                    zip.Save();
                    System.IO.File.Delete(filepath + "pdfFiles\\" + fname + "\\" + name + ".pdf");
                }
                else
                {
                    System.IO.File.Delete(filepath + "pdfFiles\\" + fname + "\\" + name + ".pdf");
                }
            }
        }
Beispiel #49
0
        public static void attestation(string raison, string spécialité, string image, string wilaya, string Rc, string matricule_fiscal, string date, string gérant, string employé, string date_naissance, string date_embauche, string poste, string chemin, string chemin1)
        {
            Microsoft.Office.Interop.Word.Application _ApplicationWord = new Microsoft.Office.Interop.Word.Application();
            _ApplicationWord.Visible = false;
            string path      = chemin1 + "\\Modeles\\REF-ATTESTATION DE TRAVAIL.docx";
            object oFileName = (object)@path;
            object Faux      = (object)false;
            object Vrai      = (object)true;
            object M         = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word._Document _MonDocument = _ApplicationWord.Documents.Add(ref oFileName, ref Faux, ref M, ref Vrai);

            object Nom   = (object)"date";
            object Nom1  = (object)"date1";
            object Nom2  = (object)"dateEmbauche";
            object Nom3  = (object)"dateNaissance";
            object Nom4  = (object)"employé";
            object Nom5  = (object)"gérant";
            object Nom6  = (object)"gérant1";
            object Nom7  = (object)"RcMatriculeFiscal";
            object Nom8  = (object)"poste";
            object Nom9  = (object)"raison";
            object Nom10 = (object)"raison1";
            object Nom11 = (object)"raison2";
            object Nom13 = (object)"spécialité";
            object Nom14 = (object)"wilaya";
            object Nom15 = (object)"wilaya1";
            object Nom16 = (object)"logo";



            Microsoft.Office.Interop.Word.Bookmark    _MonSignet;
            Microsoft.Office.Interop.Word.Range       _MonRange;
            Microsoft.Office.Interop.Word.InlineShape _MonImage;

            //récupére la liste de signets
            Microsoft.Office.Interop.Word.Bookmarks _MesSignets = _MonDocument.Bookmarks;

            //si le signet cherché existe
            if (_MesSignets.Exists("date"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(date);
            }
            if (_MesSignets.Exists("date1"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom1);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(date);
            }
            if (_MesSignets.Exists("dateEmbauche"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom2);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(date_embauche);
            }
            if (_MesSignets.Exists("dateNaissance"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom3);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(date_naissance);
            }
            if (_MesSignets.Exists("employé"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom4);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(employé);
            }
            if (_MesSignets.Exists("gérant"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom5);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(gérant);
            }
            if (_MesSignets.Exists("gérant1"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom6);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(gérant);
            }
            if (_MesSignets.Exists("RcMatriculeFiscal"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom7);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(Rc + "/" + matricule_fiscal);
            }
            if (_MesSignets.Exists("poste"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom8);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(poste);
            }
            if (_MesSignets.Exists("raison"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom9);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("raison1"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom10);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("raison2"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom11);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(raison);
            }
            if (_MesSignets.Exists("spécialité"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom13);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(spécialité);
            }
            if (_MesSignets.Exists("wilaya"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom14);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(wilaya);
            }
            if (_MesSignets.Exists("wilaya1"))
            {
                //on positionne le range sur le signet et la fonction retourne true
                _MonSignet = _MesSignets.get_Item(ref Nom15);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonRange.InsertAfter(wilaya);
            }
            if (_MesSignets.Exists("logo"))
            {
                _MonSignet = _MesSignets.get_Item(ref Nom16);
                _MonSignet.Select();
                _MonRange = _MonSignet.Range;
                _MonRange.Delete(ref M, 1);
                _MonImage = _MonRange.InlineShapes.AddPicture(image + "\\logo.png", ref Faux, ref Vrai, ref M); //le chemin d'accès au logo image+ "\\Logo\\Logo.png"
            }


            oFileName = @chemin;
            _MonDocument.SaveAs(ref oFileName, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M, ref M);

            _MonDocument.Close(ref M, ref M, ref M);
            _ApplicationWord.Application.Quit(ref M, ref M, ref M);
        }
Beispiel #50
0
        private void save()
        {
            this.Enabled = false;


            Directory.CreateDirectory(".\\" + main.companyName + "\\wjgl\\542\\" + a0.Text + "");

            string temp = System.IO.Directory.GetCurrentDirectory();// d当前运行路径

            //    MessageBox.Show(temp);
            string OrignFile;//word模板路径

            OrignFile = "\\baseDB\\商标书式\\3 续展变更转让许可质押注销\\4转让\\2撤回转让移转申请注册商标申请书.dot";

            //开始写入数据

            string parFilePath = temp + OrignFile;//文件路径
            object FilePath    = parFilePath;

            Microsoft.Office.Interop.Word._Application AppliApp = new Microsoft.Office.Interop.Word.Application();
            AppliApp.Visible = false;
            Microsoft.Office.Interop.Word._Document doc = AppliApp.Documents.Add(ref FilePath);
            object missing    = System.Reflection.Missing.Value;
            object isReadOnly = false;



            doc.Activate();

            //数据写入代码段


            object aa = temp + "\\" + main.companyName + "\\wjgl\\542\\" + a0.Text + "\\" + a0.Text + ".docx";

            object[] MyBM = new object[34]; //创建一个书签数组

            for (int i = 0; i < 14; i++)    //给书签数组赋值
            {
                MyBM[i] = "a" + (i + 1).ToString();
            }

            MyBM[14] = "a15_1";
            MyBM[15] = "a15_2";



            for (int i = 16; i < 33; i++)//给书签数组赋值
            {
                MyBM[i] = "a" + i.ToString();
            }


            //给对应的书签位置写入数据
            doc.Bookmarks.get_Item(ref MyBM[0]).Range.Text  = a1.Text;
            doc.Bookmarks.get_Item(ref MyBM[1]).Range.Text  = a2.Text;
            doc.Bookmarks.get_Item(ref MyBM[2]).Range.Text  = a3.Text;
            doc.Bookmarks.get_Item(ref MyBM[3]).Range.Text  = a4.Text;
            doc.Bookmarks.get_Item(ref MyBM[4]).Range.Text  = a5.Text;
            doc.Bookmarks.get_Item(ref MyBM[5]).Range.Text  = a6.Text;
            doc.Bookmarks.get_Item(ref MyBM[6]).Range.Text  = a7.Text;
            doc.Bookmarks.get_Item(ref MyBM[7]).Range.Text  = a8.Text;
            doc.Bookmarks.get_Item(ref MyBM[8]).Range.Text  = a9.Text;
            doc.Bookmarks.get_Item(ref MyBM[9]).Range.Text  = a10.Text;
            doc.Bookmarks.get_Item(ref MyBM[10]).Range.Text = a11.Text;
            doc.Bookmarks.get_Item(ref MyBM[11]).Range.Text = a12.Text;
            doc.Bookmarks.get_Item(ref MyBM[12]).Range.Text = a13.Text;
            doc.Bookmarks.get_Item(ref MyBM[13]).Range.Text = a14.Text;



            if (a15.Text == "是")
            {
                doc.Bookmarks.get_Item(ref MyBM[14]).Range.Text = "✔";
            }
            if (a15.Text == "否")
            {
                doc.Bookmarks.get_Item(ref MyBM[15]).Range.Text = "✔";
            }


            doc.Bookmarks.get_Item(ref MyBM[16]).Range.Text = a16.Text;
            doc.Bookmarks.get_Item(ref MyBM[17]).Range.Text = a17.Text;

            doc.Bookmarks.get_Item(ref MyBM[18]).Range.Text = a18.Text;
            doc.Bookmarks.get_Item(ref MyBM[19]).Range.Text = a19.Text;

            doc.Bookmarks.get_Item(ref MyBM[20]).Range.Text = a20.Text;
            doc.Bookmarks.get_Item(ref MyBM[21]).Range.Text = a21.Text;
            doc.Bookmarks.get_Item(ref MyBM[22]).Range.Text = a22.Text;
            doc.Bookmarks.get_Item(ref MyBM[23]).Range.Text = a23.Text;

            doc.Bookmarks.get_Item(ref MyBM[24]).Range.Text = a24.Text;
            doc.Bookmarks.get_Item(ref MyBM[25]).Range.Text = a25.Text;
            doc.Bookmarks.get_Item(ref MyBM[26]).Range.Text = a26.Text;
            doc.Bookmarks.get_Item(ref MyBM[27]).Range.Text = a27.Text;

            doc.Bookmarks.get_Item(ref MyBM[28]).Range.Text = a28.Text;
            doc.Bookmarks.get_Item(ref MyBM[29]).Range.Text = a29.Text;
            doc.Bookmarks.get_Item(ref MyBM[30]).Range.Text = a30.Text;
            doc.Bookmarks.get_Item(ref MyBM[31]).Range.Text = a31.Text;

            doc.Bookmarks.get_Item(ref MyBM[32]).Range.Text = a32.Text;


            doc.SaveAs(ref aa);
            doc.Close();
            this.Enabled = true;
        }
        private void GenerateTemplate(string savePath, string templatePath)
        {
            //Yeah not pretty but ¯\_(ツ)_/¯
            try
            {
                //Support for Enviroment Vars like %username%
                object saveAsObj = Environment.ExpandEnvironmentVariables(savePath);
                templatePath = Environment.ExpandEnvironmentVariables(templatePath);

                DirectoryEntry de = new DirectoryEntry(Properties.Settings.Default.DomainServer);
                // Authentication details
                de.AuthenticationType = AuthenticationTypes.FastBind;
                DirectorySearcher DirectorySearcher = new DirectorySearcher(de);
                DirectorySearcher.ClientTimeout = TimeSpan.FromSeconds(30);
                // load all properties
                DirectorySearcher.PropertiesToLoad.Add("*");
                //Use Current logged in SamAccountName as filter            
                DirectorySearcher.Filter = "(sAMAccountName=" + UserPrincipal.Current.SamAccountName + ")";
                SearchResult result = DirectorySearcher.FindOne(); // There should only be one entry
                if (result != null)
                {
                    //Word init
                    //Source: https://www.techrepublic.com/blog/how-do-i/how-do-i-modify-word-documents-using-c/
                    object missing = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                    Microsoft.Office.Interop.Word.Document document = null;
                    if (File.Exists(templatePath))
                    {
                        object file = (object)templatePath;
                        object readOnly = true;
                        object isVisisble = false;
                        document = wordApp.Documents.Open(ref file, ref missing,
                            ref readOnly, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref isVisisble, ref missing, ref missing,
                            ref missing, ref missing
                            );

                        document.Activate();



                        //Loop through each properties

                        foreach (string propname in result.Properties.PropertyNames)
                        {
                            foreach (Object objValue in result.Properties[propname])
                            {
                                this.FindAndReplace(wordApp, "<" + propname.ToLower() + ">", objValue);
                            }
                        }
                        document.SaveAs2(ref saveAsObj, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLTemplate);
                        document.Close();
                    }
                    else
                    {
                        MessageBox.Show("Couldn't find Template File " + templatePath, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }


                }
                else
                {
                    //Didnt find anything, which should be impossible but safe is safe
                    MessageBox.Show("Couldn't find any entries for " + UserPrincipal.Current.SamAccountName, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Unknown Error: " + e.Message , "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
                    
        }
        private static Control CreateSentence(ChalLine line, StackPanel parent, Microsoft.Office.Interop.Word.Application wordApp)
        {
            var ctrl = new Control();

            string sentence = Sentences.GetSentenceToQuestion(line.Quest);

            var invalid_synonyms = GetInvalidSynonyms(line.Quest);

            //Console.WriteLine(sentence);

            var found = false;

            foreach (var word in sentence.SplitSentence())
            {
                if (found)
                {
                    CreateDefaultLabel(line, parent, word);
                    continue;
                }

                if (line.Quest.Type == Model.Voc)
                {
                    string answer = (line.Quest as VocVM).Answer;
                    var    answers_compatibility = Sentences.GetCompatibleWord(answer, word);

                    if (answers_compatibility.Length > 0)
                    {
                        ctrl = new ComboChallenge();
                        MyCbBxs.BuildSynonyms(answers_compatibility, invalid_synonyms, ctrl as ComboChallenge,
                                              parent, char.IsUpper(word[1]), wordApp);
                        found = true;
                    }
                    else
                    {
                        CreateDefaultLabel(line, parent, word);
                    }
                }
                else if (line.Quest.Type == Model.Spell)
                {
                    string text = (line.Quest as SpellVM).Text;


                    if (word.ContainsInsensitive(text))
                    {
                        ctrl = new TextBox();
                        ctrl.VerticalContentAlignment = VerticalAlignment.Center;
                        ctrl.Margin = new Thickness(1, 0, 1, 0);
                        ctrl.Width  = text.Length * 5 + 26;

                        ctrl.GotFocus += (source, e) => FileHtmlControls.PlayPronunciation(text, ctrl);
                        ctrl.KeyDown  += (source, e) =>
                        {
                            if (e.Key == System.Windows.Input.Key.Enter && line.Quest.Type == Model.Spell)
                            {
                                FileHtmlControls.PlayPronunciation(text, ctrl);
                            }
                        };

                        if (!text.EqualsNoCase(word))
                        {
                            //Console.WriteLine("answer was " + text);
                            var dif = word.ReplaceIgnoreCase(text, "");
                            (ctrl as TextBox).Text = dif;
                        }

                        parent.Children.Add(ctrl);
                        found = true;
                    }
                    else
                    {
                        CreateDefaultLabel(line, parent, word);
                    }
                }
            }

            return(ctrl);
        }
Beispiel #53
0
        addResultsToCutSheet(List <FieldData> fd, string strPath)
        {
            string strTxtTarget = FileManager.getFilesWithEditor("SELECT CUTSHEET", "UPDATE CUTSHEET", "Word Document (*.docx)|*.docx", strPath, "Select CutSheet to update: ");

            Microsoft.Office.Interop.Word.Application objWordApp = new Word();
            Microsoft.Office.Interop.Word.Document    objWordDoc = objWordApp.Documents.Open(strTxtTarget);

            objWordApp.Visible = true;

            Microsoft.Office.Interop.Word.Table objWordTable = objWordDoc.Tables[2];

            for (int i = 0; i < fd.Count; i++)
            {
                for (int j = 2; j <= objWordTable.Rows.Count; j++)
                {
                    Microsoft.Office.Interop.Word.Cell objWordCell = objWordTable.Cell(j, 2);
                    string strCellText = objWordCell.Range.Text;

                    string strPntNum = "";
                    int    k         = 1;
                    do
                    {
                        byte[] asciiBytes = Encoding.ASCII.GetBytes(strCellText.Substring(k, 1));
                        if (asciiBytes[0] == 13)
                        {
                            break;
                        }
                        strPntNum = strPntNum + strCellText.Substring(k, 1);
                        k         = k + 1;
                    } while (true);

                    string strGrade = "";
                    if (fd[i].PntNum == strPntNum)
                    {
                        objWordCell = objWordTable.Cell(j, 3);
                        strCellText = objWordCell.Range.Text;

                        k = 1;
                        do
                        {
                            byte[] asciiBytes = Encoding.ASCII.GetBytes(strCellText.Substring(k, 1));
                            if (asciiBytes[0] == 13)
                            {
                                break;
                            }
                            strGrade = strGrade + strCellText.Substring(k, 1);
                            k        = k + 1;
                        } while (true);

                        double dblGrade = double.Parse(strGrade);
                        double dblStake = System.Math.Round(fd[i].ElevStake, 4);

                        objWordCell = objWordTable.Cell(j, 4);
                        objWordCell.Range.InsertBefore(Convert.ToString(dblStake));

                        double dblDiff = System.Math.Round(dblGrade - dblStake, 2);

                        if (dblDiff < 0)
                        {
                            objWordCell = objWordTable.Cell(j, 5);
                            objWordCell.Range.InsertBefore(Convert.ToString(dblDiff * -1));
                        }
                        else
                        {
                            objWordCell = objWordTable.Cell(j, 6);
                            objWordCell.Range.InsertBefore(Convert.ToString(dblDiff));
                        }
                        break;
                    }
                }
            }
        }
        public static void PopulateRows(Grid parent, Model type, List <ChalLine> lines, Microsoft.Office.Interop.Word.Application wordApp = null)
        {
            var watcher = new Stopwatch();

            watcher.Start();

            Footer.Log("Loading...");

            lines.Clear();

            var actual_chosen = new List <int>();

            for (int row = 0; row < 4; row++)
            {
                var quest = QuestControl.GetRandomAvailableQuestion(type, actual_chosen);
                actual_chosen.Add(quest.Id);

                var item = CreateChalLine(quest, row, parent, wordApp);
                lines.Add(item);
                Footer.Log("Loading... Challenge " + (row + 1) + " was loaded in " + watcher.Elapsed.TotalSeconds + " seconds.");
            }
            ;

            Footer.Log("4 challenges loaded in " + watcher.Elapsed.TotalSeconds + " seconds.");
        }
Beispiel #55
0
    public static void GetColors()
    {
        Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
        Documents     docs = app.Documents;
        Document      doc  = docs.Open("C:\\temp\\ColorTest3.docx", ReadOnly: true);
        StringBuilder sb   = new StringBuilder();

        sb.AppendLine("<html><body>");
        sb.AppendLine("<table border=1 style='font-family:Arial;'>");
        sb.AppendLine("<tr><th>Text</th><th>RGB</th><th>Color</th></tr>");
        Dictionary <Color, int> counts = new Dictionary <Color, int>();

        foreach (Range rng in doc.StoryRanges)
        {
            foreach (Range rngChar in rng.Characters)               // by each character
            {
                _Font f   = rngChar.Font;
                int   rgb = (int)f.Color;
                //System.Drawing.Color col = System.Drawing.ColorTranslator.FromOle(rgb); // do not use - not 1-to-1
                var col = RgbColorRetriever.GetRGBColor(f.Color, doc);
                //ColorFormat cf = f.TextColor; // error - exception on ".doc" files
                sb.AppendLine(String.Format("<tr><td>{0}</td><td>{1},{2},{3}</td><td bgcolor='{4}'></td></tr>", rngChar.Text, col.R, col.G, col.B, ToHex(col)));
                //sb.AppendLine(rngChar.Text + " " + col.R + "/" + col.G + "/" + col.B);

                if (f.Color != WdColor.wdColorAutomatic)
                {
                    if (counts.ContainsKey(col))
                    {
                        counts[col]++;
                    }
                    else
                    {
                        counts[col] = 1;
                    }
                }

                Marshal.ReleaseComObject(f);
                Marshal.ReleaseComObject(rngChar);
            }
            Marshal.ReleaseComObject(rng);
        }
        sb.AppendLine(String.Format("<tr><td colspan=3>&nbsp;</td></tr>"));

        foreach (Range rng in doc.StoryRanges)
        {
            foreach (Range rngWord in rng.Words)               // by each word
            {
                _Font f   = rngWord.Font;
                int   rgb = (int)f.Color;
                //System.Drawing.Color col = System.Drawing.ColorTranslator.FromOle(rgb);  // do not use - not 1-to-1
                var col = RgbColorRetriever.GetRGBColor(f.Color, doc);
                sb.AppendLine(String.Format("<tr><td>{0}</td><td>{1},{2},{3}</td><td bgcolor='{4}'></td></tr>", rngWord.Text, col.R, col.G, col.B, ToHex(col)));
                //sb.AppendLine(rngWord.Text + " " + col.R + "/" + col.G + "/" + col.B);
                Marshal.ReleaseComObject(f);
                Marshal.ReleaseComObject(rngWord);
            }
            Marshal.ReleaseComObject(rng);
        }
        sb.AppendLine("</table>");
        sb.AppendLine("</body></html>");

        doc.Close(false);
        app.Quit(false);
        Marshal.ReleaseComObject(doc);
        Marshal.ReleaseComObject(docs);
        Marshal.ReleaseComObject(app);

        // if there is a tie, then there is the risk that the color will flip back and forth depending on how the dictionary is ordered
        Color  max  = counts.Count == 0 ? Color.Black : counts.Aggregate((i1, i2) => i1.Value > i2.Value ? i1 : i2).Key;
        String html = sb.ToString();         // testing only
    }
Beispiel #56
0
        // ---------------------------------------------------------------------------------------

        // ----------------------------- Open & handle word/excel files --------------------------
        public void openFile()
        {
            bool readOnly;

            if (openMode == "w")
            {
                readOnly = false;
            }
            else
            {
                readOnly = true;
            }

            switch (fileFormat)
            {
            case 0:
                try
                {
                    // ~~~~~~~~~~~~~~~~~~~~~~ Starting Word instance ~~~~~~~~~~~~~~~~~~~~
                    var wordApp = new Microsoft.Office.Interop.Word.Application();
                    wordApp.ShowAnimation = false;
                    wordApp.Visible       = false;
                    object wordAppMissing = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Word.Document wordFile = new Microsoft.Office.Interop.Word.Document();
                    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    // ~~ Opening Word file
                    wordFile = wordApp.Documents.Open(filePath, ref wordAppMissing, readOnly, ref wordAppMissing,
                                                      ref wordAppMissing, ref wordAppMissing, ref wordAppMissing,
                                                      ref wordAppMissing, ref wordAppMissing, ref wordAppMissing,
                                                      ref wordAppMissing, false, ref wordAppMissing, ref wordAppMissing,
                                                      ref wordAppMissing, ref wordAppMissing);

                    // ~~ Read mode: delay and then close file
                    if (readOnly == true)
                    {
                        delayFunc(timeToKeepOpen1);

                        wordFile.Close(false, ref wordAppMissing, ref wordAppMissing);
                        wordFile = null;
                    }
                    // ~~ Write mode: delay1 - write data - ?delay2? - close file
                    else
                    {
                        // Get random Lorem Ipsum text to write
                        Random r           = new Random(DateTime.Now.Millisecond);
                        int    randomLorem = r.Next(0, 5);

                        // first delay
                        delayFunc(timeToKeepOpen1);

                        wordFile.Content.SetRange(0, 0);
                        wordFile.Content.Text = lorems[randomLorem] + "\r\n";

                        // second delay (if any)
                        delayFunc(timeToKeepOpen2);

                        // saving & closing file
                        wordFile.SaveAs2(filePath);
                        wordFile.Close(false, ref wordAppMissing, ref wordAppMissing);
                        wordFile = null;
                    }

                    // ~~~~~~~~~~~~~~~~~~~~ Terminating Word instance ~~~~~~~~~~~~~~~~~~~
                    if (wordFile != null)
                    {
                        Marshal.ReleaseComObject(wordFile);
                    }
                    wordApp.Quit(ref wordAppMissing, ref wordAppMissing, ref wordAppMissing);
                    wordApp.Quit();
                    if (wordApp != null)
                    {
                        Marshal.ReleaseComObject(wordApp);
                    }
                    wordApp = null;
                    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error while opening word file");
                    Console.WriteLine(ex.Message);
                }
                break;

            case 1:
                try
                {
                    // ~~~~~~~~~~~~~~~~~~~~~ Starting Excel instance ~~~~~~~~~~~~~~~~~~~~
                    Microsoft.Office.Interop.Excel.Application excelApp;
                    Microsoft.Office.Interop.Excel.Workbook    workBook;
                    Microsoft.Office.Interop.Excel.Worksheet   workSheet;
                    excelApp = new Microsoft.Office.Interop.Excel.Application();
                    object excelAppMissing = System.Reflection.Missing.Value;
                    excelApp.Visible       = false;
                    excelApp.DisplayAlerts = false;
                    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    // ~~ Opening Excel file
                    workBook = excelApp.Workbooks.Open(filePath, excelAppMissing, readOnly);

                    // ~~ Read mode: delay and then close file
                    if (readOnly == true)
                    {
                        delayFunc(timeToKeepOpen1);

                        workBook.Close(false);
                        workBook = null;
                    }
                    // ~~ Write mode: delay1 - write data - ?delay2? - close file
                    else
                    {
                        // Selecting random rows and columns count
                        Random r           = new Random(DateTime.Now.Millisecond);
                        int    rowsToWrite = r.Next(10, 70);
                        int    colsToWrite = r.Next(10, 30);

                        // Opening & naming worksheet
                        workSheet      = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet;
                        workSheet.Name = "Edited file";

                        // first delay
                        delayFunc(timeToKeepOpen1);

                        // writting random numbers
                        var data = new object[rowsToWrite, colsToWrite];
                        for (var row = 1; row <= rowsToWrite; row++)
                        {
                            for (var column = 1; column <= colsToWrite; column++)
                            {
                                data[row - 1, column - 1] = r.Next(99, 99999);
                            }
                        }

                        var startCell  = (Range)workSheet.Cells[1, 1];
                        var endCell    = (Range)workSheet.Cells[rowsToWrite, colsToWrite];
                        var writeRange = workSheet.Range[startCell, endCell];

                        writeRange.Value2 = data;

                        // second delay (if any)
                        delayFunc(timeToKeepOpen2);

                        // saving & closing file
                        workBook.SaveAs(filePath);
                        workBook.Close(true, filePath, excelAppMissing);
                        workSheet = null;
                        workBook  = null;
                        if (workSheet != null)
                        {
                            Marshal.ReleaseComObject(workSheet);
                        }
                    }

                    // ~~~~~~~~~~~~~~~~~~~ Terminating Excel instance ~~~~~~~~~~~~~~~~~~~
                    if (workBook != null)
                    {
                        Marshal.ReleaseComObject(workBook);
                    }
                    excelApp.Quit();
                    excelApp = null;
                    if (excelApp != null)
                    {
                        Marshal.ReleaseComObject(excelApp);
                    }
                    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error while opening excel file");
                    Console.WriteLine(ex.Message);
                }
                break;

            default:
                Console.WriteLine("Error! Wrong file format!");
                Console.WriteLine("Exiting...");
                Environment.Exit(1);
                break;
            }
        }
Beispiel #57
0
        private void save()
        {
            this.Enabled = false;



            Directory.CreateDirectory(".\\" + main.companyName + "\\wjgl\\201\\" + a0.Text + "");

            string temp = System.IO.Directory.GetCurrentDirectory();// d当前运行路径

            //    MessageBox.Show(temp);
            string OrignFile;//模板路径

            OrignFile = "\\baseDB\\商标书式\\2 异议\\01 商标异议申请书.dot";

            //开始写入数据

            string parFilePath = temp + OrignFile;//文件路径
            object FilePath    = parFilePath;

            Microsoft.Office.Interop.Word._Application AppliApp = new Microsoft.Office.Interop.Word.Application();
            AppliApp.Visible = false;
            Microsoft.Office.Interop.Word._Document doc = AppliApp.Documents.Add(ref FilePath);
            object missing    = System.Reflection.Missing.Value;
            object isReadOnly = false;



            doc.Activate();

            //数据写入代码段


            object aa = temp + "\\" + main.companyName + "\\wjgl\\201\\" + a0.Text + "\\" + a0.Text + ".docx";

            object[] MyBM = new object[16]; //创建一个书签数组

            for (int i = 0; i < 9; i++)     //给书签数组赋值
            {
                MyBM[i] = "a" + (i + 1).ToString();
            }
            MyBM[9]  = "a10";
            MyBM[10] = "a11";
            MyBM[11] = "a12_1";
            MyBM[12] = "a12_2";
            MyBM[13] = "a13";
            MyBM[14] = "a14";
            MyBM[15] = "a15";



            //给对应的书签位置写入数据
            doc.Bookmarks.get_Item(ref MyBM[0]).Range.Text = a1.Text;
            doc.Bookmarks.get_Item(ref MyBM[1]).Range.Text = a2.Text;
            doc.Bookmarks.get_Item(ref MyBM[2]).Range.Text = a3.Text;
            doc.Bookmarks.get_Item(ref MyBM[3]).Range.Text = a4.Text;
            doc.Bookmarks.get_Item(ref MyBM[4]).Range.Text = a5.Text;
            doc.Bookmarks.get_Item(ref MyBM[5]).Range.Text = a6.Text;
            doc.Bookmarks.get_Item(ref MyBM[6]).Range.Text = a7.Text;
            doc.Bookmarks.get_Item(ref MyBM[7]).Range.Text = a8.Text;
            doc.Bookmarks.get_Item(ref MyBM[8]).Range.Text = a9.Text;

            doc.Bookmarks.get_Item(ref MyBM[9]).Range.Text  = a10.Text;
            doc.Bookmarks.get_Item(ref MyBM[10]).Range.Text = a11.Text;

            string xx;

            if (a12.Text == "是")
            {
                xx = "✔";
            }
            else
            {
                xx = " ";
            }
            doc.Bookmarks.get_Item(ref MyBM[11]).Range.Text = xx;
            if (a12.Text == "否")
            {
                xx = "✔";
            }
            else
            {
                xx = " ";
            }
            doc.Bookmarks.get_Item(ref MyBM[12]).Range.Text = xx;



            doc.Bookmarks.get_Item(ref MyBM[13]).Range.Text = a13.Text;
            doc.Bookmarks.get_Item(ref MyBM[14]).Range.Text = a14.Text;
            doc.Bookmarks.get_Item(ref MyBM[15]).Range.Text = a15.Text;



            doc.SaveAs(ref aa);
            doc.Close();
            this.Enabled = true;
        }
Beispiel #58
0
        private void button2_Click(object sender, EventArgs e)
        {
            object oTemplate = "";
            object oMissing  = System.Reflection.Missing.Value;

            //创建一个Word应用程序实例
            Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();
            //设置为不可见
            oWord.Visible = false;
            //模板文件地址,这里假设在X盘根目录
            try
            {
                OpenFileDialog openFileDialogEmpImage = new OpenFileDialog();
                //          openFileDialogEmpImage.Filter = "*.jpg|*.jpg|*.png|*.png|*.bmp|*.bmp|*.tiff|*.tiff";//图片格式
                if (openFileDialogEmpImage.ShowDialog() == DialogResult.OK)
                {
                    //           isUpLoadPicture = true;//记录是否上传了相片,用于后面保存操作使用:是一个成员变
                    try
                    {
                        empUpLoadPictureRealPos = openFileDialogEmpImage.FileName;//实际的文件路径+文件名
                        String[] empImageData = empUpLoadPictureRealPos.Split('.');
                        //empImageData[1]:是上传的图片的后缀名
                        empUpLoadPictureFormat = empImageData[1];
                        oTemplate = openFileDialogEmpImage.FileName;
                    }
                    catch
                    {
                        MessageBox.Show("您选择的文件不能被读取或文件类型不对!", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch
            {
            }
            //  object oTemplate = "C:\\Users\\IHCI\\Desktop\\档案加工流转单.dot";
            //以模板为基础生成文档
            Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
            //声明书签数组
            object[] oBookMark = new object[21];
            //赋值书签名
            oBookMark[0]  = "a1";
            oBookMark[1]  = "a2";
            oBookMark[2]  = "a3";
            oBookMark[3]  = "a4";
            oBookMark[4]  = "a5";
            oBookMark[5]  = "a6";
            oBookMark[6]  = "a7";
            oBookMark[7]  = "a8";
            oBookMark[8]  = "a9";
            oBookMark[9]  = "a10";
            oBookMark[10] = "a11";
            oBookMark[11] = "a12";
            oBookMark[12] = "a13";
            oBookMark[13] = "a14";
            oBookMark[14] = "a15";
            oBookMark[15] = "a16";
            oBookMark[16] = "a17";
            oBookMark[17] = "a18";
            oBookMark[18] = "a19";
            oBookMark[19] = "a20";

            //赋值任意数据到书签的位置
            oDoc.Bookmarks.get_Item(ref oBookMark[0]).Range.Text  = textBoxXMDW.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[1]).Range.Text  = textBoxLQPCH.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[2]).Range.Text  = textBoxLZDH.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[3]).Range.Text  = textBoxDALX.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[4]).Range.Text  = textBoxGDFS.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[5]).Range.Text  = textBoxNX.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[6]).Range.Text  = textBoxZRR.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[7]).Range.Text  = textBoxYS.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[8]).Range.Text  = textBoxJGLX.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[9]).Range.Text  = textBox1.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[10]).Range.Text = textBox2.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[11]).Range.Text = textBox3.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[12]).Range.Text = textBox4.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[13]).Range.Text = textBox5.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[14]).Range.Text = textBox6.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[15]).Range.Text = textBox7.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[16]).Range.Text = textBox8.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[17]).Range.Text = textBox9.Text.Trim();
            oDoc.Bookmarks.get_Item(ref oBookMark[18]).Range.Text = dateTimePicker1.Value.ToString("yyyy-MM-dd");
            oDoc.Bookmarks.get_Item(ref oBookMark[19]).Range.Text = dateTimePicker2.Value.ToString("yyyy-MM-dd");


            //弹出保存文件对话框,保存生成的Word
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter     = "Word Document(*.doc)|*.doc";
            sfd.DefaultExt = "Word Document(*.doc)|*.doc";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                object filename = sfd.FileName;

                oDoc.SaveAs(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);
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                //关闭word
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
            }

            ExportToExcel d = new ExportToExcel();

            d.OutputAsExcelFile(dataGridView1);
        }
Beispiel #59
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox2.Text != "")
            {
                #region 冷库
                if (comboBox2.Text == "冷库验证项目模拟报告模板")
                {
                    object filename = Application.StartupPath + "\\bin\\" + Global.templateName;

                    object G_Missing = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                    Microsoft.Office.Interop.Word.Document    wordDoc;
                    wordDoc = wordApp.Documents.Open(filename);
                    wordDoc.ActiveWindow.Visible = false;//打开word

                    Microsoft.Office.Interop.Word.Range myRange = wordDoc.Range();

                    Microsoft.Office.Interop.Word.Find f = myRange.Find;
                    f.Text = "冷库名称/编号:";
                    f.ClearFormatting();

                    bool finded = f.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                            );

                    myRange      = wordDoc.Range(myRange.End, myRange.End + 28);
                    myRange.Text = textBox1.Text;

                    Microsoft.Office.Interop.Word.Range myRange1 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f1       = myRange1.Find;
                    f1.Text = ":长";
                    f1.ClearFormatting();

                    bool finded1 = f1.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange1      = wordDoc.Range(myRange1.End, myRange1.End + 4);
                    myRange1.Text = textBox2.Text;

                    Microsoft.Office.Interop.Word.Range myRange2 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f2       = myRange2.Find;
                    f2.Text = ",宽";
                    f2.ClearFormatting();

                    bool finded2 = f2.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange2      = wordDoc.Range(myRange2.End, myRange2.End + 4);
                    myRange2.Text = textBox4.Text;

                    Microsoft.Office.Interop.Word.Range myRange3 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f3       = myRange3.Find;
                    f3.Text = ",高";
                    f3.ClearFormatting();

                    bool finded3 = f3.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange3      = wordDoc.Range(myRange3.End, myRange3.End + 4);
                    myRange3.Text = textBox5.Text;

                    Microsoft.Office.Interop.Word.Range myRange4 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f4       = myRange4.Find;
                    f4.Text = "体积约为";
                    f4.ClearFormatting();

                    bool finded4 = f4.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange4      = wordDoc.Range(myRange4.End, myRange4.End + 6);
                    myRange4.Text = textBox6.Text;

                    Microsoft.Office.Interop.Word.Range myRange5 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f5       = myRange5.Find;
                    f5.Text = "出入口";
                    f5.ClearFormatting();

                    bool finded5 = f5.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange5      = wordDoc.Range(myRange5.End, myRange5.End + 4);
                    myRange5.Text = textBox3.Text;

                    Microsoft.Office.Interop.Word.Range myRange6 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f6       = myRange6.Find;
                    f6.Text = "货架数量";
                    f6.ClearFormatting();

                    bool finded6 = f6.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange6      = wordDoc.Range(myRange6.End, myRange6.End + 5);
                    myRange6.Text = textBox7.Text;

                    Microsoft.Office.Interop.Word.Range myRange7 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f7       = myRange7.Find;
                    f7.Text = "监控系统探头";
                    f7.ClearFormatting();

                    bool finded7 = f7.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange7      = wordDoc.Range(myRange7.End, myRange7.End + 6);
                    myRange7.Text = textBox8.Text;

                    Microsoft.Office.Interop.Word.Range myRange8 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f8       = myRange8.Find;
                    f8.Text = "6风机";
                    f8.ClearFormatting();

                    bool finded8 = f8.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange8      = wordDoc.Range(myRange8.End, myRange8.End + 4);
                    myRange8.Text = textBox9.Text;

                    Microsoft.Office.Interop.Word.Range myRange9 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f9       = myRange9.Find;
                    f9.Text = "(  ";
                    f9.ClearFormatting();

                    bool finded9 = f9.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange9      = wordDoc.Range(myRange9.End, myRange9.End + 2);
                    myRange9.Text = textBox10.Text;

                    Microsoft.Office.Interop.Word.Range myRange10 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f10       = myRange10.Find;
                    f10.Text = "~";
                    f10.ClearFormatting();

                    bool finded10 = f10.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                                );

                    myRange10      = wordDoc.Range(myRange10.End, myRange10.End + 2);
                    myRange10.Text = textBox12.Text;

                    Microsoft.Office.Interop.Word.Range myRange11 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f11       = myRange11.Find;
                    f11.Text = "(   ";
                    f11.ClearFormatting();

                    bool finded11 = f11.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                                );

                    myRange11      = wordDoc.Range(myRange11.End, myRange11.End + 2);
                    myRange11.Text = textBox11.Text;

                    Microsoft.Office.Interop.Word.Range myRange12 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f12       = myRange12.Find;
                    f12.Text = "~ ";
                    f12.ClearFormatting();

                    bool finded12 = f12.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                                );

                    myRange12      = wordDoc.Range(myRange12.End, myRange12.End + 2);
                    myRange12.Text = textBox13.Text;

                    wordDoc.Close();
                    wordApp.Quit();
                    wordApp = null;

                    try
                    {
                        Global.objectLen    = Convert.ToDouble(textBox2.Text);
                        Global.objectWidth  = Convert.ToDouble(textBox4.Text);
                        Global.objectHeight = Convert.ToDouble(textBox5.Text);


                        Global.tempLimitLow  = Convert.ToDouble(textBox10.Text);
                        Global.tempLimitHigh = Convert.ToDouble(textBox12.Text);
                    }
                    catch (Exception)
                    {
                    }
                    this.Close();
                }
                #endregion

                #region 灭菌器
                if (comboBox2.Text == "灭菌器验证项目模拟报告模板")
                {
                    object filename = Application.StartupPath + "\\bin\\" + Global.templateName;
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                    Microsoft.Office.Interop.Word.Document    wordDoc;
                    wordDoc = wordApp.Documents.Open(filename);
                    wordDoc.ActiveWindow.Visible = false;
                    Microsoft.Office.Interop.Word.Table nowtable2 = wordDoc.Tables[4];
                    nowtable2.Cell(2, 3).Range.InsertAfter(textBox25.Text);
                    nowtable2.Cell(3, 3).Range.InsertAfter(textBox26.Text);
                    nowtable2.Cell(4, 3).Range.InsertAfter(textBox27.Text);
                    nowtable2.Cell(5, 3).Range.InsertAfter(textBox28.Text);
                    nowtable2.Cell(2, 4).Range.InsertAfter(textBox29.Text);
                    nowtable2.Cell(3, 4).Range.InsertAfter(textBox30.Text);
                    nowtable2.Cell(4, 4).Range.InsertAfter(textBox31.Text);
                    nowtable2.Cell(5, 4).Range.InsertAfter(textBox32.Text);
                    nowtable2.Cell(6, 1).Range.InsertAfter(textBox34.Text);
                    nowtable2.Cell(6, 2).Range.InsertAfter(textBox44.Text);
                    nowtable2.Cell(7, 1).Range.InsertAfter(textBox45.Text);
                    nowtable2.Cell(7, 2).Range.InsertAfter(textBox46.Text);

                    Microsoft.Office.Interop.Word.Table nowtable = wordDoc.Tables[5];
                    nowtable.Cell(2, 4).Range.InsertAfter(textBox33.Text);
                    nowtable.Cell(3, 4).Range.InsertAfter(textBox39.Text);
                    nowtable.Cell(4, 4).Range.InsertAfter(textBox41.Text);
                    nowtable.Cell(5, 4).Range.InsertAfter(textBox47.Text);
                    nowtable.Cell(6, 4).Range.InsertAfter(textBox48.Text);
                    nowtable.Cell(7, 1).Range.InsertAfter(textBox34.Text);
                    nowtable.Cell(7, 2).Range.InsertAfter(textBox44.Text);
                    nowtable.Cell(8, 1).Range.InsertAfter(textBox45.Text);
                    nowtable.Cell(8, 2).Range.InsertAfter(textBox46.Text);

                    Microsoft.Office.Interop.Word.Table nowtable1 = wordDoc.Tables[6];
                    nowtable1.Cell(2, 4).Range.InsertAfter(textBox35.Text);
                    nowtable1.Cell(3, 4).Range.InsertAfter(textBox36.Text);
                    nowtable1.Cell(4, 4).Range.InsertAfter(textBox37.Text);
                    nowtable1.Cell(5, 4).Range.InsertAfter(textBox38.Text);
                    nowtable1.Cell(6, 4).Range.InsertAfter(textBox40.Text);
                    nowtable1.Cell(7, 4).Range.InsertAfter(textBox42.Text);
                    nowtable1.Cell(8, 4).Range.InsertAfter(textBox43.Text);
                    nowtable1.Cell(9, 1).Range.InsertAfter(textBox34.Text);
                    nowtable1.Cell(9, 2).Range.InsertAfter(textBox44.Text);
                    nowtable1.Cell(10, 1).Range.InsertAfter(textBox45.Text);
                    nowtable1.Cell(10, 2).Range.InsertAfter(textBox46.Text);
                    wordDoc.Save();
                    wordApp.Quit();
                    wordApp = null;
                    this.Close();



                    try
                    {
                        Global.objectLen    = Convert.ToDouble(textBox15.Text);
                        Global.objectWidth  = Convert.ToDouble(textBox19.Text);
                        Global.objectHeight = Convert.ToDouble(textBox20.Text);



                        Global.tempLimitLow = Convert.ToDouble(textBox16.Text);

                        Global.tempLimitHigh = Convert.ToDouble(textBox18.Text);
                    }
                    catch (Exception)
                    {
                    }
                }

                #endregion

                #region 高温热处理炉
                if (comboBox2.Text == "高温热处理炉验证项目模拟报告模板")
                {
                    object filename = Application.StartupPath + "\\bin\\" + Global.templateName;

                    object G_Missing = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                    Microsoft.Office.Interop.Word.Document    wordDoc;
                    wordDoc = wordApp.Documents.Open(filename);
                    wordDoc.ActiveWindow.Visible = false;//打开word

                    Microsoft.Office.Interop.Word.Range myRange = wordDoc.Range();

                    Microsoft.Office.Interop.Word.Find f = myRange.Find;
                    f.Text = "2.1.1热处理炉型号/编号:";
                    f.ClearFormatting();

                    bool finded = f.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                            ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                            );

                    myRange      = wordDoc.Range(myRange.End, myRange.End + 28);
                    myRange.Text = textBox14.Text;

                    Microsoft.Office.Interop.Word.Range myRange1 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f1       = myRange1.Find;
                    f1.Text = "2.1.2热处理炉制造厂家:";
                    f1.ClearFormatting();

                    bool finded1 = f1.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange1      = wordDoc.Range(myRange1.End, myRange1.End + 28);
                    myRange1.Text = textBox23.Text;

                    Microsoft.Office.Interop.Word.Range myRange2 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f2       = myRange2.Find;
                    f2.Text = "2.1.3热处理炉规格(内径):长";
                    f2.ClearFormatting();

                    bool finded2 = f2.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange2      = wordDoc.Range(myRange2.End, myRange2.End + 4);
                    myRange2.Text = textBox15.Text;

                    Microsoft.Office.Interop.Word.Range myRange3 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f3       = myRange3.Find;
                    f3.Text = ",宽";
                    f3.ClearFormatting();

                    bool finded3 = f3.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange3      = wordDoc.Range(myRange3.End, myRange3.End + 4);
                    myRange3.Text = textBox19.Text;

                    Microsoft.Office.Interop.Word.Range myRange4 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f4       = myRange4.Find;
                    f4.Text = ",高";
                    f4.ClearFormatting();

                    bool finded4 = f4.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange4      = wordDoc.Range(myRange4.End, myRange4.End + 4);
                    myRange4.Text = textBox20.Text;

                    Microsoft.Office.Interop.Word.Range myRange5 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f5       = myRange5.Find;
                    f5.Text = "体积约为";
                    f5.ClearFormatting();

                    bool finded5 = f5.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange5      = wordDoc.Range(myRange5.End, myRange5.End + 6);
                    myRange5.Text = textBox21.Text;

                    Microsoft.Office.Interop.Word.Range myRange6 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f6       = myRange6.Find;
                    f6.Text = "2.1.4监控系统探头";
                    f6.ClearFormatting();

                    bool finded6 = f6.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange6      = wordDoc.Range(myRange6.End, myRange6.End + 6);
                    myRange6.Text = textBox17.Text;

                    Microsoft.Office.Interop.Word.Range myRange7 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f7       = myRange7.Find;
                    f7.Text = "(  ";
                    f7.ClearFormatting();

                    bool finded7 = f7.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange7      = wordDoc.Range(myRange7.End, myRange7.End + 5);
                    myRange7.Text = textBox16.Text;

                    Microsoft.Office.Interop.Word.Range myRange8 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f8       = myRange8.Find;
                    f8.Text = "~";
                    f8.ClearFormatting();

                    bool finded8 = f8.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange8      = wordDoc.Range(myRange8.End, myRange8.End + 7);
                    myRange8.Text = textBox18.Text;

                    Microsoft.Office.Interop.Word.Range myRange9 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f9       = myRange9.Find;
                    f9.Text = "2.2.2保温精度范围:";
                    f9.ClearFormatting();

                    bool finded9 = f9.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                              ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                              );

                    myRange9      = wordDoc.Range(myRange9.End, myRange9.End + 7);
                    myRange9.Text = textBox22.Text;

                    Microsoft.Office.Interop.Word.Range myRange10 = wordDoc.Range();
                    Microsoft.Office.Interop.Word.Find  f10       = myRange10.Find;
                    f10.Text = "2.2.3常用温度值:";
                    f10.ClearFormatting();

                    bool finded10 = f10.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                                ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                                );

                    myRange10      = wordDoc.Range(myRange10.End, myRange10.End + 12);
                    myRange10.Text = textBox24.Text;

                    wordDoc.Save();
                    wordApp.Quit();
                    wordApp = null;
                    this.Close();
                }
                #endregion
            }
            else
            {
                MessageBox.Show("请选择报表模板。");
            }
        }
Beispiel #60
0
        private void Print()
        {
            AnalyzeView analyzeView = new AnalyzeView();

            analyzeView.Show();

            return;

            CalendarView calendar = new CalendarView();

            calendar.ViewModel.OKClicked += (s, e) =>
            {
                var data = e.EventData;

                var startDate = data.Item1;
                var endDate   = data.Item2;

                if (startDate > endDate)
                {
                    var temp = startDate;
                    startDate = endDate;
                    endDate   = temp;
                }

                var result = _database.GetPeriodListAccount(DateHelper.ToStringDate(startDate), DateHelper.ToStringDate(endDate));
                try
                {
                    var modelList = JsonConvert.DeserializeObject <List <DailyModel> >(result);
                    modelList.Sort((DailyModel x, DailyModel y) => x.Date.CompareTo(y.Date));

                    if (modelList != null && modelList.Count > 0)
                    {
                        Microsoft.Office.Interop.Word.Application word     = new Microsoft.Office.Interop.Word.Application();
                        Microsoft.Office.Interop.Word.Document    document = new Microsoft.Office.Interop.Word.Document();

                        Object oMissing = System.Reflection.Missing.Value;
                        Object oFalse   = false;

                        Microsoft.Office.Interop.Word.Paragraph paragraph = document.Content.Paragraphs.Add(ref oMissing);
                        paragraph.Range.Font.Size = 15;

                        object start     = 0;
                        object end       = 0;
                        object oEndOfDoc = "\\endofdoc";
                        Microsoft.Office.Interop.Word.Range tableLocation = document.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        var table = document.Content.Tables.Add(tableLocation, modelList.Count, 4);
                        table.Range.Font.Size          = 15;
                        table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        table.AllowAutoFit             = true;

                        int row = 1;
                        foreach (var model in modelList)
                        {
                            table.Cell(row, 1).Range.Text = model.Date;
                            table.Cell(row, 2).Range.Text = model.Type.ToString();
                            table.Cell(row, 3).Range.Text = model.Name;

                            if (model.Type == ItemType.Outgo || model.Type == ItemType.Kakao ||
                                model.Type == ItemType.Samsung || model.Type == ItemType.Hana ||
                                model.Type == ItemType.Hyundai || model.Type == ItemType.Cash)
                            {
                                table.Cell(row, 4).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;
                            }
                            else
                            {
                                table.Cell(row, 4).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlue;
                            }

                            table.Cell(row, 4).Range.Text = "\\ " + string.Format("{0:###,###,###,###,###,###,###}", model.Amount);

                            row++;
                        }

                        table.Columns[1].AutoFit();
                        Single width1 = table.Columns[1].Width;
                        table.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent); // fill page width
                        table.Columns[1].SetWidth(width1, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustFirstColumn);

                        table.Columns[2].AutoFit();
                        Single width2 = table.Columns[2].Width;
                        table.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent); // fill page width
                        table.Columns[2].SetWidth(width2, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustFirstColumn);

                        table.Columns[3].AutoFit();
                        Single width3 = table.Columns[3].Width;
                        table.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent); // fill page width
                        table.Columns[3].SetWidth(width3, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustFirstColumn);

                        table.Columns[4].AutoFit();
                        Single width4 = table.Columns[4].Width;
                        table.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent); // fill page width
                        table.Columns[4].SetWidth(width4, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustFirstColumn);

                        table.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter;

                        document.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;

                        Object fileName = Directory.GetCurrentDirectory() + "\\" + "Report_" + DateHelper.ToStringDate(startDate) + "_" + DateHelper.ToStringDate(endDate) + ".doc";

                        try
                        {
                            document.SaveAs(ref fileName);

                            System.Diagnostics.Process.Start(fileName.ToString());

                            if (word.ActivePrinter != null || word.ActivePrinter != "")
                            {
                                document.PrintOut(ref oFalse, 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, ref oMissing, ref oMissing, ref oMissing);
                            }

                            document.Close();
                            word.Quit();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("오류가 발생했습니다. 다시 시도 해 주세요.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            };
            calendar.ViewModel.Closing += (s, e) =>
            {
                calendar.Close();
            };
            calendar.ViewModel.SelectedStartDate = DateHelper.GetMondayOfWeek(_selectedDate);
            calendar.ViewModel.SelectedEndDate   = DateHelper.GetSundayOfWeek(_selectedDate);
            calendar.ShowDialog();
        }