Beispiel #1
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 override void Initialised(Document document)
 {
     if (document != null)
     {
         vstoDocument= ((ApplicationFactory)VstoFactory).GetVstoObject(document);
         vstoDocument.SelectionChange += VstoDocumentOnSelectionChange;
         RibbonVisible = true;
     }
 }
        public void Initialised(object context)
        {
            document = context as Document;

            if (document != null)
            {
                vstoDocument = ((ApplicationFactory)VstoFactory).GetVstoObject(document);
                vstoDocument.SelectionChange += VstoDocumentOnSelectionChange;
            }
        }
Beispiel #4
0
        public frmMain()
        {
            InitializeComponent();
            Size = new Size(371, 481);
            loadedDoc = new Microsoft.Office.Interop.Word.Document();
            tmpDoc    = new Microsoft.Office.Interop.Word.Document();

            // Set the theme
            RefreshTheme(Theme.NULL);
        }
Beispiel #5
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();
 }
Beispiel #6
0
        // Open a file (the file must exists) and activate it
        public void Open(string strFileName)
        {
            object fileName = strFileName;
            object readOnly = false;
            object isVisible = true;

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

            oDoc.Activate();
        }
Beispiel #7
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);
 }
        /// <summary>
        /// Закрытие приложения
        /// </summary>
        public void QuitApplication()
        {
            if (application != null)
            {
                range = null;
                table = null;
                document = null;
                application.Quit();
                application = null;                
            }

        }
Beispiel #9
0
 public virtual void Export()
 {
     try
     {
         Document = WordApp.Documents.Add(TemplatePath);
         Document.Paragraphs.LineSpacing = 12F;
         WordApp.Visible = true;
         SetBaseFonts();
         FillTable(Document, UnitList);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
         object doNotSave = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
         object missing = Type.Missing;
         ((Microsoft.Office.Interop.Word._Application) WordApp).Quit(ref doNotSave, ref missing, ref missing);
     }
 }
        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 #11
0
        public void CreateWord(String HtmlFile, string fileWord)
        {
            object filename1 = HtmlFile;

            object oMissing = System.Reflection.Missing.Value;

            object oFalse = false;

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

            Microsoft.Office.Interop.Word.Document oDoc = new
            Microsoft.Office.Interop.Word.Document();

            oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref
            oMissing, ref oMissing);

            oWord.Visible = false;

            oDoc = oWord.Documents.Open(ref filename1, 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);

            filename1 = fileWord;

            object fileFormat =
            Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;

            oDoc.SaveAs(ref filename1, ref fileFormat, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing);

            oDoc.Close(ref oFalse, ref oMissing, ref oMissing);

            oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
        }
Beispiel #12
0
        /// <summary>
        /// 附加dot模版文件
        /// </summary>
        private void LoadDotFile(string strDotFile)
        {
            if (!string.IsNullOrEmpty(strDotFile))
            {
                Microsoft.Office.Interop.Word.Document wDot = null;
                if (oWordApplic != null)
                {
                    oDoc = oWordApplic.ActiveDocument;

                    oWordApplic.Selection.WholeStory();

                    //string strContent = oWordApplic.Selection.Text;

                    oWordApplic.Selection.Copy();
                    wDot = CreateWordDocument(strDotFile, true);

                    object bkmC = "Content";

                    if (oWordApplic.ActiveDocument.Bookmarks.Exists("Content") == true)
                    {
                        oWordApplic.ActiveDocument.Bookmarks.get_Item
                        (ref bkmC).Select();
                    }

                    //对标签"Content"进行填充
                    //直接写入内容不能识别表格什么的
                    //oWordApplic.Selection.TypeText(strContent);
                    oWordApplic.Selection.Paste();
                    oWordApplic.Selection.WholeStory();
                    oWordApplic.Selection.Copy();
                    wDot.Close(ref missing, ref missing, ref missing);

                    oDoc.Activate();
                    oWordApplic.Selection.Paste();

                }
            }
        }
Beispiel #13
0
        public void refresh_datagrid()
        {
            string name = find_name.Text;
            string bd   = find_bd.Text;
            string doc  = stat_doc.Text;

            find_logs.Clear();
            if (doc == "")
            {
                find_logs           = database.request(String.Format("select * from logs where name like '%{0}%' and bd like '%{1}%';", name.ToUpperInvariant(), bd));
                datagrid.DataSource = find_logs;
            }
            else
            {
                find_logs = database.request(String.Format("select * from logs where name like '%{0}%' and bd like '%{1}%' and type like '%{2}%';", name.ToUpperInvariant(), bd, doc));
                DataTable  data = new DataTable();
                DataColumn column;
                DataRow    row;

                filepath = "";
                foreach (DataRow dr in docs.Rows)
                {
                    if (dr["name"].ToString() == doc)
                    {
                        filepath = dr["filepath"].ToString();
                    }
                }

                column            = new DataColumn();
                column.ColumnName = "id";
                data.Columns.Add(column);

                column            = new DataColumn();
                column.ColumnName = "Дата";
                data.Columns.Add(column);

                object missing = System.Reflection.Missing.Value;
                try
                {
                    document = win_word.Documents.Add(filepath, false, ref missing, ref missing);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }


                bookmarks = new SortedList <Int32, Microsoft.Office.Interop.Word.Bookmark>();
                foreach (Microsoft.Office.Interop.Word.Bookmark bookmark in document.Bookmarks)
                {
                    bookmarks.Add(bookmark.Start, bookmark);
                }
                for (int i = 0; i < bookmarks.Count; i++)
                {
                    column            = new DataColumn();
                    column.ColumnName = bookmarks.Values[i].Name;
                    data.Columns.Add(column);
                }
                int k = 0;
                foreach (DataRow dr in find_logs.Rows)
                {
                    row = data.NewRow();
                    string   date_str = dr["date"].ToString();
                    DateTime date     = Convert.ToDateTime(date_str);

                    string   result = dr["result"].ToString();
                    string[] values = result.Split('|');
                    row[0] = k;
                    k++;
                    row[1] = date.ToString("yyyy.MM.dd");
                    for (int i = 0; i < values.Length - 1; i++)
                    {
                        row[i + 2] = values[i];
                    }
                    data.Rows.Add(row);
                }

                datagrid.DataSource         = data;
                datagrid.Columns[0].Visible = false;
            }

            datagrid.Refresh();
            datagrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader;

            datagrid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
        }
Beispiel #14
0
        public void FormExam(int ID, int PaperCount, int QuestionsCount, string Teacher, string Cafedral, int course, int semester, string path)
        {
            string Subject = unit.SubjectRepository.Get(ID).Name;

            Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
            winword.ShowAnimation = false;
            winword.Visible       = false;
            object missing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            for (int i = 0; i < PaperCount; i++)
            {
                var exam = new Model.Exam();
                exam.Title = "Билет №" + (i + 1).ToString();

                var papers = exam.BuildQuestionList(GetQuestions(ID), QuestionsCount);

                //Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                //document.Content.SetRange(0, 0);

                var wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 12;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Font.Bold = 1;
                wp.Range.Text      = "МИНОБРНАУКИ РОССИИ";
                wp.Range.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;
                wp.Range.ParagraphFormat.SpaceAfter      = 0;
                wp.Range.ParagraphFormat.Alignment       = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 12;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = "Федеральное государственное бюджетное \r\n образовательное учреждение высшего образования";
                wp.Range.ParagraphFormat.SpaceAfter      = 0;
                wp.Range.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;
                wp.Range.ParagraphFormat.Alignment       = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Font.Bold = 1;
                wp.Range.Text      = "«Ухтинский государственный технический университет» \r\n (УГТУ)";
                wp.Range.ParagraphFormat.SpaceAfter = 12;
                wp.Range.ParagraphFormat.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = "Кафедра вычислительной техники, информационных систем и технологий";
                wp.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = "Дисциплина " + "«" + Subject + "»";
                wp.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = "Направление подготовки 09.03.02";
                wp.Range.ParagraphFormat.SpaceAfter = 0;
                wp.Range.ParagraphFormat.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                var    dt  = DateTime.Now;
                string str = "";
                if (dt.Month <= 6)
                {
                    str = $"{dt.Year - 1} - {dt.Year} учебный год";
                }
                else
                {
                    str = $"{dt.Year} - {dt.Year + 1} учебный год";
                }
                wp.Range.Text = str;
                wp.Range.ParagraphFormat.SpaceAfter = 0;
                wp.Range.ParagraphFormat.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = "Форма обучения дневная";
                wp.Range.ParagraphFormat.SpaceAfter = 0;
                wp.Range.ParagraphFormat.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = "Курс " + course;
                wp.Range.ParagraphFormat.SpaceAfter = 0;
                wp.Range.ParagraphFormat.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = "Семестр " + semester;
                wp.Range.ParagraphFormat.SpaceAfter = 12;
                wp.Range.ParagraphFormat.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                wp.Range.InsertParagraphAfter();


                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Font.Bold = 1;
                wp.Range.Text      = exam.Title;
                wp.Range.ParagraphFormat.SpaceAfter = 24;
                wp.Range.ParagraphFormat.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                for (int j = 0; j < QuestionsCount; j++)
                {
                    wp.Range.Font.Size = 14;
                    wp.Range.Font.Name = "Times New Roman";
                    wp.Range.ParagraphFormat.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    wp.Range.ParagraphFormat.SpaceAfter = 0;
                    wp.Range.ParagraphFormat.Space15();
                    wp.Range.InsertBefore($"{j + 1}. {papers[j]} \r\n");
                }

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = $"Экзаменатор _____________ " + Teacher;
                wp.Range.ParagraphFormat.Alignment   = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                wp.Range.ParagraphFormat.SpaceBefore = 24;
                wp.Range.ParagraphFormat.SpaceAfter  = 0;
                wp.Range.ParagraphFormat.Space15();
                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = $"Зав. кафедрой _____________ " + Cafedral;
                wp.Range.ParagraphFormat.Alignment   = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                wp.Range.ParagraphFormat.SpaceBefore = 0;
                wp.Range.ParagraphFormat.SpaceAfter  = 0;
                wp.Range.ParagraphFormat.Space15();

                wp.Range.InsertParagraphAfter();

                wp = document.Paragraphs.Add(Type.Missing);
                wp.Range.Font.Size = 14;
                wp.Range.Font.Name = "Times New Roman";
                wp.Range.Text      = $"Утверждено на заседании кафедры протокол № ___ от ___________г";
                wp.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                wp.Range.ParagraphFormat.Space15();
                wp.Range.ParagraphFormat.SpaceBefore = 0;
                wp.Range.ParagraphFormat.SpaceAfter  = 0;
                wp.Range.InsertParagraphAfter();
                if (i != PaperCount - 1)
                {
                    wp.Range.InsertBreak();
                }
            }

            object filename = $"{path}\\{Subject} {DateTime.Now.Day}.{DateTime.Now.Month}.{DateTime.Now.Year}.docx";

            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("Экзамен успешно создан!");
        }
Beispiel #15
0
 void _WordApplication_MailMergeDataSourceLoad(Microsoft.Office.Interop.Word.Document Doc)
 {
     DisplayInWatchWindow(countMailMergeDataSourceLoad++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #16
0
 void _WordApplication_MailMergeWizardSendToCustom(Microsoft.Office.Interop.Word.Document Doc)
 {
     DisplayInWatchWindow(countMailMergeWizardSendToCustom++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #17
0
 void _WordApplication_WindowActivate(Microsoft.Office.Interop.Word.Document Doc, Microsoft.Office.Interop.Word.Window Wn)
 {
     DisplayInWatchWindow(countWindowActivate++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #18
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);
        }
 private static void quitterWord(Microsoft.Office.Interop.Word.Application msWord, Microsoft.Office.Interop.Word.Document nvDoc, object missing)
 {
     nvDoc.Close(ref missing, ref missing, ref missing);
     msWord.Quit(ref missing, ref missing, ref missing);
 }
Beispiel #20
0
 void _WordApplication_DocumentBeforeClose(Microsoft.Office.Interop.Word.Document Doc, ref bool Cancel)
 {
     DisplayInWatchWindow(countDocumentBeforeClose++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #21
0
 void _WordApplication_DocumentOpen(Microsoft.Office.Interop.Word.Document Doc)
 {
     DisplayInWatchWindow(countDocumentOpen++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #22
0
 void _WordApplication_DocumentSync(Microsoft.Office.Interop.Word.Document Doc, Microsoft.Office.Core.MsoSyncEventType SyncEventType)
 {
     DisplayInWatchWindow(countDocumentSync++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #23
0
 void _WordApplication_EPostageInsertEx(Microsoft.Office.Interop.Word.Document Doc, int cpDeliveryAddrStart, int cpDeliveryAddrEnd, int cpReturnAddrStart, int cpReturnAddrEnd, int xaWidth, int yaHeight, string bstrPrinterName, string bstrPaperFeed, bool fPrint, ref bool fCancel)
 {
     DisplayInWatchWindow(countEPostageInsertEx++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #24
0
 void _WordApplication_EPostagePropertyDialog(Microsoft.Office.Interop.Word.Document Doc)
 {
     DisplayInWatchWindow(countEPostagePropertyDialog++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #25
0
 void _WordApplication_MailMergeAfterMerge(Microsoft.Office.Interop.Word.Document Doc, Microsoft.Office.Interop.Word.Document DocResult)
 {
     DisplayInWatchWindow(countMailMergeAfterMerge++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #26
0
 void _WordApplication_MailMergeBeforeMerge(Microsoft.Office.Interop.Word.Document Doc, int StartRecord, int EndRecord, ref bool Cancel)
 {
     DisplayInWatchWindow(countMailMergeBeforeMerg++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #27
0
        private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            try
            {
                var fileInfo = new System.IO.FileInfo(openFileDialog.FileName);

                // If the file is bigger than 30 mb
                if (fileInfo.Length * (9.35 * Math.Pow(10, -7)) > 30)
                    MessageBox.Show("This is a relatively large file.  Please allow load times in between 1 - 2 minutes.",
                        "BIG FILE", MessageBoxButtons.OK, MessageBoxIcon.Information);

                loadedDoc = wordApp.Documents.Open(openFileDialog.FileName);
                tmpDoc = wordApp.Documents.Add();

                loadedDoc.Content.Copy();
                tmpDoc.Content.Paste();

                hasLoaded = true;

                Size = new Size(Screen.GetWorkingArea(Bounds).Width,
                    Screen.GetWorkingArea(Bounds).Height);
                Location = new Point(0, 0);

                lblLoadedFile.Text    = "Loaded Doc: " + loadedDoc.Path + "\\" + loadedDoc.Name;
                stslblFileLoaded.Text = "File Loaded: True";
                pgNums                = loadedDoc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages);
                lblPagesInDoc.Text    = "Pages in Document: " + pgNums.ToString();

                pdfReader.Visible = true;

                SaveTempPDF();
                pdfReader.Refresh();

                System.Media.SystemSounds.Beep.Play();
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                PrintErrorMessage("ERROR! The document failed to load.  Either" +
                    " the document is in use or you don't have permission to open it.", ex);
            }
            catch (Exception ex)
            {
                PrintErrorMessage("ERROR! Could not open the file.", ex);
            }
        }
Beispiel #28
0
        private void button3_Click(object sender, EventArgs e)
        {
            object filename1     = Application.StartupPath + "\\bin\\" + Global.templateName;
            string ImagePath     = pictureBox1.ImageLocation;
            string strKey        = "8.4.1空载温度曲线图";
            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;
                }
            }

            string ImagePath1     = pictureBox2.ImageLocation;
            string strKey1        = "8.4.3满载温度曲线图";
            object MissingValue1  = Type.Missing;
            bool   isFindSealLoc1 = false;

            Microsoft.Office.Interop.Word.Application wp1 = null;
            Microsoft.Office.Interop.Word.Document    wd1 = null;
            try
            {
                wp1 = new Microsoft.Office.Interop.Word.Application();
                wd1 = wp1.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);
                wp1.Selection.Find.ClearFormatting();
                wp1.Selection.Find.Replacement.ClearFormatting();
                wp1.Selection.Find.Text = strKey1;
                object objReplace1 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp1.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref objReplace1, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor1           = wp1.Selection.Range;
                    object LinkToFile1       = false;
                    object SaveWithDocument1 = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape1 = wp1.Selection.InlineShapes.AddPicture(
                        ImagePath1, ref LinkToFile1, ref SaveWithDocument1, ref Anchor1);
                    Inlineshape1.Select();
                    Microsoft.Office.Interop.Word.Shape shape1 = Inlineshape1.ConvertToShape();
                    shape1.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc1 = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd1 != null)
                {
                    wd1.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd1);
                    wd1 = null;
                }
                if (wp1 != null)
                {
                    wp1.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp1);
                    wp1 = null;
                }
            }

            {
                string ImagePath2     = pictureBox3.ImageLocation;
                string strKey2        = "8.4.5热穿透测试温度曲线图";
                object MissingValue2  = Type.Missing;
                bool   isFindSealLoc2 = false;
                Microsoft.Office.Interop.Word.Application wp2 = null;
                Microsoft.Office.Interop.Word.Document    wd2 = null;
                try
                {
                    wp2 = new Microsoft.Office.Interop.Word.Application();
                    wd2 = wp2.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);
                    wp2.Selection.Find.ClearFormatting();
                    wp2.Selection.Find.Replacement.ClearFormatting();
                    wp2.Selection.Find.Text = strKey2;
                    object objReplace1 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                    if (wp2.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                                   ref MissingValue, ref MissingValue, ref MissingValue,
                                                   ref MissingValue, ref MissingValue, ref MissingValue,
                                                   ref MissingValue, ref objReplace1, ref MissingValue,
                                                   ref MissingValue, ref MissingValue, ref MissingValue))
                    {
                        object Anchor1           = wp2.Selection.Range;
                        object LinkToFile1       = false;
                        object SaveWithDocument1 = true;
                        Microsoft.Office.Interop.Word.InlineShape Inlineshape1 = wp2.Selection.InlineShapes.AddPicture(
                            ImagePath2, ref LinkToFile1, ref SaveWithDocument1, ref Anchor1);
                        Inlineshape1.Select();
                        Microsoft.Office.Interop.Word.Shape shape1 = Inlineshape1.ConvertToShape();
                        shape1.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                        isFindSealLoc2 = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    if (wd2 != null)
                    {
                        wd2.Close();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(wd2);
                        wd2 = null;
                    }
                    if (wp2 != null)
                    {
                        wp2.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(wp2);
                        wp2 = null;
                    }
                }
            }


            string filename = Application.StartupPath.ToString() + "\\bin\\" + Global.templateName + ".doc";

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

            Spire.Doc.Fields.TextBox      textBox   = document.TextBoxes[1];
            Spire.Doc.Documents.Paragraph paragraph = textBox.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange = paragraph.AppendText(textBox1.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox111 = document.TextBoxes[2];
            Spire.Doc.Documents.Paragraph paragraph1 = textBox111.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange1 = paragraph1.AppendText(textBox2.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox1111 = document.TextBoxes[3];
            Spire.Doc.Documents.Paragraph paragraph11 = textBox1111.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange11 = paragraph11.AppendText(textBox3.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            MessageBox.Show("导入成功!");

            this.Close();
        }
Beispiel #29
0
        public void DoSearchAndReplaceInWord(string argFileName, int argFlatId)
        {
            DataTable dt = new DataTable();

            dt = m_lTBL.GetFlatDetails(argFlatId);

            Microsoft.Office.Interop.Word.Application oword = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    odoc  = new Microsoft.Office.Interop.Word.Document();

            // Define an object to pass to the API for missing parameters
            object missing = System.Type.Missing;

            try
            {
                // Everything that goes to the interop must be an object

                oword.Documents.Open(argFileName);

                odoc.Activate();
                oword.Visible = false;

                odoc = oword.ActiveDocument;

                Dictionary <string, string> findandreplace = new Dictionary <string, string>();
                findandreplace.Add("<DocumentDate>", m_DocumentDate.ToString("dd-MMM-yyyy"));
                findandreplace.Add("<Name>", dt.Rows[0]["BuyerName"].ToString());
                findandreplace.Add("<FatherName>", dt.Rows[0]["FatherName"].ToString());
                findandreplace.Add("<Age>", dt.Rows[0]["Age"].ToString());
                findandreplace.Add("<Address1>", dt.Rows[0]["Address1"].ToString());
                findandreplace.Add("<Address2>", dt.Rows[0]["Address2"].ToString());
                findandreplace.Add("<City>", dt.Rows[0]["City"].ToString());
                findandreplace.Add("<State>", dt.Rows[0]["State"].ToString());
                findandreplace.Add("<Country>", dt.Rows[0]["CountryName"].ToString());
                findandreplace.Add("<PinCode>", dt.Rows[0]["PinCode"].ToString());
                findandreplace.Add("<ChequeNo>", dt.Rows[0]["ChequeNo"].ToString());
                findandreplace.Add("<PANNo>", dt.Rows[0]["PanNo"].ToString());
                findandreplace.Add("<FlatNo>", dt.Rows[0]["FlatNo"].ToString());
                findandreplace.Add("<Block>", dt.Rows[0]["BlockName"].ToString());
                findandreplace.Add("<Level>", dt.Rows[0]["LevelName"].ToString());
                findandreplace.Add("<UDS>", dt.Rows[0]["USLand"].ToString());
                findandreplace.Add("<Area>", dt.Rows[0]["Area"].ToString());
                findandreplace.Add("<FinalizationDate>", Convert.ToDateTime(dt.Rows[0]["FinalizationDate"]).ToString("dd-MMM-yyyy"));
                findandreplace.Add("<SystemDate>", Convert.ToDateTime(dt.Rows[0]["SystemDate"]).ToString("dd-MMM-yyyy"));
                findandreplace.Add("<CostCentreName>", dt.Rows[0]["CostCentreName"].ToString());
                findandreplace.Add("<CCAddress1>", dt.Rows[0]["CCAddress1"].ToString());
                findandreplace.Add("<CCAddress2>", dt.Rows[0]["CCAddress2"].ToString());
                findandreplace.Add("<CCCity>", dt.Rows[0]["CCCity"].ToString());
                findandreplace.Add("<CCPincode>", dt.Rows[0]["CCPincode"].ToString());
                findandreplace.Add("<CompanyName>", dt.Rows[0]["CompanyName"].ToString());
                findandreplace.Add("<CompanyAddress>", dt.Rows[0]["CompanyAddress"].ToString());
                findandreplace.Add("<CompanyPhone>", dt.Rows[0]["CompanyPhone"].ToString());
                findandreplace.Add("<CoApplicantName>", dt.Rows[0]["CoApplicantName"].ToString());
                findandreplace.Add("<CoApplicantAge>", dt.Rows[0]["CoApplicantAge"].ToString());
                findandreplace.Add("<CoApplicantAddress1>", dt.Rows[0]["CoApplicantAddress1"].ToString());
                findandreplace.Add("<CoApplicantAddress2>", dt.Rows[0]["CoApplicantAddress2"].ToString());
                findandreplace.Add("<CoApplicantRelationshipWithBuyer>", "");
                findandreplace.Add("<CoApplicantPANNo>", dt.Rows[0]["CoApplicantPANNo"].ToString());
                findandreplace.Add("<BankName>", dt.Rows[0]["BankName"].ToString());
                findandreplace.Add("<BankBranch>", dt.Rows[0]["BankBranch"].ToString());
                findandreplace.Add("<BankAddress>", dt.Rows[0]["BankAddress"].ToString());
                findandreplace.Add("<BankContactPerson>", dt.Rows[0]["BankContactPerson"].ToString());
                findandreplace.Add("<BankLoanAccNo>", dt.Rows[0]["BankLoanAccNo"].ToString());
                findandreplace.Add("<MobileNo>", dt.Rows[0]["MobileNo"].ToString());
                findandreplace.Add("<Email>", dt.Rows[0]["Email"].ToString());
                findandreplace.Add("<UDS(in words)>", dt.Rows[0]["UDS(in words)"].ToString());
                findandreplace.Add("<FlatType>", dt.Rows[0]["FlatType"].ToString());
                findandreplace.Add("<Rate>", dt.Rows[0]["Rate"].ToString());
                findandreplace.Add("<Rate(in words)>", dt.Rows[0]["Rate(in words)"].ToString());
                findandreplace.Add("<CarParkType>", dt.Rows[0]["CarParkType"].ToString());
                findandreplace.Add("<BasicCost>", dt.Rows[0]["BasicCost"].ToString());
                findandreplace.Add("<BasicCost(in words)>", dt.Rows[0]["BasicCost(in words)"].ToString());
                findandreplace.Add("<FlatCost>", dt.Rows[0]["FlatCost"].ToString());
                findandreplace.Add("<FlatCost(in words)>", dt.Rows[0]["FlatCost(in words)"].ToString());
                findandreplace.Add("<LandCost>", dt.Rows[0]["LandCost"].ToString());
                findandreplace.Add("<LandCost(in words)>", dt.Rows[0]["LandCost(in words)"].ToString());
                findandreplace.Add("<Advance>", dt.Rows[0]["Advance"].ToString());
                findandreplace.Add("<Advance(in words)>", dt.Rows[0]["Advance(in words)"].ToString());
                findandreplace.Add("<SaleAgreementLandValue>", dt.Rows[0]["SaleAgreementLandValue"].ToString());
                findandreplace.Add("<SaleAgreementLandValue(in words)>", dt.Rows[0]["SaleAgreementLandValue(in words)"].ToString());
                findandreplace.Add("<OtherCostAmt>", dt.Rows[0]["OtherCostAmt"].ToString());
                findandreplace.Add("<QualifierAmount>", dt.Rows[0]["QualifierAmount"].ToString());
                findandreplace.Add("<RegistrationValue>", dt.Rows[0]["RegistrationValue"].ToString());
                findandreplace.Add("<MaintenanceCharge>", dt.Rows[0]["MaintenanceCharge"].ToString());
                findandreplace.Add("<MaintenanceCharge(in words)>", dt.Rows[0]["MaintenanceCharge(in words)"].ToString());
                findandreplace.Add("<CorpusFund>", dt.Rows[0]["CorpusFund"].ToString());
                findandreplace.Add("<CorpusFund(in words)>", dt.Rows[0]["CorpusFund(in words)"].ToString());
                findandreplace.Add("<LegalCharges>", dt.Rows[0]["LegalCharges"].ToString());
                findandreplace.Add("<LegalCharges(in words)>", dt.Rows[0]["LegalCharges(in words)"].ToString());
                findandreplace.Add("<ReceiptDate>", dt.Rows[0]["ReceiptDate"].ToString());
                findandreplace.Add("<Amount>", dt.Rows[0]["Amount"].ToString());
                findandreplace.Add("<Amount(in words)>", dt.Rows[0]["Amount(in words)"].ToString());
                findandreplace.Add("<NetAmount>", dt.Rows[0]["NetAmount"].ToString());
                findandreplace.Add("<NetAmount(in words)>", dt.Rows[0]["NetAmount(in words)"].ToString());
                findandreplace.Add("<PaidAmount>", dt.Rows[0]["PaidAmount"].ToString());
                findandreplace.Add("<PaidAmount(in words)>", dt.Rows[0]["PaidAmount(in words)"].ToString());
                findandreplace.Add("<BalanceAmount>", dt.Rows[0]["BalanceAmount"].ToString());
                findandreplace.Add("<BalanceAmount(in words)>", dt.Rows[0]["BalanceAmount(in words)"].ToString());
                findandreplace.Add("<DocumentDay>", m_DocumentDate.Day.ToString());
                findandreplace.Add("<DocumentMonth>", System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(m_DocumentDate.Month).ToString());

                foreach (KeyValuePair <string, string> pair in findandreplace)
                {
                    foreach (Microsoft.Office.Interop.Word.Range tmpRange in odoc.StoryRanges)
                    {
                        object findme        = pair.Key;
                        object replacewithme = pair.Value;

                        tmpRange.Find.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;

                        object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

                        tmpRange.Find.Execute(ref findme, ref missing, ref missing,
                                              ref missing, ref missing, ref missing, ref missing,
                                              ref missing, ref missing, ref replacewithme, ref replaceAll,
                                              ref missing, ref missing, ref missing, ref missing);
                    }
                }
                //odoc.Content.Find.Execute(FindText: "<Name>", ReplaceWith: dt.Rows[0]["BuyerName"].ToString());


                oword.Documents.Save();
                oword.Documents.Close();

                //odoc.Close(ref missing, ref missing, ref missing);
                oword.Application.Quit(ref missing, ref missing, ref missing);
            }
            catch
            {
                odoc.Close(ref missing, ref missing, ref missing);
                oword.Application.Quit(ref missing, ref missing, ref missing);
            }
        }
Beispiel #30
0
        public void s()
        {
            try
            {
                var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
                //@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
                var templateName = direc + "大型精密仪器设备论证一览表_模板.doc";
                Microsoft.Office.Interop.Word.ApplicationClass wordApp;
                Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
                object Obj_FileName = templateName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;
                wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Object Nothing = System.Reflection.Missing.Value;
                wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                wordDocument.Activate();

                Microsoft.Office.Interop.Word.Table wordTable = wordDocument.Tables[1];

                var Iid = Request.GetInt("tastItemID");

                var memI = Database.ConstructTaskItems.SingleOrDefault(cti => cti.ID == Iid);
                wordDocument.Bookmarks.get_Item("Unit").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.College.Name;
                wordDocument.Bookmarks.get_Item("DeviceManager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Member.Name;
                wordDocument.Bookmarks.get_Item("Manager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Manager.Name;
                wordDocument.Bookmarks.get_Item("DeviceNumber").Range.Text = memI.ConstructPlanItem.DeviceNumber;

                wordTable.Cell(1, 3).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
                wordTable.Cell(2, 3).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.EnglishName;
                wordTable.Cell(3, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.Quantity.ToString();
                wordTable.Cell(3, 4).Range.Text = (memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice / 100).ToString() + "元";
                wordTable.Cell(3, 6).Range.Text = ((memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice * memI.ConstructPlanItem.MemberApplyItem.Quantity) / 100).ToString() + "元";

                wordTable.Cell(5, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.NecessityAnalysis;
                wordTable.Cell(12, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.MainSpec;
                wordTable.Cell(27, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.AccessorySpec;

                wordTable.Cell(1, 6).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Environment;
                wordTable.Cell(7, 9).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Consumables;
                wordTable.Cell(9, 9).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Power;

                var deviceMaths = Database.DeviceMatchs.Where(dm => dm.ApplyDevice == memI.ConstructPlanItem.MemberApplyItem.ApplyDevice);
                var temp = 0;
                //设备选型
                if (deviceMaths.Count() > 0 && deviceMaths.Count() <= 4)
                    foreach (var item in deviceMaths)
                    {
                        if (item != null)
                        {
                            wordTable.Cell(2, 5 + temp).Range.Text = item.MarketDevice.MarketDeviceName;
                            wordTable.Cell(4, 8 + temp).Range.Text = item.MarketDevice.Model;

                            var deviceSupplier = Database.DeviceSuppliers.Where(ds => ds.DeviceMatch == item).FirstOrDefault();
                            if (deviceSupplier != null)
                            {
                                wordTable.Cell(6, 4 + temp).Range.Text = deviceSupplier.Supplier.Name;
                                wordTable.Cell(7, 4 + temp).Range.Text = deviceSupplier.ContactPerson + ":" + deviceSupplier.ContactPhone;
                                wordTable.Cell(8, 4 + temp).Range.Text = (deviceSupplier.Price / 100).ToString() + "元";
                                wordTable.Cell(9, 4 + temp).Range.Text = deviceSupplier.PriceSource == 0 ? "供应商" : "网络";
                            }
                        }
                        temp += 1;
                    }
                var extrals = Database.DeviceExtramurals.Where(de => de.ApplyDevice == memI.ConstructPlanItem.MemberApplyItem.ApplyDevice).ToList();
                if (extrals.Count() > 0 && extrals.Count() <= 4)
                {
                    if (extrals.Count() >= 1)
                    {
                        wordTable.Cell(11, 4).Range.Text = extrals[0].Brand.ToString();
                        wordTable.Cell(11, 5).Range.Text = extrals[0].WorkUnit.ToString();
                        wordTable.Cell(11, 6).Range.Text = extrals[0].UserName;
                        wordTable.Cell(11, 7).Range.Text = extrals[0].BuyTime.Value.ToShortDateString();
                        wordTable.Cell(11, 8).Range.Text = (extrals[0].UnitPrice / 100).ToString() + "元";
                        for (int i = 1; i < extrals.Count(); i++)
                        {
                            wordTable.Cell(11 + i, 4).Range.Text = extrals[i].Brand.ToString();
                            wordTable.Cell(11 + i, 5).Range.Text = extrals[i].WorkUnit.ToString();
                            wordTable.Cell(11 + i, 6).Range.Text = extrals[i].UserName;
                            wordTable.Cell(11 + i, 7).Range.Text = extrals[i].BuyTime.Value.ToShortDateString();
                            wordTable.Cell(11 + i, 8).Range.Text = (extrals[i].UnitPrice / 100).ToString() + "元";
                        }
                    }
                }

                SaveDocument(wordDocument, wordApp, direc + "大型精密仪器设备论证一览表.doc");

                downLoad(direc + "大型精密仪器设备论证一览表.doc", "大型精密仪器设备论证一览表.doc");

                var downLoadInfo = string.Format("国资处:{0},下载设备:{1} 的大型设备论证报告", User.Name, memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName);
                BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
            }
            catch (System.Exception ex)
            {
                new PackedException("导出大型精密仪器论证一览表", ex).Hanldle();
            }
        }
Beispiel #31
0
        public void uploadFiles(C1FlexGrid poGrid)
        {
            for (int i = 1; i < poGrid.Rows.Count; i++)
            {
                try
                {
                    object[] _progressCount = new object[2];
                    _progressCount[0] = poGrid.GetDataDisplay(i, "Title");

                    //update database
                    loMySqlTransaction = GlobalVariables.goMySqlConnection.BeginTransaction();

                    //para ni sa loading text -- file to db
                    _progressCount[1] = 1;
                    FileUpload.GetType().GetMethod("reportProgress").Invoke(FileUpload, _progressCount);
                    //^para sa loading text

                    loDocument.Title = poGrid.GetDataDisplay(i, "Title");
                    loDocument.Path = GlobalVariables.goFileServer;
                    loDocument.Newspaper = poGrid.GetDataDisplay(i, "Newspaper");
                    loDocument.Doctype = poGrid.GetDataDisplay(i, "Doc Type");
                    loDocument.Section = poGrid.GetDataDisplay(i, "Section");
                    loDocument.PublishedDate = poGrid.GetDataDisplay(i, "Published Date");

                    //generate preview
                    string _preview = "";
                    switch (loDocument.Doctype)
                    {
                        case ".rtf":
                        case ".doc":
                            //add preview
                            try
                            {
                                object readOnly = false;
                                object isVisible = false;
                                object _missing = System.Reflection.Missing.Value;
                                _oApplication = new Microsoft.Office.Interop.Word.Application();
                                //_oDocument = _oApplication.Documents.Open(poGrid.GetDataDisplay(i, "Local Path"));
                                object _path = @"" + poGrid.GetDataDisplay(i, "Local Path").ToString();
                                _oDocument = _oApplication.Documents.Open(ref _path, 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);
                                _preview = GlobalFunctions.addSlashes(_oDocument.Content.Text);
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            {
                                _oDocument.Close();
                                _oApplication.Quit();
                            }
                            break;

                        case ".txt":
                            //add preview
                            string _textPreview = File.ReadAllText(poGrid.GetDataDisplay(i, "Local Path"));
                            _preview = GlobalFunctions.addSlashes(_textPreview);
                            break;
                    }

                    loDocument.Preview = _preview;

                    string _docId = loDocument.insert(ref loMySqlTransaction);

                    char[] _separator = { ',' };

                    //para ni sa loading text -- authors
                    _progressCount[1] = 2;
                    FileUpload.GetType().GetMethod("reportProgress").Invoke(FileUpload, _progressCount);
                    //^para sa loading text

                    //add authors
                    string[] _authors = poGrid.GetDataDisplay(i, "Authors").Split(_separator, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string _str in _authors)
                    {
                        loDocAuthor.AuthorId = _str;
                        loDocAuthor.DocumentId = _docId;
                        loDocAuthor.insert(ref loMySqlTransaction);
                    }

                    //para ni sa loading text -- editors
                    _progressCount[1] = 3;
                    FileUpload.GetType().GetMethod("reportProgress").Invoke(FileUpload, _progressCount);
                    //^para sa loading text

                    //add editors
                    string[] _editors = poGrid.GetDataDisplay(i, "Editors").Split(_separator, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string _str in _editors)
                    {
                        loDocEditor.EditorId = _str;
                        loDocEditor.DocumentId = _docId;
                        loDocEditor.insert(ref loMySqlTransaction);
                    }

                    //para ni sa loading text -- tags
                    _progressCount[1] = 4;
                    FileUpload.GetType().GetMethod("reportProgress").Invoke(FileUpload, _progressCount);
                    //^para sa loading text

                    //add tags
                    string[] _tags = poGrid.GetDataDisplay(i, "Tags").Split(_separator, StringSplitOptions.RemoveEmptyEntries);

                    IList<string> _tagList = GlobalFunctions.removeRedundancy(_tags);

                    foreach (string _str in _tagList)
                    {
                        loDocTag.Tag = _str.ToLower().Trim();
                        loDocTag.DocumentId = _docId;
                        try
                        {
                            loDocTag.insert(ref loMySqlTransaction);
                        }
                        catch { }
                    }

                    //para ni sa loading text -- hidden tags
                    _progressCount[1] = 5;
                    FileUpload.GetType().GetMethod("reportProgress").Invoke(FileUpload, _progressCount);
                    //^para sa loading text

                    //add hidden tags
                    IList<string> _hiddenTagList = new List<string>();
                    //start with the dates
                    DateTime _publishedDate = DateTime.Parse(poGrid.GetDataDisplay(i, "Published Date"));
                    _hiddenTagList.Add(_publishedDate.ToString("yyyy")); //year
                    _hiddenTagList.Add(_publishedDate.ToString("MMM")); //short month name
                    _hiddenTagList.Add(_publishedDate.ToString("MMMM")); //month name
                    _hiddenTagList.Add(_publishedDate.ToShortDateString());
                    _hiddenTagList.Add(_publishedDate.ToLongDateString());
                    _hiddenTagList.Add(_publishedDate.ToString("yyyy-MM-dd"));
                    _hiddenTagList.Add(_publishedDate.ToString("dd-MM-yy"));

                    //title
                    char[] _whiteSpaceSeparator = { ' ' };
                    string[] _splitTitle = loDocument.Title.Split(_whiteSpaceSeparator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string _str in _splitTitle)
                    {
                        _hiddenTagList.Add(_str);
                    }

                    //authors
                    string[] _authorNames = poGrid.GetDataDisplay(i, "Names").Split(_separator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string _str in _authorNames)
                    {
                        string[] _nameSplit = _str.Split(_whiteSpaceSeparator, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string _str2 in _nameSplit)
                        {
                            _hiddenTagList.Add(_str2);
                        }
                    }

                    //editors
                    string[] _editorInitials = poGrid.GetDataDisplay(i, "Initials").Split(_separator, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string _str in _editorInitials)
                    {
                        string[] _initialSplit = _str.Split(_whiteSpaceSeparator, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string _str2 in _initialSplit)
                        {
                            _hiddenTagList.Add(_str2);
                        }
                    }

                    //also add the newspaper and section as tags
                    _hiddenTagList.Add(loDocument.Newspaper);
                    _hiddenTagList.Add(poGrid.GetDataDisplay(i, "Section Name"));

                    //remove repetitive entries
                    IList<string> _noRepeatHiddenTags = GlobalFunctions.removeRedundancy(_hiddenTagList.ToArray<string>());

                    //save to database like a baws
                    foreach (string _str in _noRepeatHiddenTags)
                    {
                        if (_str != "" || _str != null)
                        {
                            loDocTag.Tag = _str.ToLower().Trim();
                            loDocTag.DocumentId = _docId;
                            try
                            {
                                loDocTag.insert(ref loMySqlTransaction);
                            }
                            catch { }
                        }
                    }

                    //para ni sa loading text -- first 100 words
                    _progressCount[1] = 6;
                    FileUpload.GetType().GetMethod("reportProgress").Invoke(FileUpload, _progressCount);
                    //^para sa loading text

                    //get the document contents, but check for it's doctype first though!
                    switch (loDocument.Doctype)
                    {
                        case ".rtf":
                        case ".doc":
                            string _docContents = "";
                            _oApplication = new Microsoft.Office.Interop.Word.Application();
                            _oDocument = _oApplication.Documents.Open(poGrid.GetDataDisplay(i, "Local Path"));

                            //loop throught the first 100 words

                            int _numberOfWords = 0;

                            if (_oDocument.Words.Count >= 100)
                            {
                                _numberOfWords = 100;
                            }
                            else
                            {
                                _numberOfWords = _oDocument.Words.Count;
                            }

                            for (int _wordCount = 1; _wordCount <= _numberOfWords; _wordCount++)
                            {
                                _docContents += _oDocument.Words[_wordCount].Text;
                            }

                            string[] _docContentsArr = _docContents.Split(_whiteSpaceSeparator, StringSplitOptions.RemoveEmptyEntries);

                            IList<string> _docContentsList = GlobalFunctions.removeRedundancy(_docContentsArr);

                            foreach (string _str in _docContentsList)
                            {
                                if (_str.Length > 1)
                                {
                                    loDocTag.Tag = _str.ToLower().Trim();
                                    loDocTag.DocumentId = _docId;
                                    try
                                    {
                                        loDocTag.insert(ref loMySqlTransaction);
                                    }
                                    catch { }
                                }
                            }
                            break;
                        case ".txt":
                            string _textContents = File.ReadAllText(poGrid.GetDataDisplay(i, "Local Path"));
                            string[] _textContentsArr = _textContents.Split(_whiteSpaceSeparator, StringSplitOptions.RemoveEmptyEntries);

                            IList<string> _textContentsList = GlobalFunctions.removeRedundancy(_textContentsArr);
                            foreach (string _str in _textContentsList)
                            {
                                if (_str.Length > 1)
                                {
                                    loDocTag.Tag = _str.ToLower().Trim();
                                    loDocTag.DocumentId = _docId;
                                    try
                                    {
                                        loDocTag.insert(ref loMySqlTransaction);
                                    }
                                    catch { }
                                }
                            }
                            break;
                    }

                    //maypa ang mysqltransaction, mu commit!
                    loMySqlTransaction.Commit();

                    //copy file to server
                    File.Copy(@"" + poGrid.GetDataDisplay(i, "Local Path"), @"" + GlobalVariables.goFileServer + @"\" + _docId + loDocument.Doctype);

                    //para ni sa loading text -- first 100 words
                    _progressCount[1] = 7;
                    FileUpload.GetType().GetMethod("reportProgress").Invoke(FileUpload, _progressCount);
                    //^para sa loading text
                }
                catch (Exception)
                {
                    loMySqlTransaction.Rollback();
                    throw;
                }
                finally
                {
                    if (_oDocument != null)
                    {
                        _oDocument.Close();
                        _oApplication.Quit();
                    }

                    GC.Collect();
                }
            }
        }
Beispiel #32
0
        private static void _printFile(string file, int count = 1)
        {
            string format = file.Split('.').Last().ToLower();

            switch (_avaliableFormats.Where(f => f.FileFormat == format).Select(f => f.PrintAs).First())
            {
            case ePrintAs.pdf:
            case ePrintAs.rtf:
            {
                #region printing pdf

                for (int i = 0; i < count; i++)
                {
                    using (Process p = new Process())
                    {
                        p.StartInfo = new ProcessStartInfo()
                        {
                            Verb           = "print",
                            FileName       = file,
                            CreateNoWindow = true,
                            WindowStyle    = ProcessWindowStyle.Hidden,
                        };
                        p.Start();
                        p.WaitForInputIdle();        //System.Threading.Thread.Sleep(3000); //if (false == p.CloseMainWindow()) //p.Kill();
                    }
                }

                #endregion
                break;
            }

            case ePrintAs.docx:
            case ePrintAs.doc:
            {
                #region print docx

                for (int i = 0; i < count; i++)
                {
                    Microsoft.Office.Interop.Word.Application wordInstance = new Microsoft.Office.Interop.Word.Application();
                    wordInstance.Visible = false;
                    object fileObject = file;
                    object oMissing   = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Word.Document doc = wordInstance.Documents.Open(ref fileObject, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                    doc.Activate();
                    doc.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
                    doc.Close(ref oMissing, ref oMissing, ref oMissing);
                    wordInstance.Quit(ref oMissing, ref oMissing, ref oMissing);
                    doc          = null;
                    wordInstance = null;
                }

                break;
                #endregion
            }

            case ePrintAs.txt:
            {
                #region txt
                Font   printFont = new Font("Arial", 10);
                string content   = File.ReadAllText(file);
                // for (int i = 0; i < count; i++)
                {
                    try
                    {
                        PrintDocument pd = new PrintDocument();
                        pd.PrintPage += (sender, print_event) =>
                        {
                            print_event.Graphics.DrawString(content, printFont, Brushes.Black,
                                                            print_event.MarginBounds.Left, 0, new StringFormat());
                        };
                        pd.PrinterSettings.Copies = (short)count;
                        pd.Print();
                    }
                    catch { }
                }
                break;
                #endregion
            }
            }

            if (Configs.Logging)
            {
                file.Put(count);
            }

            GC.Collect();
        }
        private bool Save_FileDoc1()
        {
            try
            {
                var application = new Microsoft.Office.Interop.Word.Application();
                var document = new Microsoft.Office.Interop.Word.Document();
                document = application.Documents.Add(Template: Server.MapPath("/File/Template/templateHDDV.doc"));

                application.Visible = true;

                foreach (Microsoft.Office.Interop.Word.Field field in document.Fields)
                {
                    if (field.Code.Text.Contains("MerPos01"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPos02"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPos03"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPos04"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPos05"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerName"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerAddress"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPhone"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerTaxCode"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerEmail"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerRepresent"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerPosition"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerBeginM"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerDeadlineInt"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerDeadlineString"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerCostTitle01"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerCostTitle02"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                    else if (field.Code.Text.Contains("MerCostDetail"))
                    {
                        field.Select();
                        application.Selection.TypeText("text1");
                    }
                }
                document.SaveAs(FileName: String.Format(Server.MapPath("/File/WordFile/HopDongDVKeToan_Code_{0}.doc"), 123));

                document.Close();
                application.Quit();

                return true;
            }
            catch (Exception) { throw; return false; }
        }
Beispiel #34
0
 void _WordApplication_MailMergeWizardStateChange(Microsoft.Office.Interop.Word.Document Doc, ref int FromState, ref int ToState, ref bool Handled)
 {
     DisplayInWatchWindow(countMailMergeWizardStateChange++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
Beispiel #35
0
        private void fillDocument(string _filename, List<ReplacePattern> replacePatterns)
        {
            // Генерируем случайную строку из символов латиницы, например
            string templateFileName = _filename;
            string randomFilePathName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            _filename = Path.Combine(randomFilePathName, Path.GetFileName(_filename));
            if (!Directory.Exists(randomFilePathName))
            {
                Directory.CreateDirectory(randomFilePathName);
            }
            File.Copy(templateFileName, _filename);

            Object wMissing = System.Reflection.Missing.Value;
            Object wTrue = true;
            Object wFalse = false;

            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();
            //Работа с документом - Договор
            Object filename = _filename;
            Object confirmConversions = true;
            Object readOnly = false;
            Object addToRecentFiles = true;
            Object revert = false;
            Object passwordDocument = Type.Missing;
            Object passwordTemplate = 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;
            wordApp.Documents.Open(ref filename, 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);

            wordApp.Visible = true;

            wordDoc = wordApp.Documents.Add(ref filename, ref wMissing, ref wTrue, ref wFalse);

            replacePatterns.ForEach(x => wordSearchReplace(x.replaced, x.replacing, ref wordApp, x.how));

            wordApp.Visible = true;
        }
Beispiel #36
0
        public void Export_Data_To_Word(DataGridView DGV)
        {
            if (DGV.Rows.Count == 0)
            {
                return;
            }

            int RowCount    = DGV.Rows.Count;
            int ColumnCount = DGV.Columns.Count;

            Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

            //add rows
            int r = 0;

            for (int c = 0; c <= ColumnCount - 1; c++)
            {
                for (r = 0; r <= RowCount - 1; r++)
                {
                    DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
                }
            }

            Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();
            wordDoc.Application.Visible = true;

            //горизонтальная ориентация страницы
            wordDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;


            dynamic oRange = wordDoc.Content.Application.Selection.Range;
            string  tmp    = "";

            for (r = 0; r <= RowCount - 1; r++)
            {
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    tmp = tmp + DataArray[r, c] + "\t";
                }
            }

            //table format
            oRange.Text = tmp;

            object Separator       = Microsoft.Office.Interop.Word.WdTableFieldSeparator.wdSeparateByTabs;
            object ApplyBorders    = true;
            object AutoFit         = true;
            object AutoFitBehavior = Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent;

            oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
                                  Type.Missing, Type.Missing, ref ApplyBorders,
                                  Type.Missing, Type.Missing, Type.Missing,
                                  Type.Missing, Type.Missing, Type.Missing,
                                  Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);

            oRange.Select();

            wordDoc.Application.Selection.Tables[1].Select();
            wordDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
            wordDoc.Application.Selection.Tables[1].Rows.Alignment             = 0;
            wordDoc.Application.Selection.Tables[1].Rows[1].Select();
            wordDoc.Application.Selection.InsertRowsAbove(1);
            wordDoc.Application.Selection.Tables[1].Rows[1].Select();

            //стили
            wordDoc.Application.Selection.Tables[1].Rows[1].Range.Bold      = 1;
            wordDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma";
            wordDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

            //добавляем заголовки для таблицы
            for (int c = 0; c <= ColumnCount - 1; c++)
            {
                wordDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
            }

            wordDoc.Application.Selection.Tables[1].Rows[1].Select();
            wordDoc.Application.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            foreach (Microsoft.Office.Interop.Word.Section section in wordDoc.Application.ActiveDocument.Sections)
            {
                Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                headerRange.Text      = "Кредитный калькулятор";
                headerRange.Font.Size = 16;
                headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            }
        }
Beispiel #37
0
 void _WordApplication_MailMergeDataSourceValidate(Microsoft.Office.Interop.Word.Document Doc, ref bool Handled)
 {
     DisplayInWatchWindow(countMailMergeDataSourceValidate++, System.Reflection.MethodInfo.GetCurrentMethod().Name);
 }
        private Microsoft.Office.Interop.Word.Document OpenWordTemplateFile(string FileNameStr)
        {
            Microsoft.Office.Interop.Word.Document oDoc = new Microsoft.Office.Interop.Word.Document();

            object Obj_FileName = FileNameStr;
            object Visible = false;
            object ReadOnly = false;
            object missing = System.Reflection.Missing.Value;
            _WordApplicMain = new Microsoft.Office.Interop.Word.Application();
            Object Nothing = System.Reflection.Missing.Value;
            oDoc = _WordApplicMain.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref Visible,
                ref missing, ref missing, ref missing,
                ref missing);
            oDoc.Activate();

            return oDoc;
        }
Beispiel #39
0
 /// <summary>
 /// Manage WordExport_DocumentBeforeClose
 /// </summary>
 /// <param name="Doc"></param>
 /// <param name="Cancel"></param>
 private void WordExport_DocumentBeforeClose(Microsoft.Office.Interop.Word.Document Doc, ref bool Cancel)
 {
     _IsPringPriview = false;
 }
        /// <summary>
        /// 调用模板生成Microsoft.Office.Interop.Word
        /// </summary>
        /// <param name="templateFile">模板文件</param>
        /// <param name="fileName">生成的具有模板样式的新文件</param>
        public static bool ExportWord(string templateFile, string fileName, Dictionary<string, string> Content)
        {
            try
            {
                //生成Microsoft.Office.Interop.Word程序对象
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

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

                //模板文件拷贝到新文件
                File.Copy(TemplateFile, FileName);
                //生成documnet对象
                Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
                object Obj_FileName = FileName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;

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

                Dictionary<string, string> Bookmarks = new Dictionary<string, string>();
                foreach (Microsoft.Office.Interop.Word.Bookmark bm in doc.Bookmarks)
                {
                    Bookmarks.Add(bm.Name, bm.Name);
                }
                foreach (String bm in Bookmarks.Keys)
                {
                    object WordMarkName = bm;// "书签名称" + WordIndex.ToString();//word模板中的书签名称
                    object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
                    doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref WordMarkName);//光标转到书签的位置
                    switch (bm)//为每个标签 添加内容。
                    {
                        case "传真电话": doc.ActiveWindow.Selection.TypeText(Content["传真电话"]); break;
                        case "发出时间": doc.ActiveWindow.Selection.TypeText(Content["发出时间"]); break;
                        case "发表人": doc.ActiveWindow.Selection.TypeText(Content["发表人"]); break;
                        case "受理单号": doc.ActiveWindow.Selection.TypeText(Content["受理单号"]); break;
                        case "开通时间": doc.ActiveWindow.Selection.TypeText(Content["开通时间"]); break;
                        case "执行人": doc.ActiveWindow.Selection.TypeText(Content["执行人"]); break;
                        case "执行情况": doc.ActiveWindow.Selection.TypeText(Content["执行情况"]); break;
                        case "执行时间": doc.ActiveWindow.Selection.TypeText(Content["执行时间"]); break;
                        case "收到人": doc.ActiveWindow.Selection.TypeText(Content["收到人"]); break;
                        case "收到时间": doc.ActiveWindow.Selection.TypeText(Content["收到时间"]); break;
                        case "申请单位": doc.ActiveWindow.Selection.TypeText(Content["申请单位"]); break;
                        case "相关文件": doc.ActiveWindow.Selection.TypeText(Content["相关文件"]); break;
                        case "确认人": doc.ActiveWindow.Selection.TypeText(Content["确认人"]); break;
                        case "确认意见": doc.ActiveWindow.Selection.TypeText(Content["确认意见"]); break;
                        case "联系方式": doc.ActiveWindow.Selection.TypeText(Content["联系方式"]); break;
                        case "调度单号": doc.ActiveWindow.Selection.TypeText(Content["调度单号"]); break;
                        case "通知内容": doc.ActiveWindow.Selection.TypeText(Content["通知内容"]); break;

                    }
                    //doc.ActiveWindow.Selection.TypeText("插入的内容" + BookmarksCount.ToString());//插入的内容,插入位置是word模板中书签定位的位置
                    doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//设置当前定位书签位置插入内容的格式
                }

                //int WordNum = 4;//书签个数
                ////将光标转到模板中定义的书签的位置,插入所需要添加的内容,循环次数与书签个数相符
                //for (int WordIndex = 1; WordIndex <= WordNum; WordIndex++)
                //{
                //    object WordMarkName = "书签名称" + WordIndex.ToString();//Microsoft.Office.Interop.Word模板中的书签名称
                //    object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
                //    doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref WordMarkName);//光标转到书签的位置
                //    doc.ActiveWindow.Selection.TypeText("插入的内容" + WordIndex.ToString());//插入的内容,插入位置是Microsoft.Office.Interop.Word模板中书签定位的位置
                //    doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//设置当前定位书签位置插入内容的格式
                //    //doc.ActiveWindow.Selection.TypeParagraph();//回车换行
                //}

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

                return true;

            }
            catch (Exception Ex)
            {
                return false;
            }
        }
Beispiel #41
0
        public static void loadword(string path)
        {
            try
            {
                object filenamenew = HostingEnvironment.MapPath(path.Replace("../", "~/"));
                Microsoft.Office.Interop.Word.Application AC = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
                object readOnly = false;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;

                doc = AC.Documents.Open(ref filenamenew, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
                // text = doc.Content.Text;
                //AC.Documents.Close();

            }
            catch (Exception ex)
            {

            }
        }
        public static void CreateContractCheckResult(string fileName, Model.ContractCheckResult result)
        {
            XWPFDocument doc = new XWPFDocument();
            XWPFParagraph pTitle = doc.CreateParagraph();
            pTitle.Alignment = ParagraphAlignment.CENTER;
            XWPFRun rText = pTitle.CreateRun();
            rText.IsBold = true;
            rText.FontSize = 18;
            rText.SetText("客户管理系统合同数据检查结果报告");

            XWPFParagraph pDesc = doc.CreateParagraph();
            pDesc.Alignment = ParagraphAlignment.RIGHT;
            rText = pDesc.CreateRun();
            rText.IsBold = false;
            rText.SetColor("#ff0000");
            rText.FontSize = 8;
            rText.SetText("*本报告仅供参考,实际结果以客户管理系统为准");
            XWPFParagraph pContent = doc.CreateParagraph();
            pContent.Alignment = ParagraphAlignment.BOTH;
            rText = pContent.CreateRun();
            rText.IsBold = true;
            rText.SetText("一、合同概况:");

            if (!string.IsNullOrEmpty(result.ContractSurvey))
            {
                string[] strList = result.ContractSurvey.Split(new char[] { '$' });
                foreach (string item in strList)
                {
                    pContent = doc.CreateParagraph();
                    rText = pContent.CreateRun();
                    rText.SetText("        " + item);
                }
            }

            pContent = doc.CreateParagraph();
            pContent.Alignment = ParagraphAlignment.BOTH;
            rText = pContent.CreateRun();
            rText.IsBold = true;
            rText.SetText("二、检查结果:");

            pContent = doc.CreateParagraph();
            rText = pContent.CreateRun();
            rText.SetText("        " + result.CheckResult);

            pContent = doc.CreateParagraph();
            pContent.Alignment = ParagraphAlignment.BOTH;
            rText = pContent.CreateRun();
            rText.IsBold = true;
            rText.SetText("三、检查规则:");

            if (!string.IsNullOrEmpty(result.CheckRule))
            {
                string[] strList = result.CheckRule.Split(new char[] { '$' });
                foreach (string item in strList)
                {
                    pContent = doc.CreateParagraph();
                    rText = pContent.CreateRun();
                    rText.SetText("        " + item);
                }
            }

            FileStream sw = File.Create(fileName);
            doc.Write(sw);
            sw.Close();
            try
            {
                Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
                Object nothing = System.Reflection.Missing.Value;
                Object filePath = fileName;
                wordApplication.Documents.Open(ref filePath, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref   nothing, ref   nothing, ref   nothing, ref   nothing, ref  nothing, ref   nothing, ref   nothing);
                wordDocument = wordApplication.ActiveDocument;
                wordApplication.Visible = true;
            }
            catch { }
        }
        private void exportDocFile(string TemplateFileName, string saveFileName, List <double> lineLengthList)
        {
            GC.Collect();
            int[] lineCount = new int[6] {
                0, 0, 0, 0, 0, 0
            };
            double[] linePercent = new double[6] {
                0, 0, 0, 0, 0, 0
            };
            string[] lineName = new string[6] {
                "", "", "", "", "", ""
            };
            double[] linePercentSum = new double[6] {
                0, 0, 0, 0, 0, 0
            };
            for (int i = 0; i < lineLengthList.Count; i++)
            {
                if (lineLengthList[i] >= 0 && lineLengthList[i] < 2)
                {
                    lineCount[0]++;
                    lineName[0] = "[0,2)";
                }
                else if (lineLengthList[i] >= 2 && lineLengthList[i] < 5)
                {
                    lineCount[1]++;
                    lineName[1] = "[2,5)";
                }
                else if (lineLengthList[i] >= 5 && lineLengthList[i] < 10)
                {
                    lineCount[2]++;
                    lineName[2] = "[5,10)";
                }
                else if (lineLengthList[i] >= 10 && lineLengthList[i] < 11.5)
                {
                    lineCount[3]++;
                    lineName[3] = "[10,11.5)";
                }
                else if (lineLengthList[i] >= 11.5 && lineLengthList[i] < 12.3)
                {
                    lineCount[4]++;
                    lineName[4] = "[11.5,12.3)";
                }
                else if (lineLengthList[i] >= 12.3)
                {
                    lineCount[5]++;
                    lineName[5] = ">=12.3";
                }
            }
            for (int i = 0; i < 6; i++)
            {
                linePercent[i] = Math.Round((double)lineCount[i] * 100 / (double)lineLengthList.Count, 2);
            }

            linePercentSum[0] = linePercent[0] / 100;
            for (int i = 1; i < 6; i++)
            {
                linePercentSum[i] += linePercentSum[i - 1] + linePercent[i] / 100;
            }

            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            //!<根据模板文件生成新文件框架
            File.Copy(TemplateFileName, saveFileName);
            //!<生成documnet对象
            Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
            //!<打开新文挡
            object objFileName = saveFileName;
            object missing     = System.Reflection.Missing.Value;
            object isReadOnly  = false;
            object isVisible   = false;

            doc = app.Documents.Open(ref objFileName, ref missing, ref isReadOnly, ref missing,
                                     ref missing, ref missing, ref missing, ref missing,
                                     ref missing, ref missing, ref missing, ref isVisible,
                                     ref missing, ref missing, ref missing, ref missing);
            doc.Activate();
            //!<光标转到书签
            int length = 0;

            for (int bookIndex = 1; bookIndex <= 6; bookIndex++)
            {
                object BookMarkName = "tb" + bookIndex.ToString();
                object what         = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
                doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref BookMarkName); //!<定位到书签位置

                doc.ActiveWindow.Selection.TypeText(lineCount[bookIndex - 1].ToString());              //!<在对应书签位置插入内容
                length = lineCount[bookIndex - 1].ToString().Length;
                app.ActiveDocument.Bookmarks.get_Item(ref BookMarkName).End = app.ActiveDocument.Bookmarks.get_Item(ref BookMarkName).End + length;
            }
            for (int bookIndex = 7; bookIndex <= 12; bookIndex++)
            {
                object BookMarkName = "tb" + bookIndex.ToString();
                object what         = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
                doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref BookMarkName); //!<定位到书签位置

                doc.ActiveWindow.Selection.TypeText(linePercent[bookIndex - 7].ToString() + "%");      //!<在对应书签位置插入内容
                length = linePercent[bookIndex - 7].ToString().Length;
                app.ActiveDocument.Bookmarks.get_Item(ref BookMarkName).End = app.ActiveDocument.Bookmarks.get_Item(ref BookMarkName).End + length;
            }

            //生成统计图1
            DataTable  attributeTable = new DataTable("数量");
            DataColumn pDataColumn    = new DataColumn("管节长度");

            pDataColumn.Unique   = true;
            pDataColumn.DataType = System.Type.GetType("System.String");
            attributeTable.Columns.Add(pDataColumn);
            pDataColumn          = null;
            pDataColumn          = new DataColumn("统计值");
            pDataColumn.Unique   = false;
            pDataColumn.DataType = System.Type.GetType("System.Double");
            attributeTable.Columns.Add(pDataColumn);
            pDataColumn = null;

            string jpgpath = ClsGDBDataCommon.GetParentPathofExe() + @"Resource\BMP\neijiance.jpg";

            createStatChart(attributeTable, lineCount, linePercent, lineName, jpgpath);

            object BookMarkNameimg = "tb13";
            object whatimg         = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;

            doc.ActiveWindow.Selection.GoTo(ref whatimg, ref missing, ref missing, ref BookMarkNameimg); //!<定位到书签位置
            object Anchor           = app.Selection.Range;
            object LinkToFile       = false;
            object SaveWithDocument = true;

            Microsoft.Office.Interop.Word.InlineShape shape = app.ActiveDocument.InlineShapes.AddPicture(jpgpath, ref LinkToFile, ref SaveWithDocument, ref Anchor);
            //shape.Width = 100f;//图片宽度
            //shape.Height = 20f;//图片高度

            //生成统计图2
            DataTable  attributeTable2 = new DataTable("累计比例");
            DataColumn pDataColumn2    = new DataColumn("管节长度");

            pDataColumn2.Unique   = true;
            pDataColumn2.DataType = System.Type.GetType("System.String");
            attributeTable2.Columns.Add(pDataColumn2);
            pDataColumn2          = null;
            pDataColumn2          = new DataColumn("累计值");
            pDataColumn2.Unique   = false;
            pDataColumn2.DataType = System.Type.GetType("System.Double");
            attributeTable2.Columns.Add(pDataColumn2);
            pDataColumn2 = null;

            string jpgpath2 = ClsGDBDataCommon.GetParentPathofExe() + @"Resource\BMP\neijiance2.jpg";

            createStatChart2(attributeTable2, linePercentSum, linePercent, lineName, jpgpath2);

            object BookMarkNameimg2 = "tb14";
            object whatimg2         = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;

            doc.ActiveWindow.Selection.GoTo(ref whatimg2, ref missing, ref missing, ref BookMarkNameimg2); //!<定位到书签位置
            object Anchor2           = app.Selection.Range;
            object LinkToFile2       = false;
            object SaveWithDocument2 = true;

            Microsoft.Office.Interop.Word.InlineShape shape2 = app.ActiveDocument.InlineShapes.AddPicture(jpgpath2, ref LinkToFile2, ref SaveWithDocument2, ref Anchor2);
            //shape.Width = 100f;//图片宽度
            //shape.Height = 20f;//图片高度

            //!<输出完毕后关闭doc对象
            object IsSave = true;

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

            MessageBox.Show("生成“" + saveFileName + "”成功!");
        }
        private void checkExistsInDocument(string filePath, string inputString, bool stopOnFailure, string customErrorMessage)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();

            object fileName = filePath;
            // Define an object to pass to the API for missing parameters
            object missing = System.Type.Missing;
            doc = word.Documents.Open(ref fileName,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing);

            String read = string.Empty;
            List<string> data = new List<string>();
            foreach (Microsoft.Office.Interop.Word.Range tmpRange in doc.StoryRanges)
            {
                //read += tmpRange.Text + "<br>";
                data.Add(tmpRange.Text);
            }
            ((Microsoft.Office.Interop.Word._Document)doc).Close();
            ((Microsoft.Office.Interop.Word._Application)word).Quit();
            Boolean isFound = false;
            foreach (String line in data)
            {
                if (line.Contains(inputString))
                {
                    isFound = true;
                    break;
                }
            }

            if (!isFound)
            {
                reportResults(
                         stopOnFailure,
                         "Check Document",
                         "Check Doument Information command failed. File: " + filePath
                         + " does not contain the expected values.",
                         LogLevel.Error,
                         "",
                         customErrorMessage);
            }
            else
            {
                reportResults("Check Document",
                                        "Check Document Information command passed.",
                                        LogLevel.Success
                                        );
            }
        }
Beispiel #45
0
        private string InitRead(string Template, Dictionary <string, string> datas, string filePath)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document    doc = null;
            //将要导出的新word文件名
            string physicNewFile = "预报告.doc";

            try
            {
                app         = new Microsoft.Office.Interop.Word.Application();             //创建word应用程序
                app.Visible = false;
                object fileName = System.Windows.Forms.Application.StartupPath + Template; //Year1;//模板文件
                //打开模板文件
                object oMissing = System.Reflection.Missing.Value;
                doc = app.Documents.Open(ref fileName,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);



                object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                foreach (var item in datas)
                {
                    app.Selection.Find.Replacement.ClearFormatting();
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Text             = item.Key;   //需要被替换的文本
                    app.Selection.Find.Replacement.Text = item.Value; //替换文本

                    //执行替换操作
                    app.Selection.Find.Execute(
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing, ref oMissing,
                        ref oMissing, ref replace,
                        ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing);
                }


                //对替换好的word模板另存为一个新的word文档
                doc.SaveAs(String.Format(@"{0}\{1}", filePath, physicNewFile),
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

                //准备导出word
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                //这边为了捕获Response.End引起的异常
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭word文档
                }
                if (app != null)
                {
                    app.Quit();//退出word应用程序
                }
            }
            return(physicNewFile);
        }
        ////////////////////////////////////////
            //        MS-Word Processing
            ////////////////////////////////////////

            //Word.ApplicationClass wordApp = new Word.ApplicationClass();

        private void Func1()
        {
            Microsoft.Office.Interop.Word.ApplicationClass oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();

            object fileName = (object)@"D:\Documents and Settings\Haim\Desktop\Kan-Naim\test.doc";
            //object fileName = (object)@"D:\Documents and Settings\Haim\Desktop\Kan-Naim\ArticleEditor.doc";
            object oMissing = System.Reflection.Missing.Value;

            oWordApp.Visible = true;
            oWordDoc = oWordApp.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            oWordDoc.ActiveWindow.Selection.WholeStory();
            oWordDoc.ActiveWindow.Selection.Copy();

            IDataObject data = Clipboard.GetDataObject();

            if (data != null) richTextBox1.Text = data.GetData(DataFormats.Text).ToString();

            object oTrue = true;
            object oFalse = false;

            Object oTemplatePath = (object)@"D:\Documents and Settings\Haim\Desktop\Kan-Naim\ArticleTemplate.dotx";
            oWordDoc = oWordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oTrue);

            Microsoft.Office.Tools.Word.RichTextContentControl richTextContentControl1;
            Microsoft.Office.Tools.Word.Document oWordTools = new Microsoft.Office.Tools.Word.Document();
            //oWordTools.Application.ActiveDocument.ContentControls = oWordApp;
            oWordTools.Paragraphs[1].Range.InsertParagraphBefore();
            oWordTools.Paragraphs[1].Range.Select();
            richTextContentControl1 = oWordTools.Controls.AddRichTextContentControl("richTextControl1");
            richTextContentControl1.PlaceholderText = "Enter your first name";

            //oWordDoc.ContentControls.get_Item(

        }
Beispiel #47
0
        ///<summary>
        /// 在word 中查找一个字符串直接替换所需要的文本
        /// </summary>
        /// <param name="strOldText">原文本</param>
        /// <param name="strNewText">新文本</param>
        /// <returns></returns>
        public bool Replace(string strOldText, string strNewText)
        {
            if (oDoc == null)
                oDoc = oWordApplic.ActiveDocument;
            this.oDoc.Content.Find.Text = strOldText;
            object FindText, ReplaceWith, Replace;// 
            FindText = strOldText;//要查找的文本
            ReplaceWith = strNewText;//替换文本
            Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;/**//*wdReplaceAll - 替换找到的所有项。
                                                      * wdReplaceNone - 不替换找到的任何项。
                                                    * wdReplaceOne - 替换找到的第一项。
                                                    * */
            oDoc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
            if (oDoc.Content.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))
            {
                return true;
            }
            return false;
        }
Beispiel #48
0
        static void create_word(DataGridView dataGridView)
        {
            var Wordapp = new Microsoft.Office.Interop.Word.Application();

            Microsoft.Office.Interop.Word.Document doc   = Wordapp.Documents.Add();
            Microsoft.Office.Interop.Word.Range    range = doc.Range();
            try
            {
                int countAll = 0, countAsks = 0, countRKK = 0;
                for (int i = 1; i < dataGridView.RowCount; i++)
                {
                    countRKK  += Convert.ToInt32(dataGridView.Rows[i - 1].Cells[2].Value);
                    countAsks += Convert.ToInt32(dataGridView.Rows[i - 1].Cells[3].Value);
                    countAll  += Convert.ToInt32(dataGridView.Rows[i - 1].Cells[4].Value);
                }
                range.Text = "Справка о неисполненных документах и обращениях граждан \n";
                range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                range.Bold      = 1;
                range.Font.Name = "Arial";
                range.Font.Size = 14;
                range.EndOf();
                range.Text = "Не исполнено в срок " + countAll + " документов, из них: \n";
                range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                range.Bold      = 0;
                range.Font.Name = "Arial";
                range.Font.Size = 10;
                range.EndOf();
                range.Text = "- количество неисполненных входящих документов: " + countRKK + "; \n";
                range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                range.Bold      = 0;
                range.Font.Name = "Arial";
                range.Font.Size = 10;
                range.EndOf();
                range.Text = "- количество неисполненных письменных обращений граждан: " + countAsks + ". \n";
                range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                range.Bold      = 0;
                range.Font.Name = "Arial";
                range.Font.Size = 10;
                range.EndOf();
                range.Text = "Сортировка: по общему количеству документов \n";
                range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                range.Bold      = 0;
                range.Font.Name = "Arial";
                range.Font.Size = 10;
                range.EndOf();

                Microsoft.Office.Interop.Word.Table table = doc.Tables.Add(range, dataGridView.RowCount, dataGridView.ColumnCount);
                table.Borders.Enable                  = 1;
                table.Cell(1, 1).Range.Text           = "№ п.п.";
                table.Cell(1, 2).Range.Text           = "Ответственный исполнитель";
                table.Cell(1, 3).Range.Text           = "Количество неисполненных входящих документов";
                table.Cell(1, 4).Range.Text           = "Количество неисполненных письменных обращений граждан";
                table.Cell(1, 5).Range.Text           = "Общее количество документов и обращений";
                table.Range.Bold                      = 0;
                table.Range.Font.Name                 = "Arial";
                table.Range.Font.Size                 = 10;
                table.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //table.Columns[0].
                for (int i = 1; i < dataGridView.RowCount; i++)
                {
                    table.Cell(i + 1, 1).Range.Text = dataGridView.Rows[i - 1].Cells[0].Value.ToString();
                    table.Cell(i + 1, 2).Range.Text = dataGridView.Rows[i - 1].Cells[1].Value.ToString();
                    table.Cell(i + 1, 3).Range.Text = dataGridView.Rows[i - 1].Cells[2].Value.ToString();
                    table.Cell(i + 1, 4).Range.Text = dataGridView.Rows[i - 1].Cells[3].Value.ToString();
                    table.Cell(i + 1, 5).Range.Text = dataGridView.Rows[i - 1].Cells[4].Value.ToString();
                }
                var      Paragraph = Wordapp.ActiveDocument.Paragraphs.Add();
                var      rangeEnd  = Paragraph.Range;
                DateTime dt        = DateTime.Now;
                string   curDate   = dt.ToShortDateString();
                rangeEnd.Text = "\n Дата составление справки: " + curDate;
                rangeEnd.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                rangeEnd.Bold      = 0;
                rangeEnd.Font.Name = "Arial";
                rangeEnd.Font.Size = 10;
                Wordapp.Visible    = true;
            }
            catch { }
        }
        private void LoadFiles(string dir)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            openFileDialog.Filter           = "Text files (*.txt)|*.txt|Excel Files (*.xls)|*.xls;*.xlsx|Word Files (*.doc;*.docx;*.dot)|*.doc;*.docx;*.dot|Pdf Files (*.pdf)|*.pdf|All Files (*.*)|*.*";
            //Djora 14.05.21
            string path = @"\\" + LoginForm.FileServer + @"\d\PlacanjaUplate\";


            //string path = @"D:\\server\PlacanjaUplate\";


            if (Directory.Exists(path))
            {
                openFileDialog.InitialDirectory = path;
            }
            //openFileDialog.WindowStartupLocation= WindowStartupLocation.CenterScreen;
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                strFileName = openFileDialog.FileName;
                string folderPath = openFileDialog.InitialDirectory;
                this.Text = openFileDialog.SafeFileName;
                switch (openFileDialog.FilterIndex)
                {
                case 1:
                    odabranifajl     = openFileDialog.SafeFileName.ToString();
                    IzvodPoruka.Text = openFileDialog.SafeFileName.ToString();
                    //ProcessStartInfo startInfo = new ProcessStartInfo("notepad.exe");
                    //startInfo.WindowStyle = ProcessWindowStyle.Maximized;
                    //Process.Start(strFileName);

                    break;

                case 2:
                    var excelApp = new Microsoft.Office.Interop.Excel.Application();
                    excelApp.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlNormal;
                    //excelApp.Top = Top + 108; ;
                    // excelApp.Width = Width-70;
                    string ime = excelApp.Name;
                    //excelApp.Height = Height-70;
                    excelApp.Visible = true;
                    Microsoft.Office.Interop.Excel.Workbooks books = excelApp.Workbooks;
                    //excelApp.Width = Width;
                    //excelApp.Height = Height;

                    excelApp.Workbooks.Open(strFileName);

                    break;

                case 3:
                    Microsoft.Office.Interop.Word.Application wdApp = new Microsoft.Office.Interop.Word.Application();
                    wdApp.Visible     = true;
                    wdApp.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateNormal;
                    Microsoft.Office.Interop.Word.Document aDoc = wdApp.Documents.Open(strFileName);


                    break;

                case 4:
                    WebBrowser wb = new WebBrowser();
                    wb.Top = Top - 40;
                    wb.Navigate(strFileName);

                    break;

                case 5:
                    ProcessStartInfo startInfo1 = new ProcessStartInfo("");
                    startInfo1.WindowStyle = ProcessWindowStyle.Maximized;
                    Process.Start(strFileName);
                    break;
                }
                strPutanjaPlacanja = openFileDialog.InitialDirectory;
            }
        }
 /// <summary>
 /// Обработчик темпланов
 /// </summary>
 /// <param name="parFilaName">имя файла word с ТП</param>
 public ThematicPlanProcessor(String parFilaName)
 {
     Thread.Sleep(1000);
     this.application = new Interpop.Word.Application();
     this.document = application.Documents.Open(parFilaName);
 }
Beispiel #51
0
        public void ReplaceStr(string Str, string Vaule, Microsoft.Office.Interop.Word.Document WordDoc)
        {
            object MissingValue = Type.Missing;

            WordDoc.Content.Find.Execute(Str, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue, Vaule, Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll, MissingValue, MissingValue, MissingValue, MissingValue);
        }
Beispiel #52
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         /* if (catalogsComboBox.SelectedIndex == 1)
           {*/
         col = 0;
         if (DialogResult.OK == saveFileDialog1.ShowDialog())
         {
             Microsoft.Office.Interop.Word.Application wdApp = new Microsoft.Office.Interop.Word.Application();
             Microsoft.Office.Interop.Word.Document wdDoc = new Microsoft.Office.Interop.Word.Document();
             wdDoc = wdApp.Documents.Add();
             Microsoft.Office.Interop.Word.Range rang = wdDoc.Range();
             wdDoc.SpellingChecked = false;
             wdDoc.ShowSpellingErrors = false;
             wdApp.Selection.Font.Name = "Times New Roman";
             wdApp.Selection.Font.Size = 12;
             wdApp.ActiveDocument.Select();
             string CommandText = "select * from `ads_paper`.`catalogitems` order by idcatalogItems";
             string Connect = "Database=" + dbname + ";Data Source=" + server + ";User Id=" + dbuser + ";Password="******";Port=" + dbPort;
             MySqlConnection myConnection = new MySqlConnection(Connect);
             MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
             myConnection.Open(); //Устанавливаем соединение с базой данных.
             MySqlDataReader MyDataReader;
             bool state = false;
             MyDataReader = myCommand.ExecuteReader();
             int[] catID = new int[5];
             int parentID;
             int real;
             int sum;
             while (MyDataReader.Read())
             {
                 catID[0] = MyDataReader.GetInt32(0);
                 catID[1] = MyDataReader.GetInt32(2);
                 catID[2] = MyDataReader.GetInt32(3);
                 catID[3] = MyDataReader.GetInt32(4);
                 catID[4] = MyDataReader.GetInt32(5);
                 string name = MyDataReader.GetString(1); //Получаем строку
                 //parentID = MyDataReader.GetInt32(6);
                 //real = MyDataReader.GetInt32(7);
                 //sum = MyDataReader.GetInt32(8);
                 if (checkCount(catID))
                 {
                     wdApp.Selection.TypeParagraph();
                     if (catID[2] == 0)
                     {
                         wdApp.Selection.TypeText("@@" + catID[1].ToString());
                         wdApp.Selection.TypeParagraph();
                         wdApp.Selection.TypeParagraph();
                         wdApp.Selection.TypeText(name);
                         wdApp.Selection.TypeParagraph();
                         wdApp.Selection.TypeParagraph();
                     }
                     else if (catID[3] == 0)
                     {
                         if (catID[1] == 1 || catID[1] == 4 || catID[1] == 5 || catID[1] == 11 || catID[1] == 18)
                         {
                             wdApp.Selection.TypeText("-" + catID[1].ToString() + "." + catID[2].ToString() + "-");
                             wdApp.Selection.TypeParagraph();
                         }
                         else
                         {
                             wdApp.Selection.TypeText(catID[1].ToString() + "." + catID[2].ToString());
                         }
                         wdApp.Selection.TypeText(" " + name);
                         wdApp.Selection.TypeParagraph();
                         state = true;
                     }
                     else
                     {
                         wdApp.Selection.TypeText(name);
                         wdApp.Selection.TypeParagraph();
                         wdApp.Selection.TypeParagraph();
                         state = false;
                     }
                     PrintAdsOB(catID, ref wdApp);
                 }
             }
             MyDataReader.Close();
             myConnection.Close();
             ReplaceTextWord(ref wdApp, "  ", " ");
             wdApp.ActiveDocument.SaveAs(saveFileDialog1.FileName + ".doc");
             wdDoc.Close();
             //wdApp.Documents.Close();
             wdApp.Quit();
             MessageBox.Show("Выгрузка завершена, выгружено: " + col.ToString() + " объявлений");
         }
     }
     catch (Exception except)
     {
         MessageBox.Show(except.Message);
     }
 }
Beispiel #53
0
        //Word替换功能
        public static void StrReplace(string StrOld, string StrNew, Microsoft.Office.Interop.Word.Document WordDoc)
        {
            object Object = null;

            WordDoc.Content.Find.Execute(StrOld, Object, Object, Object, Object, Object, Object, Object, Object, StrNew, Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll, Object, Object, Object, Object);
        }
Beispiel #54
0
 public static void SetTableVaule(string Vaule, int Table, int Row, int Column, Microsoft.Office.Interop.Word.Document WordDoc)
 {
     WordDoc.Tables[Table].Cell(Row, Column).Range.Text = Vaule;
 }
Beispiel #55
0
        private void DökümanıOluştur()
        {
            var application = new Microsoft.Office.Interop.Word.Application();
            var document    = new Microsoft.Office.Interop.Word.Document();

            application.Visible = false;
            document            = application.Documents.Add(path);
            foreach (Microsoft.Office.Interop.Word.Field field in document.Fields)
            {
                if (field.Code.Text.Contains("isAdi"))
                {
                    field.Select();
                    application.Selection.TypeText(HerkezeAçıkİhaleHizmetAlımıİdariŞartName.isAdi);
                }
                else if (field.Code.Text.Contains("kayıtno"))
                {
                    field.Select();
                    application.Selection.TypeText(HerkezeAçıkİhaleHizmetAlımıİdariŞartName.kayıtno);
                }
                else if (field.Code.Text.Contains("firmatarih"))
                {
                    field.Select();
                    application.Selection.TypeText(dateTimePicker1.Text);
                }
                else if (field.Code.Text.Contains("firmasaat"))
                {
                    field.Select();
                    application.Selection.TypeText(dateEdit1.Text);;
                }
                else if (field.Code.Text.Contains("firma1"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        field.Select();
                        application.Selection.TypeText(HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1);
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("firma2"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        field.Select();
                        application.Selection.TypeText(HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2);
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("firma3"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        field.Select();
                        application.Selection.TypeText(HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3);
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("teklifmektubu"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox1.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("birimfiyatcetveli"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox2.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("ticaretsicil"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox3.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("odakayıt"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox4.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("imza"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox5.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("velaketname"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox6.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("isdeneyim"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox7.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("geciciteminat"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox8.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("isortak"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox9.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("faaliyet"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox10.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("ortaklıkdurum"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma1 != null)
                    {
                        if (checkBox11.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                }
                else if (field.Code.Text.Contains("1a"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox22.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("2b"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox21.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("3c"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox20.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("4d"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox19.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("5e"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox18.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("6f"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox17.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("7g"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox16.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("8x"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox15.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("9y"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox14.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("10m"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox13.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("11z"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma2 != null)
                    {
                        if (checkBox12.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        else
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("one"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (one.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (one.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("two"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (two.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (two.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("tri"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (tri.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (tri.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("four"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (four.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (four.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("five"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (five.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (five.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("six"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (six.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (six.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("seven"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (seven.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (seven.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("eight"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (eight.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (eight.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("nine"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (nine.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (nine.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("ten"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (ten.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (ten.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("eleven"))
                {
                    if (HerkezeAçıkİhaleHizmetAlımıTipYaklasikMaliyetFormu.firma3 != null)
                    {
                        if (eleven.Checked == true)
                        {
                            field.Select();
                            application.Selection.TypeText("✓");
                        }
                        if (eleven.Checked == false)
                        {
                            field.Select();
                            application.Selection.TypeText("GD");
                        }
                    }
                    else
                    {
                        field.Delete();
                    }
                }
                else if (field.Code.Text.Contains("komisyonbaskan"))
                {
                    field.Select();
                    application.Selection.TypeText(HerkezeAçıkİhaleKomisyonOlurYazısı.komisyon1);
                }
                else if (field.Code.Text.Contains("komisyon1"))
                {
                    field.Select();
                    application.Selection.TypeText(HerkezeAçıkİhaleKomisyonOlurYazısı.komisyon2);
                }
                else if (field.Code.Text.Contains("komisyon2"))
                {
                    field.Select();
                    application.Selection.TypeText(HerkezeAçıkİhaleKomisyonOlurYazısı.komisyon3);
                }
            }
            document.SaveAs2(path1);
            document.Close();
            application.Quit();
            richEditControl1.LoadDocument(path1);
        }
Beispiel #56
0
        // Open a new document
        public void Open()
        {
            oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            oDoc.Activate();
        }
Beispiel #57
0
        static void Main(string[] args)

        {
            string conString = "User Id=x; password=x;" + "Data Source=x.world; Pooling=false;";



            OracleConnection con = new OracleConnection();

            con.ConnectionString = conString;



            try {
                con.Open();
                Console.WriteLine("Connection to database successful!");
            } catch {
                Console.WriteLine("Connection Failed!");
            }



            string path_string_failed = "";

            string path_string = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            int    counter     = 0;

            path_string_failed = path_string + "\\failed_2\\";

            string[] fileEntries = Directory.GetFiles(path_string_failed, "*.pdf");
            foreach (string fileName in fileEntries)
            {
                Console.WriteLine(fileName);



                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                object miss          = System.Reflection.Missing.Value;
                string path_string_z = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @fileName);

                object path     = path_string_z;
                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 < 100; i++)
                {
                    try {
                        totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
                    } catch {
                    }
                }

                int starting_pos = 0;

                int ending_pos = 0;

                try {
                    starting_pos = totaltext.IndexOf("Pkt") + 11;
                    ending_pos   = totaltext.IndexOf("Pkt", starting_pos);
                } catch {
                    string newName_path_name_2 = path_string + "\\uhoh\\";
                    Console.WriteLine("Bad File Type");
                }


                string pkt_ctrl_num = "";
                string div          = "";

                try {
                    pkt_ctrl_num = totaltext.Substring(starting_pos, ending_pos - starting_pos).Trim();

                    if (pkt_ctrl_num.Length > 13)
                    {
                        ending_pos = totaltext.IndexOf("Customer", starting_pos);


                        pkt_ctrl_num = totaltext.Substring(starting_pos, ending_pos - starting_pos).Trim();
                        pkt_ctrl_num = pkt_ctrl_num.Trim();
                        //success = true;

                        pkt_ctrl_num = pkt_ctrl_num.Remove(pkt_ctrl_num.Length - 2);
                    }
                } catch {
                    Console.WriteLine("pk:" + pkt_ctrl_num);



                    string newName_path_name_2 = path_string + "\\uhoh\\";


                    if (pkt_ctrl_num.Length > 12 || pkt_ctrl_num == "")
                    {
                        Console.WriteLine("No Pkt Found!");
                    }
                    else
                    {
                        Console.WriteLine("Incorret File Type...Skipped.");
                        System.IO.File.Move(fileName, newName_path_name_2);
                    }
                }

                Console.WriteLine("Pickticket_found:" + pkt_ctrl_num);



                string query = @
                               "select div from pkt_hdr ph 
                            JOIN cd_master cm on ph.cd_master_id = cm.cd_master_id where pkt_ctrl_nbr =" + "'" + pkt_ctrl_num + "'" +
                               "and cm.co = 'AMBU'" + @
                               "UNION all
                            select div from arc_wh_ghc1.pkt_hdr ap 
                            JOIN cd_master cm on ap.cd_master_id = cm.cd_master_id 
                            where ap.pkt_ctrl_nbr =" + "'" + pkt_ctrl_num + "'" + @
                               "
                            and cm.co = 'AMBU' and 
                            not exists ( select null from pkt_hdr ph 
                            JOIN cd_master cm on ph.cd_master_id = cm.cd_master_id 
                            where ph.pkt_ctrl_nbr = " + "'" + pkt_ctrl_num + "'" + ")";



                OracleCommand cmd = con.CreateCommand();
                cmd.CommandText = query;

                OracleDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    // Console.WriteLine("in reader");

                    div = reader.GetString(0);

                    Console.WriteLine("div= " + div);
                }


                string newName             = div + "_" + pkt_ctrl_num;
                string newName_path_name   = path_string + "\\success2\\" + newName + ".pdf";
                string newName_path_name_3 = path_string + "\\uhoh\\";
                reader.Close();


                docs.Close(false);
                word.Quit(false);
                reader.Close();

                if (docs != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(docs);
                }
                if (word != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(word);
                }

                docs = null;
                word = null;
                GC.Collect();


                try {
                    // success = false;
                    System.IO.File.Move(fileName, newName_path_name);
                } catch {
                    // success = false;
                    Console.WriteLine("file already exists skipped! ");

                    File.Move(fileName, newName_path_name_3 + Path.GetFileName(fileName));
                    // System.IO.File.Copy(fileName, newName_path_name_3);
                }



                counter = counter + 1;
            }



            Console.WriteLine("Total Numbers of Files in directory equals: " + counter);
            Console.ReadLine()
        }
Beispiel #58
0
        /// <summary>
        /// 将doc文档转换成html
        /// </summary>
        /// <param name="FilePath">虚拟路径文件名</param>
        /// <param name="NewHtmlName">新的html文件名</param>
        /// <param name="StrHtml">获取的Html</param>
        /// <param name="IsDelDocFile">是否删除doc文件</param>
        /// <param name="IsDelHtmlFile">是否删除html文件</param>
        /// <returns>如果返回false,则NewHtmlName和StrHtml均为空</returns>
        public bool Convertion2Html(string FilePath, out string NewHtmlName, out string StrHtml, bool IsDelDocFile, bool IsDelHtmlFile)
        {
            NewHtmlName = "";
            StrHtml = "";
            if (FilePath.Trim() == "")
            {
                return false;
            }

            //必须先关闭WINWORD
            try
            {
                System.Diagnostics.Process[] CloseID = System.Diagnostics.Process.GetProcessesByName("WINWORD");

                for (int i = 0; i < CloseID.Length; i++)
                {
                    if (!CloseID[i].CloseMainWindow())
                    {
                        CloseID[i].Kill();
                    }
                }
            }
            catch { }
            //绝对路径,同时将后缀名定位小写doc,防止大写
            string RealFileNamePath = HttpContext.Current.Server.MapPath(FilePath);
            RealFileNamePath = RealFileNamePath.Substring(0, RealFileNamePath.Length - 3) + "doc";
            RealFileNamePath = "d:\\2.doc";
            //调用word类库
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            Type wordType = word.GetType();
            Microsoft.Office.Interop.Word.Documents docs = word.Documents;
            Type docsType = docs.GetType();
            //读取doc文档
            Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
            try
            {
               doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open",
               System.Reflection.BindingFlags.InvokeMethod,null, docs, new Object[] { RealFileNamePath, true, true });
            }
            catch
            {
                try
                {
                    wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod,
                        null, word, null);
                }
                catch { }
                return false;
            }

            //   转换格式,另存为
            Type docType = doc.GetType();
            object saveFileName = RealFileNamePath.Replace(".doc", ".htm");

            try
            {
                docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
                null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });
                ///其它格式:
                ///wdFormatHTML
                ///wdFormatDocument
                ///wdFormatDOSText
                ///wdFormatDOSTextLineBreaks
                ///wdFormatEncodedText
                ///wdFormatRTF
                ///wdFormatTemplate
                ///wdFormatText
                ///wdFormatTextLineBreaks
                ///wdFormatUnicodeText
                wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
            }
            catch
            {
                //   退出 Word
                try
                {
                    wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod,
                        null, word, null);
                }
                catch { }
                return false;
            }
            //返回的数据
            NewHtmlName = FilePath.Replace(".doc", ".htm");
            //一定要等待几秒再操作,否则由于缓存的文件没有写入,会导致异常
            System.Threading.Thread.Sleep(3000);
            StrHtml = this.GetFileContent(NewHtmlName);
            //根据需要删除文件
            if (IsDelDocFile)
            {
                System.IO.File.Delete(RealFileNamePath);
            }
            if (IsDelHtmlFile)
            {
                System.IO.File.Delete(RealFileNamePath.Replace(".doc", ".htm"));
                ////删除文件夹,先判断是否存在该目录
                //string dirPath = RealFileNamePath.Replace(".doc", ".files");
                //if (System.IO.Directory.Exists(dirPath))
                //    System.IO.Directory.Delete(dirPath, true);
            }

            return true;
        }
Beispiel #59
0
        public void downTable()
        {
            try
            {
                var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
                //@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
                var templateName = direc + "附件1-985大型设备购置论证报告_模板.doc";
                Microsoft.Office.Interop.Word.ApplicationClass wordApp;
                Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
                object Obj_FileName = templateName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;
                wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Object Nothing = System.Reflection.Missing.Value;
                wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                wordDocument.Activate();

                Microsoft.Office.Interop.Word.Table wordTable = wordDocument.Tables[1];

                var Iid = Request.GetInt("tastItemID");

                var memI = Database.ConstructTaskItems.SingleOrDefault(cti => cti.ID == Iid);

                wordDocument.Bookmarks.get_Item("DeviceName").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
                wordDocument.Bookmarks.get_Item("Unit").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.College.Name;
                wordDocument.Bookmarks.get_Item("DeviceManager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Member.Name;
                wordDocument.Bookmarks.get_Item("Phone").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Member.GetExpert(Database).MobilePhone;
                wordDocument.Bookmarks.get_Item("Year").Range.Text = DateTime.Now.Year.ToString();
                wordDocument.Bookmarks.get_Item("month").Range.Text = DateTime.Now.Month.ToString();
                wordDocument.Bookmarks.get_Item("day").Range.Text = DateTime.Now.Day.ToString();
                wordDocument.Bookmarks.get_Item("year2").Range.Text = DateTime.Now.Year.ToString();
                wordDocument.Bookmarks.get_Item("month2").Range.Text = DateTime.Now.Month.ToString();
                //wordDocument.Bookmarks.get_Item("Manager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Manager.Name;
                //wordDocument.Bookmarks.get_Item("DeviceNumber").Range.Text = memI.ConstructPlanItem.DeviceNumber;

                wordTable.Cell(1, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
                wordTable.Cell(2, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.EnglishName;
                wordTable.Cell(3, 4).Range.Text = memI.ConstructPlanItem.MemberApplyItem.Quantity.ToString();
                wordTable.Cell(3, 2).Range.Text = (memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice / 100).ToString() + "元";
                wordTable.Cell(3, 6).Range.Text = ((memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice * memI.ConstructPlanItem.MemberApplyItem.Quantity) / 100).ToString() + "元";

                wordDocument.Bookmarks.get_Item("NecessityAnalysis").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.NecessityAnalysis;
                wordTable.Cell(5, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.MainSpec;

                SaveDocument(wordDocument, wordApp, direc + "大型设备购置论证报告.doc");

                downLoad(direc + "大型设备购置论证报告.doc", "大型设备购置论证报告.doc");

                var downLoadInfo = string.Format("{0}下载设备:{1},购置论证报告", User.Name, memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName);
                BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
            }
            catch (System.Exception ex)
            {
                new PackedException("大型设备购置论证报告", ex).Hanldle();
            }
        }
Beispiel #60
-1
        private void btnMerge_Click(object sender, EventArgs e)
        {
            bool checkBox = true;
            bool sendAsCheck = true;

            //Default index values
            int primaryEmailIndex = 0;
            int cc1Index = 1;
            int cc2Index = 2;
            int cc3Index = 3;

            if (rbtnYes.Checked == true)
            {
                checkBox = isChecked(cboxConfirm);
                sendAsCheck = checkSendAsEmail(ddSendAs);

            }

            if (isPresent(txtSavePath, "Save Path") && isPresent(txtWordDoc, "Word Doc Path") && isPresent(txtExcelDoc, "Excel Path") && checkBox && sendAsCheck)
            {
                if (isWord(txtWordDoc) && isExcel(txtExcelDoc))
                {

                    try
                    {
                        string saveToPath = txtSavePath.Text.ToString() + "\\";

                        //Declare word doc stuff
                        Microsoft.Office.Interop.Word.Application application1 = new Microsoft.Office.Interop.Word.Application();
                        Microsoft.Office.Interop.Word.Document document1 = new Microsoft.Office.Interop.Word.Document();

                        //Get the Word Doc
                        string docPath = txtWordDoc.Text.ToString();

                        //application1.Visible = true;

                        //Declare excel Doc stuff
                        Microsoft.Office.Interop.Excel.Application xlApp;
                        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
                        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;

                        string excelPath = txtExcelDoc.Text.ToString();

                        object misValue = System.Reflection.Missing.Value;
                        xlApp = new Microsoft.Office.Interop.Excel.Application();
                        xlWorkBook = xlApp.Workbooks.Add(excelPath);
                        xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                        //xlApp.Visible = true;

                        DataTable sheet1 = generateDT(excelPath);

                        int rowCount = sheet1.Rows.Count;
                        int colCount = sheet1.Columns.Count;

                        //Adds dynamic fields
                        List<WordField> fields = new List<WordField>();
                        List<int> headerPositions = new List<int>();
                        for (int k = 0; k < colCount; k++)
                        {
                            fields.Add(new WordField() { field = sheet1.Rows[0][k].ToString(), positionIndex = k});

                            if (fields[k].field.Contains("PrimaryEmail")|| fields[k].field.Contains("Email"))
                            {
                                primaryEmailIndex = k;
                            }
                            if (fields[k].field.Contains("CC1"))
                            {
                                cc1Index = k;
                            }
                            if (fields[k].field.Contains("CC2"))
                            {
                                cc2Index = k;
                            }
                            if (fields[k].field.Contains("CC3"))
                            {
                                cc3Index = k;
                            }
                            foreach (string n in listRecieved)
                            {
                                if (fields[k].field.Contains(n))
                                {
                                    headerPositions.Add(k);
                                }

                            }

                        }

                        int totalEmailCount = 0;
                        for (int i = 1; i < rowCount; i++)//i, row value
                        {
                            document1 = application1.Documents.Add(docPath);

                            foreach (Microsoft.Office.Interop.Word.Field field in document1.Fields)
                            {
                                int currentCol = 0;
                                do
                                {
                                    string fieldTarget = field.Code.Text.ToString();
                                    string fieldTest = fields[currentCol].field.ToString();
                                    bool test = fieldTarget.Contains(fieldTest);
                                    if (test)//field.Code.Text.Contains(fields[currentCol].field.ToString())
                                    {
                                        field.Select();

                                        if (fieldTest == "" || String.IsNullOrEmpty(fieldTest))
                                        {
                                            application1.Selection.TypeText(" ");
                                        }
                                        else
                                        {
                                            application1.Selection.TypeText(sheet1.Rows[i][currentCol].ToString());
                                        }

                                        break;
                                    }
                                    currentCol+=1;

                                }
                                while(currentCol< colCount);

                            }
                            //Determine save format
                            string fileExtension;
                            object format = new Microsoft.Office.Interop.Word.WdSaveFormat();
                            if (rbtnPDF.Checked == true)
                            {
                                fileExtension = ".PDF";
                                format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
                            }
                            else
                            {
                                fileExtension = ".docx";
                                format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault;
                            }

                            //Name of doc
                            string rootName = "";
                            if (headerPositions.Count != listRecieved.Count)
                            {
                                rootName = listRecieved[0].ToString();
                            }

                            string docNameRaw = "";
                            foreach (int pos in headerPositions)
                            {
                                docNameRaw += sheet1.Rows[i][pos].ToString()+"_";
                            }

                            if (rootName.Length > 1)
                            {
                                docNameRaw = rootName + "_" + docNameRaw;
                            }

                            string docName = saveToPath + docNameRaw.Substring(0,docNameRaw.Length-1) + fileExtension;

                            document1.SaveAs2(FileName: docName, FileFormat: format);

                            if (rbtnYes.Checked == true)
                            {

                                    //Email stuff
                                    ApplicationClass oApp = new ApplicationClass();
                                    MailItem mailItem = (MailItem)oApp.CreateItem(OlItemType.olMailItem);

                                    Recipients oRecips = mailItem.Recipients;

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

                                    string primaryEmail = sheet1.Rows[i][primaryEmailIndex].ToString();
                                    List<string> sCCRecipsList = new List<string>();
                                    List<int> ccIndexList = new List<int>();
                                    ccIndexList.Add(cc1Index);
                                    ccIndexList.Add(cc2Index);
                                    ccIndexList.Add(cc3Index);

                                    int numofCC = Convert.ToInt16(cmbCCNumber.SelectedItem.ToString());

                                    for (int iC = 0; iC < numofCC; iC++)
                                    {
                                        sCCRecipsList.Add(sheet1.Rows[i][ccIndexList[iC]].ToString());
                                    }

                                    sToRecipsList.Add(primaryEmail);

                                    foreach (string t in sToRecipsList)
                                    {
                                        if (string.IsNullOrEmpty(t) == false && t.Length > 1)
                                        {
                                            Recipient oTORecip = oRecips.Add(t);
                                            oTORecip.Type = (int)OlMailRecipientType.olTo;
                                            oTORecip.Resolve();
                                        }

                                    }

                                    foreach (string t in sCCRecipsList)
                                    {
                                        if (string.IsNullOrEmpty(t) == false && t.Length > 1)
                                        {
                                            Recipient oCCRecip = oRecips.Add(t);
                                            oCCRecip.Type = (int)OlMailRecipientType.olCC;
                                            oCCRecip.Resolve();
                                        }

                                    }

                                    string msgBody = formatLineBreaks(txtEmailBody.Text.ToString());
                                    string subjectLine = txtEmailSubject.Text.ToString();
                                    string msg =
                                       "<html>" +
                                       "<body>" +
                                       "<p>" + msgBody + "</p> <br/>" +
                                       "<p> Sincerely,</p> <br/>" +
                                       "<p><img src='http://www.lahsa.org/images/LAHSAlogoCL.png' alt='LAHSA Logo'/></p>" +
                                       "</body>" +
                                       "</html>";
                                    mailItem.SentOnBehalfOfName = ddSendAs.SelectedValue.ToString();
                                    mailItem.HTMLBody = msg;
                                    mailItem.Subject = subjectLine;
                                    //mailItem.Attachments.Add(@"C:\Users\andrewa\Desktop\Applications Dev\mailMerge_v1\Test Docs\TestWord" + docName + ".PDF", Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, 1, @"C:\Users\andrewa\Desktop\Applications Dev\mailMerge_v1\Test Docs\TestWord" + docName + ".PDF");
                                    mailItem.Attachments.Add(docName, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, 1, docName);

                                    if (sToRecipsList[0].Length > 1 )
                                    {
                                        mailItem.Send();
                                        totalEmailCount += 1;
                                    }

                            }

                        }

                        //Alert that all emails have been sent
                        string alrtMsg = "A total of " + totalEmailCount.ToString()  + " emails have been sent, please close the application :-)";
                        MessageBox.Show(alrtMsg, "Emails Succesfully Sent!");

                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                }
            }
        }