private void SaveToWordFile(string path, string text, decimal numOfVersion, FileContent fileContent)
        {
            //Создаем новый вордовский документ
            Word.Document doc = _app.Documents.Add();
            doc.Paragraphs[1].Range.Text = text;

            for (int i = 1; i <= doc.Paragraphs.Count; ++i)
            {
                doc.Paragraphs[i].Range.Font.Name = "Times New Roman";
                doc.Paragraphs[i].Range.Font.Size = 14;
            }

            //Генерируем название документа в зависимости от его содержимого (ответы или варианты)
            string title;

            if (fileContent == FileContent.Answers)
            {
                title = path + @"\Вариант " + numOfVersion + " ответы.docx";
            }
            else
            {
                title = path + @"\Вариант " + numOfVersion + ".docx";
            }

            if (File.Exists(title) && _applyToAll == false)                                        //Если файл с таким именем уже существует
            {
                UsersConfirmForms usersConfirm = new UsersConfirmForms(numOfVersion, fileContent); //Открываем окно, в котором
                                                                                                   //спрашиваем пользователя,
                                                                                                   //что делать
                _applyToAll             = usersConfirm.ApplyToAll;
                _usersConfirmFormResult = usersConfirm.ShowDialog();

                if (_usersConfirmFormResult == DialogResult.Cancel)
                {
                    doc.Close();
                    return;
                }
            }

            if (_usersConfirmFormResult == DialogResult.No)               //Если пользователь решил сохранить оба документа
            {
                string finalTitle = setTitle(title);                      //Настраиваем название файла в зависимости от того, существуют ли файлы с таким
                                                                          //же названием
                finalTitle = finalTitle.Remove(finalTitle.Length - 5, 5); //Убираем расширение .docx из названия файла
                doc.SaveAs2(finalTitle);
            }
            else
            {
                doc.SaveAs2(title);
            }

            doc.Close();
        }
Ejemplo n.º 2
0
        private void b_save_Click(object sender, EventArgs e)
        {
            SaveFileDialog save_file_dialog = new SaveFileDialog();

            save_file_dialog.Filter = "Microsoft Word Files (*.doc)|*.doc" +
                                      "| Microsoft Word Compressed Files (*.docx)|*.docx";
            save_file_dialog.DefaultExt = "doc";
            if (save_file_dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
                save_file_dialog.FileName.Length > 0)
            {
                //Сохраняем документ
                Word.Application app = new Word.Application();
                app.Visible = false;
                Word.Document doc = app.Documents.Add();
                doc.Paragraphs[1].Range.Text = this.text_box.Text;

                for (int i = 1; i < doc.Paragraphs.Count; ++i)
                {
                    doc.Paragraphs[i].Range.Font.Name = "Times New Roman";
                    doc.Paragraphs[i].Range.Font.Size = 14;
                }

                doc.SaveAs2(save_file_dialog.FileName);
                doc.Close();
                app.Quit();
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// WPS组件
 /// </summary>
 /// <param name="sourcePath"></param>
 /// <param name="targetPath"></param>
 public void WPSWordToPdf(string sourcePath, string targetPath)
 {
     app = new Word.ApplicationClass();
     Word.Document doc = app.Documents.Open(sourcePath, Visible: false);
     doc.ExportAsFixedFormat(targetPath, Word.WdExportFormat.wdExportFormatPDF);
     doc.Close();
     app.Quit();
 }
Ejemplo n.º 4
0
        // ----------------------------------------------------
        //         Replace strings in structure
        // ----------------------------------------------------
        static public void ReplaceStringInAllFiles(
            string originalFolder,
            List <TagStructure> tagList,
            Word.Application vkWordApp)
        {
            object vkMissing  = System.Reflection.Missing.Value;
            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;

            if (Directory.Exists(originalFolder))
            {
                string[] files = Directory.GetFiles(originalFolder);
                foreach (string file in files)
                {
                    string name  = Path.GetFileName(file);
                    object xFile = file;

                    // Let's open the document
                    Word.Document vkMyDoc = vkWordApp.Documents.Open(
                        ref xFile, ref vkMissing, ref vkReadOnly,
                        ref vkMissing, ref vkMissing, ref vkMissing,
                        ref vkMissing, ref vkMissing, ref vkMissing,
                        ref vkMissing, ref vkMissing, ref vkVisible);

                    vkMyDoc.Select();

                    if (tagList.Count > 0)
                    {
                        for (int i = 0; i < tagList.Count; i++)
                        {
                            FindAndReplace(
                                tagList[i].Tag,
                                tagList[i].TagValue,
                                1,
                                vkWordApp,
                                vkMyDoc);
                        }
                    }

                    WordDocumentTasks.insertPicture(vkMyDoc, "C:\\Research\\fcm\\Resources\\FCMLogo.jpg", "");
                    vkMyDoc.Save();
                    vkMyDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing);
                }

                //
                //  Replace in all folders
                //
                string[] folders = Directory.GetDirectories(originalFolder);
                foreach (string folder in folders)
                {
                    ReplaceStringInAllFiles(folder,
                                            tagList,
                                            vkWordApp);
                }
            }
        }
Ejemplo n.º 5
0
		/// <summary>
		/// catches Word's newdocument event
		/// just close
		/// </summary>
		/// <param name="doc"></param>
		private void OnNewDoc(Word.Document doc)
		{
			if(!deactivateevents)
			{
				deactivateevents=true;
				object dummy = null;
				doc.Close(ref dummy,ref dummy,ref dummy);
				deactivateevents=false;
			}
		}
Ejemplo n.º 6
0
    public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks)
    {
        Word._Application wordApplication = new Word.Application();
        object            pageBreak       = Word.WdBreakType.wdSectionBreakContinuous;
        object            outputFile      = outputFilename;
        object            fileName        = @"S:\ODS\Insight 2 Oncology\Quality Division Project\Visual Review Scores\Scoring Template\MergeTemplate.docx";
        object            end             = Word.WdCollapseDirection.wdCollapseEnd;

        try
        {
            wordApplication.Visible = false;
            Word.Document  wordDocument = wordApplication.Documents.Add(ref fileName);
            Word.Selection selection    = wordApplication.Selection;

            foreach (string file in filesToMerge)
            {
                if (file.Contains("Scores.docx"))
                {
                    selection.PageSetup.PaperSize   = Word.WdPaperSize.wdPaper11x17;
                    selection.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
                    selection.InsertFile(file);
                    selection.Collapse(ref end);
                }
                if (!file.Contains("Scores.docx") && insertPageBreaks)
                {
                    selection.InsertFile(file);
                    selection.InsertBreak(pageBreak);
                }
            }
            wordApplication.Selection.Document.Content.Select();
            wordDocument.PageSetup.TopMargin          = (float)50;
            wordDocument.PageSetup.RightMargin        = (float)50;
            wordDocument.PageSetup.LeftMargin         = (float)50;
            wordDocument.PageSetup.BottomMargin       = (float)50;
            selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            selection.ParagraphFormat.SpaceAfter      = 0.0F;
            selection.ParagraphFormat.SpaceBefore     = 0.0F;
            wordDocument.SaveAs(outputFile + ".docx");
            wordDocument.Close();
            wordDocument = wordApplication.Documents.Open(outputFile + ".docx");
            wordDocument.ExportAsFixedFormat(outputFile + ".pdf", Word.WdExportFormat.wdExportFormatPDF);
            wordDocument = null;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            wordApplication.Quit();
        }
    }
Ejemplo n.º 7
0
        public void Quit( )
        {
            object missing = System.Reflection.Missing.Value;

            if (oDoc != null)
            {
                oDoc.Close(ref missing, ref missing, ref missing);
                oDoc = null;
            }
            if (oWordApplic != null)
            {
                oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
                oWordApplic = null;
            }
        }
Ejemplo n.º 8
0
        // ---------------------------------------------
        //             Copy Documents
        // ---------------------------------------------
        public static object CopyDocument(
            object fromFileName,
            object destinationFileName,
            List <WordDocumentTasks.TagStructure> tag
            )
        {
            Word.Application vkWordApp =
                new Word.Application();

            object saveFile = destinationFileName;

            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;

            object vkMissing = System.Reflection.Missing.Value;

            // Let's make the word application visible
            vkWordApp.Visible = true;
            vkWordApp.Activate();

            // Let's copy the document
            File.Copy(fromFileName.ToString(), destinationFileName.ToString(), true);

            // Let's open the DESTINATION document
            Word.Document vkMyDoc = vkWordApp.Documents.Open(
                ref destinationFileName, ref vkMissing, ref vkReadOnly,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkVisible);

            foreach (var t in tag)
            {
                FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc);
            }

            vkMyDoc.Save();

            // close the new document
            vkMyDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing);

            // close word application
            vkWordApp.Quit(ref vkFalse, ref vkMissing, ref vkMissing);

            return(saveFile);
        }
Ejemplo n.º 9
0
 public void CloseControl()
 {
     try
     {
         deactivateevents = true;
         object dummy  = null;
         object dummy2 = (object)false;
         document.Close(ref dummy, ref dummy, ref dummy);
         // Change the line below.
         wd.Quit(ref dummy2, ref dummy, ref dummy);
         deactivateevents = false;
     }
     catch (Exception ex)
     {
         String strErr = ex.Message;
     }
 }
Ejemplo n.º 10
0
        //Метод, сохраняющий текст в вордовский файл
        private void SaveToWordFile(string file_name, string text)
        {
            //Открываем ворд на фоне
            Word.Application app = new Word.Application();
            app.Visible = false;
            Word.Document doc = app.Documents.Add();
            doc.Paragraphs[1].Range.Text = text;

            for (int i = 1; i < doc.Paragraphs.Count; ++i)
            {
                doc.Paragraphs[i].Range.Font.Name = "Times New Roman";
                doc.Paragraphs[i].Range.Font.Size = 14;
            }

            doc.SaveAs2(file_name);
            doc.Close();
            app.Quit();
        }
Ejemplo n.º 11
0
		/// <summary>
		/// Close the current Document in the control --> you can 
		/// load a new one with LoadDocument
		/// </summary>
		public void CloseControl()
		{
			/*
			* this code is to reopen Word.
			*/
		
			try
			{
				deactivateevents = true;
				object dummy=null;
				document.Close(ref dummy, ref dummy, ref dummy);
				document.Application.Quit(ref dummy, ref dummy, ref dummy);
				deactivateevents = false;
			}
			catch 
			{
			}
		}
Ejemplo n.º 12
0
        private void btnYazdır_Click(object sender, EventArgs e)
        {
            try
            {
                Word.Application WordApp = new Word.Application();
                Word.Document    WordDoc = new Word.Document();

                DataSet ds = new DataSet();
                if (baglantı.State == ConnectionState.Closed)
                {
                    baglantı.Open();
                }

                OleDbCommand    komut  = new OleDbCommand("Select YazarAdi,KitapAdi from kitaplar", baglantı);
                OleDbDataReader reader = komut.ExecuteReader();

                WordDoc         = WordApp.Documents.Open(Application.StartupPath + "\\bos_kitaplar.docx");
                WordApp.Visible = true;
                int i = 2;
                while (reader.Read())
                {
                    WordDoc.Range().Tables[1].Cell(i, 1).Range.InsertAfter(reader["YazarAdi"].ToString());
                    WordDoc.Range().Tables[1].Cell(i, 2).Range.InsertAfter(reader["KitapAdi"].ToString());
                    WordDoc.Range().Tables[1].Rows.Add();
                    i++;
                }
                WordDoc.SaveAs(Application.StartupPath + "\\tum_kitaplar" + ".doc");
                WordDoc.Close();
                WordApp.Quit();

                WordDoc = null;
                WordApp = null;

                MessageBox.Show("Sorular WORD'a aktarıldı!");
                baglantı.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                baglantı.Close();
            }
        }
Ejemplo n.º 13
0
        /*
         *
         * http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx
         * 9.1 Embedding Pictures in Document Header:
         *
         * //EMBEDDING LOGOS IN THE DOCUMENT
         * //SETTING FOCUES ON THE PAGE HEADER TO EMBED THE WATERMARK
         * oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
         *
         * //THE LOGO IS ASSIGNED TO A SHAPE OBJECT SO THAT WE CAN USE ALL THE
         * //SHAPE FORMATTING OPTIONS PRESENT FOR THE SHAPE OBJECT
         * Word.Shape logoCustom = null;
         *
         * //THE PATH OF THE LOGO FILE TO BE EMBEDDED IN THE HEADER
         * String logoPath = "C:\\Document and Settings\\MyLogo.jpg";
         * logoCustom = oWord.Selection.HeaderFooter.Shapes.AddPicture(logoPath,
         * ref oFalse, ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
         *
         * logoCustom.Select(ref oMissing);
         * logoCustom.Name = "CustomLogo";
         * logoCustom.Left = (float)Word.WdShapePosition.wdShapeLeft;
         *
         * //SETTING FOCUES BACK TO DOCUMENT
         * oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
         *
         */


        public static void CompareDocuments(object fromFileName, string toFileName)
        {
            if (!File.Exists((string)fromFileName))
            {
                MessageBox.Show("File not found. " + fromFileName);
                return;
            }


            Word.Application vkWordApp =
                new Word.Application();

            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;


            object vkMissing = System.Reflection.Missing.Value;

            // Let's make the word application visible
            vkWordApp.Visible = true;
            vkWordApp.Activate();

            // Let's open the document
            Word.Document vkMyDoc = vkWordApp.Documents.Open(
                ref fromFileName, ref vkMissing, ref vkReadOnly,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkVisible);

            vkMyDoc.Compare(toFileName);

            vkMyDoc.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc);

            vkWordApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(vkWordApp);

            return;
        }
Ejemplo n.º 14
0
        private Boolean word_exec(OfficeDomain office)
        {
            Boolean result = false;

            if (Array.IndexOf(word, office.prefix) > -1)
            {
                log("word开始工作...");
                Word.Document doc = null;
                try
                {
                    //打开,参数含义:路径、格式不兼容不警告、只读
                    doc = wordApp.Documents.Open(office.path, false, true);
                    //转换
                    doc.ExportAsFixedFormat(office.pdfFileName, Word.WdExportFormat.wdExportFormatPDF);
                    result = true;
                    log("word工作完毕,准备关闭文件..");
                }
                catch (Exception e)
                {
                    error("word工作异常:{0}", e.Message);
                }
                finally
                {
                    if (doc != null)
                    {
                        try
                        {
                            doc.Close();
                            log("word文件成功关闭..");
                        }
                        catch (Exception e)
                        {
                            error("word文件关闭时发生错误{1},重启{0}.exe", word_name, e.Message);
                            word_start();
                        }
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Close the current Document in the control --> you can
 /// load a new one with LoadDocument
 /// </summary>
 public void CloseControl()
 {
     /*
      * this code is to reopen Word.
      */
     try
     {
         deactivateevents = true;
         object dummy  = null;
         object dummy2 = (object)false;
         WordDoc.Close(ref dummy, ref dummy, ref dummy);
         // Change the line below.
         WordApplication.Quit(ref dummy2, ref dummy, ref dummy);
         deactivateevents = false;
     }
     catch (Exception ex)
     {
         String strErr = ex.Message;
     }
     finally
     {
         this.KillWordProcess(OldWordProcess, NewWordProcess);
     }
 }
Ejemplo n.º 16
0
        // ---------------------------------------------
        //             Copy Documents
        // ---------------------------------------------
        public static object CopyDocumentReplaceContents(
            object fromFileName,
            object destinationFileName,
            List <WordDocumentTasks.TagStructure> tag
            )
        {
            Word.Application vkWordApp =
                new Word.Application();

            object saveFile = destinationFileName;

            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;


            object vkMissing = System.Reflection.Missing.Value;

            // Let's make the word application visible
            vkWordApp.Visible = true;
            vkWordApp.Activate();

            // Let's open the document
            Word.Document vkMyDoc = vkWordApp.Documents.Open(
                ref fromFileName, ref vkMissing, ref vkReadOnly,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkVisible);

            // Let's create a new document
            Word.Document vkNewDoc = vkWordApp.Documents.Add(
                ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkVisible);

            // Select and Copy from the original document
            vkMyDoc.Select();
            vkWordApp.Selection.Copy();

            // Paste into new document as unformatted text
            vkNewDoc.Select();
            vkWordApp.Selection.PasteSpecial(ref vkMissing, ref vkFalse,
                                             ref vkMissing, ref vkFalse, ref vkDynamic,
                                             ref vkMissing, ref vkMissing);

            // Save the new document
            vkNewDoc.SaveAs(ref saveFile, ref vkMissing,
                            ref vkMissing, ref vkMissing, ref vkMissing,
                            ref vkMissing, ref vkMissing, ref vkMissing,
                            ref vkMissing, ref vkMissing, ref vkMissing);


            // Copy elements
            // FromString => toString
            //
            // underdevelopment
            //
            vkNewDoc.Select();

            foreach (var t in tag)
            {
                FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc);
            }

            vkNewDoc.Save();

            // close the new document
            vkNewDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing);

            // close the original document
            vkMyDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing);

            // close word application
            vkWordApp.Quit(ref vkFalse, ref vkMissing, ref vkMissing);

            return(saveFile);
        }
Ejemplo n.º 17
0
        public void ExportData(DataGridView srcDgv, string fileName)           //导出数据,传入一个datagridview和一个文件路径
        {
            string type = fileName.Substring(fileName.IndexOf(".") + 1);       //获得数据类型

            if (type.Equals("xls", StringComparison.CurrentCultureIgnoreCase)) //Excel文档
            {
                Excel.Application excel = new Excel.Application();
                try
                {
                    excel.DisplayAlerts = false;
                    excel.Workbooks.Add(true);
                    excel.Visible = false;

                    for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
                    {
                        excel.Cells[2, i + 1] = srcDgv.Columns[i].HeaderText;
                    }

                    for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
                    {
                        for (int j = 0; j < srcDgv.Columns.Count; j++)
                        {
                            if (srcDgv[j, i].ValueType.ToString() == "System.Byte[]")
                            {
                                excel.Cells[i + 3, j + 1] = "System.Byte[]";
                            }
                            else
                            {
                                excel.Cells[i + 3, j + 1] = srcDgv[j, i].Value;
                            }
                        }
                    }

                    excel.Workbooks[1].SaveCopyAs(fileName);//保存
                }
                finally
                {
                    excel.Quit();
                }
                return;
            }
            //保存Word文件
            if (type.Equals("doc", StringComparison.CurrentCultureIgnoreCase))
            {
                object           path     = fileName;
                Object           none     = System.Reflection.Missing.Value;
                Word.Application wordApp  = new Word.Application();
                Word.Document    document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
                //建立表格
                Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count + 1, srcDgv.Columns.Count, ref none, ref none);
                try
                {
                    for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
                    {
                        table.Cell(1, i + 1).Range.Text = srcDgv.Columns[i].HeaderText;
                    }

                    for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
                    {
                        for (int j = 0; j < srcDgv.Columns.Count; j++)
                        {
                            string a = srcDgv[j, i].ValueType.ToString();
                            if (a == "System.Byte[]")
                            {
                                PictureBox   pp  = new PictureBox();
                                byte[]       pic = (byte[])(srcDgv[j, i].Value); //将数据库中的图片转换成二进制流
                                MemoryStream ms  = new MemoryStream(pic);        //将字节数组存入到二进制流中
                                pp.Image = Image.FromStream(ms);                 //二进制流Image控件中显示
                                pp.Image.Save(@"C:\22.bmp");                     //将图片存入到指定的路径
                                object aaa = table.Cell(i + 2, j + 1).Range;
                                wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                                wordApp.Selection.InlineShapes.AddPicture(@"C:\22.bmp", ref none, ref none, ref aaa);
                                pp.Dispose();
                            }
                            else
                            {
                                table.Cell(i + 2, j + 1).Range.Text = srcDgv[j, i].Value.ToString();
                            }
                        }
                    }
                    document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                    document.Close(ref none, ref none, ref none);
                    if (File.Exists(@"C:\22.bmp"))
                    {
                        File.Delete(@"C:\22.bmp");
                    }
                }
                finally
                {
                    wordApp.Quit(ref none, ref none, ref none);
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 动态创建table到word
        /// </summary>
        protected void CreateTableToExcel()
        {
            Word.Application app = null;
            Word.Document    doc = null;
            try
            {
                //构造数据
                List <Student> datas = new List <Student>();
                datas.Add(new Student {
                    Leader = "小李", Name = "张三", Score = 498, StuClass = "一班"
                });
                datas.Add(new Student {
                    Leader = "陈飞", Name = "李四", Score = 354, StuClass = "二班"
                });
                datas.Add(new Student {
                    Leader = "陈飞", Name = "小红", Score = 502, StuClass = "二班"
                });
                datas.Add(new Student {
                    Leader = "王林", Name = "丁爽", Score = 566, StuClass = "三班"
                });
                var cate = datas.GroupBy(s => s.StuClass);

                int    rows     = cate.Count() + 1; //表格行数加1是为了标题栏
                int    cols     = 5;                //表格列数
                object oMissing = System.Reflection.Missing.Value;
                app = new Word.Application();       //创建word应用程序
                doc = app.Documents.Add();          //添加一个word文档

                //输出大标题加粗加大字号水平居中
                app.Selection.Font.Bold = 700;
                app.Selection.Font.Size = 16;
                app.Selection.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                app.Selection.Text = "班级成绩统计单";

                //换行添加表格
                object line = Word.WdUnits.wdLine;
                app.Selection.MoveDown(ref line, oMissing, oMissing);
                app.Selection.TypeParagraph();//换行
                Word.Range range = app.Selection.Range;
                Word.Table table = app.Selection.Tables.Add(range, rows, cols, ref oMissing, ref oMissing);

                //设置表格的字体大小粗细
                table.Range.Font.Size = 10;
                table.Range.Font.Bold = 0;

                //设置表格标题
                int rowIndex = 1;
                table.Cell(rowIndex, 1).Range.Text = "班级";
                table.Cell(rowIndex, 2).Range.Text = "姓名";
                table.Cell(rowIndex, 3).Range.Text = "成绩";
                table.Cell(rowIndex, 4).Range.Text = "人数";
                table.Cell(rowIndex, 5).Range.Text = "班主任";

                //循环数据创建数据行
                rowIndex++;
                foreach (var i in cate)
                {
                    table.Cell(rowIndex, 1).Range.Text = i.Key;                //班级
                    table.Cell(rowIndex, 4).Range.Text = i.Count().ToString(); //人数
                    table.Cell(rowIndex, 5).Range.Text = i.First().Leader;     //班主任
                    table.Cell(rowIndex, 2).Split(i.Count(), 1);               //分割名字单元格
                    table.Cell(rowIndex, 3).Split(i.Count(), 1);               //分割成绩单元格

                    //对表格中的班级、姓名,成绩单元格设置上下居中
                    table.Cell(rowIndex, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    table.Cell(rowIndex, 4).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    table.Cell(rowIndex, 5).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                    //构建姓名,成绩数据
                    foreach (var x in i)
                    {
                        table.Cell(rowIndex, 2).Range.Text = x.Name;
                        table.Cell(rowIndex, 3).Range.Text = x.Score.ToString();
                        rowIndex++;
                    }
                }

                //导出到文件
                string newFile       = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";
                string physicNewFile = Server.MapPath(newFile);
                doc.SaveAs(physicNewFile,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭文档
                }
                if (app != null)
                {
                    app.Quit();//退出应用程序
                }
            }
        }
Ejemplo n.º 19
0
        private void btn_start_Click(object sender, EventArgs e)
        {
            //check if template exists
            if (ofd_template.FileName.Length == 0)
            {
                MessageBox.Show("first choose a doc word");
                return;
            }

            // check empty table
            if (dgv_data.Rows.Count == 0)
            {
                MessageBox.Show("table is empty"); return;
            }

            //check row contents
            int base_vle = -1;

            for (int i = 0; i < dgv_data.Rows.Count - 1; i++)
            {
                if (base_vle == -1)
                {
                    base_vle = Convert.ToInt32(dgv_data.Rows[i].Cells[2].Value);
                }
                else
                {
                    int this_vle = Convert.ToInt32(dgv_data.Rows[i].Cells[2].Value);;
                    if (this_vle != base_vle)
                    {
                        MessageBox.Show("content rows are not same!");
                        return;
                    }
                }
            }

            Directory.CreateDirectory("export/");
            if (Directory.GetFiles("export/").Length > 0)
            {
                MessageBox.Show("first empty export folder"); return;
            }

            progressBar1.Maximum = base_vle;
            progressBar1.Value   = 0;
            for (int i = 0; i < base_vle; i++)
            {
                progressBar1.Value = i + 1;

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

                Word.Document aDoc = null;


                wordApp.Visible = false;


                File.Copy(ofd_template.FileName, "export/" + i + ".docx");

                aDoc = wordApp.Documents.Open(System.Windows.Forms.Application.StartupPath + "/export/" + i + ".docx");


                aDoc.Activate();


                //  Call FindAndReplace()function for each change
                for (int ii = 0; ii < dgv_data.RowCount - 1; ii++)
                {
                    string   this_tag = dgv_data.Rows[ii].Cells[0].Value.ToString();
                    string[] contents = dic_data[this_tag];

                    this.FindAndReplace(wordApp, this_tag, contents[i]);
                }


                aDoc.Save();
                aDoc.Close();
            }
            MessageBox.Show("done!");
        }
Ejemplo n.º 20
0
        /// <summary>
        /// cover file word to body hmtl of mail,which embed fictures
        /// </summary>
        /// <param name="PathWordTemplate">path to word template file</param>
        /// <param name="Mail">Mail is embed body</param>
        /// <returns></returns>
        private static bool HTMLBody(DataSet DataFill, string PathWordTemplate, ref Email Mail)
        {
            string path = FrameworkParams.TEMP_FOLDER + @"\WordTemp";
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);
            path += PathWordTemplate.Substring(PathWordTemplate.LastIndexOf("\\"));
            WordDocument WordDoc = new WordDocument();
            try
            {
                WordDoc.Open(PathWordTemplate);
                for (int i = 0; i < DataFill.Tables.Count; i++)
                {
                    WordDoc.MailMerge.ExecuteGroup(DataFill.Tables[i]);
                }
                WordDoc.Save(path);

                Word.ApplicationClass wd = new Word.ApplicationClass();
                Word.Document document = new Word.Document();
                object fileName = (object)path;
                object newTemplate = false;
                object docType = 0;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;

                document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);

                object oFileName = (object)(path.Substring(0, path.LastIndexOf(".")) + ".html");
                object oSaveFormat = (object)(Word.WdSaveFormat.wdFormatHTML);

                if (System.IO.File.Exists(oFileName.ToString()))
                    System.IO.File.Delete(oFileName.ToString());

                document.SaveAs(ref oFileName,
                                ref oSaveFormat,
                                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);
                wd.Quit(ref missing, ref missing, ref missing);

                Mht mailbody = new Mht();
                mailbody.UnlockComponent("MHT-TEAMBEAN_1E1F4760821H");
                mailbody.UseCids = true;
                Mail = mailbody.GetEmail(oFileName.ToString());

                return true;
            }
            catch
            {
                return false;
            }
        }
Ejemplo n.º 21
0
        private string GetDocumentText(object path, int tryCount)
        {
            if (tryCount++ > 1)
            {
                return(string.Empty);
            }
            Word.Documents documents = null;
            try
            {
                if (_MSWord == null)
                {
                    if (!LoadWordInstance())
                    {
                        return(string.Empty);
                    }
                }
                documents = _MSWord.Documents;
            }
            catch (InvalidCastException exception)
            {
                _tracer.TraceException(exception);
                return(GetDocumentTextWithReloadingWord(path, tryCount));
            }
            catch (System.Runtime.InteropServices.COMException exception)
            {
                _tracer.TraceException(exception);
                if (IsReloadingPossible(exception))
                {
                    return(GetDocumentTextWithReloadingWord(path, tryCount));
                }
                return(string.Empty);
            }
            catch (Exception exception)
            {
                _tracer.TraceException(exception);
                return(string.Empty);
            }

            Word.Document doc      = null;
            string        bodyText = string.Empty;
            object        pass     = "******";

            try
            {
                DisableAutomationSecurity();
                doc = documents.Open(ref path, ref FALSE, ref TRUE, ref FALSE,
                                     ref pass,
                                     ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
                                     ref MissingValue,
                                     ref MissingValue, ref MissingValue);

                Word.Range range = doc.Content;
                bodyText = range.Text;
            }
            catch (System.Runtime.InteropServices.COMException exception)
            {
                _tracer.TraceException(exception);
                if (IsReloadingPossible(exception))
                {
                    _tracer.Trace("Try to load new instance of MS Word");
                    return(GetDocumentTextWithReloadingWord(path, tryCount));
                }
                if (COM_Error.CouldNotOpenMacroStorage(exception))     //This exception leads to not closed documents
                {
                    LoadWordInstance();
                    return(string.Empty);
                }
            }
            catch (InvalidCastException exception)
            {
                _tracer.TraceException(exception);
                return(GetDocumentTextWithReloadingWord(path, tryCount));
            }
            catch (Exception exception)
            {
                _tracer.TraceException(exception);
                return(string.Empty);
            }
            RestoreAutomationSecurity();

            try
            {
                if (doc != null)
                {
                    doc.Close(ref FALSE, ref MissingValue, ref MissingValue);
                }
                return(bodyText);
            }
            catch (System.Runtime.InteropServices.COMException exception)
            {
                if (IsReloadingPossible(exception))
                {
                    return(GetDocumentTextWithReloadingWord(path, tryCount));
                }
            }
            catch (InvalidCastException exception)
            {
                _tracer.TraceException(exception);
                return(GetDocumentTextWithReloadingWord(path, tryCount));
            }
            catch (Exception exception)
            {
                _tracer.TraceException(exception);
            }
            return(string.Empty);
        }
Ejemplo n.º 22
0
Archivo: UIfcm.cs Proyecto: DR2010/FCM2
        /// <summary>
        /// Get source document. Open a FileDialog window for user to select single/multiple files for
        /// parsing.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butSourceDocument_Click(object sender, System.EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                object fileName = openFileDialog.FileName;
                object saveFile = fileName + "_Vk.doc";


                object vk_read_only = false;
                object vk_visible   = true;
                object vk_false     = false;
                object vk_true      = true;
                object vk_dynamic   = 2;


                object vk_missing = System.Reflection.Missing.Value;

                // Let make the word application visible
                vk_word_app.Visible = true;
                vk_word_app.Activate();

                // Let's open the document
                Word.Document vk_my_doc = vk_word_app.Documents.Open(ref fileName,
                                                                     ref vk_missing, ref vk_read_only, ref vk_missing, ref vk_missing,
                                                                     ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing,
                                                                     ref vk_missing, ref vk_missing, ref vk_visible);

                // Let's create a new document
                Word.Document vk_new_doc = vk_word_app.Documents.Add(ref vk_missing,
                                                                     ref vk_missing, ref vk_missing, ref vk_visible);

                // Select and Copy from the original document
                vk_my_doc.Select();
                vk_word_app.Selection.Copy();

                // Paste into new document as unformatted text
                vk_new_doc.Select();
                vk_word_app.Selection.PasteSpecial(ref vk_missing, ref vk_false,
                                                   ref vk_missing, ref vk_false, ref vk_dynamic, ref vk_missing, ref vk_missing);

                // close the original document
                vk_my_doc.Close(ref vk_false, ref vk_missing, ref vk_missing);

                // Let try to replace Vahe with VAHE in the new document
                object vk_find    = "^l";
                object vk_replace = " ";
                object vk_num     = 1;

                vk_new_doc.Select();

                WordDocumentTasks.FindAndReplace(
                    "<<Client Name>>",
                    "tEST",
                    vk_num,
                    vk_word_app);

                // Save the new document
                vk_new_doc.SaveAs(ref saveFile, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing,
                                  ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing);

                // close the new document
                vk_new_doc.Close(ref vk_false, ref vk_missing, ref vk_missing);

/*
 *                              // Let's get the content from the document
 *                              Word.Paragraphs vk_my_doc_p = vk_new_doc.Paragraphs;
 *                              // Count number of paragraphs in the file
 *                              long p_count = vk_my_doc_p.Count;
 *                              // step through the paragraphs
 *                              for( int i=1; i<=p_count; i++ )
 *                              {
 *                                      Word.Paragraph vk_p = vk_my_doc_p.Item( i );
 *                                      Word.Range vk_r = vk_p.Range;
 *                                      string text = vk_r.Text;
 *
 *                                      MessageBox.Show( text );
 *                              }
 */


                // close word application
                vk_word_app.Quit(ref vk_false, ref vk_missing, ref vk_missing);
            }
        }