private void btn_Read_Click(object sender, EventArgs e)
        {
            object missing = System.Reflection.Missing.Value;                                                 //获取缺少的object类型值

            string[] P_str_Names = txt_Excel.Text.Split(',');                                                 //存储所有选择的Excel文件名
            object   P_obj_Name;                                                                              //存储遍历到的Excel文件名

            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); //实例化Word对象
            if (txt_Word.Text.EndsWith("\\"))                                                                 //判断路径是否以\结尾
            {
                P_obj_WordName = txt_Word.Text + DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc";            //记录Word文件路径及名称
            }
            else
            {
                P_obj_WordName = txt_Word.Text + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc";   //记录Word文件路径及名称
            }
            Microsoft.Office.Interop.Word.Table    table;                                                   //声明Word表格对象
            Microsoft.Office.Interop.Word.Document document = new Microsoft.Office.Interop.Word.Document(); //声明Word文档对象
            document = word.Documents.Add(ref missing, ref missing, ref missing, ref missing);              //新建Word文档
            Microsoft.Office.Interop.Word.Range range;                                                      //声明范围对象
            int    P_int_Rows = 0, P_int_Columns = 0;                                                       //存储工作表中数据的行数和列数
            object P_obj_start = 0, P_obj_end = 0;                                                          //分别记录创建表格的开始和结束范围
            object P_obj_Range = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd;           //定义要合并的范围位置

            for (int i = 0; i < P_str_Names.Length - 1; i++)                                                //遍历所有选择的Excel文件名
            {
                P_obj_Name = P_str_Names[i];                                                                //记录遍历到的Excel文件名
                List <string> P_list_SheetName = CBoxBind(P_obj_Name.ToString());                           //获取指定Excel中的所有工作表
                for (int j = 0; j < P_list_SheetName.Count; j++)                                            //遍历所有工作表
                {
                    range = document.Range(ref missing, ref missing);                                       //获取Word范围
                    range.InsertAfter(P_obj_Name + "——" + P_list_SheetName[j] + "工作表");                     //插入文本
                    range.Font.Name = "宋体";                                                                 //设置字体
                    range.Font.Size = 10;                                                                   //设置字体大小
                    DataSet myds = CBoxShowCount(P_obj_Name.ToString(), P_list_SheetName[j]);               //获取工作表中的所有数据
                    P_int_Rows    = myds.Tables[0].Rows.Count;                                              //记录工作表的行数
                    P_int_Columns = myds.Tables[0].Columns.Count;                                           //记录工作表的列数
                    range.Collapse(ref P_obj_Range);                                                        //合并范围
                    if (P_int_Rows > 0 && P_int_Columns > 0)                                                //判断如果工作表中有记录
                    {
                        //在指定范围处添加一个指定行数和列数的表格
                        table = range.Tables.Add(range, P_int_Rows, P_int_Columns, ref missing, ref missing);
                        for (int r = 0; r < P_int_Rows; r++)                                                      //遍历行
                        {
                            for (int c = 0; c < P_int_Columns; c++)                                               //遍历列
                            {
                                table.Cell(r + 1, c + 1).Range.InsertAfter(myds.Tables[0].Rows[r][c].ToString()); //将遍历到的数据添加到Word表格中
                            }
                        }
                    }
                    object P_obj_Format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument; //定义Word文档的保存格式
                    word.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;      //设置保存时不显示对话框
                    //保存Word文档
                    document.SaveAs(ref P_obj_WordName, ref P_obj_Format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                }
            }
            document.Close(ref missing, ref missing, ref missing); //关闭Word文档
            word.Quit(ref missing, ref missing, ref missing);      //退出Word应用程序
            MessageBox.Show("已经成功将多个Excel文件的内容读取到了一个Word文档中!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Beispiel #2
0
        public void readDocFile()
        {
            //VS 2010 ta dùng Application chứ không dùng ApplicationClass.
            // Tạo một thể hiện của ứng dụng MS Word.
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            // Các tham số được sử dụng trong hàm Open được hỗ trợ bởi thư viện API của MS Word
            object fileName     = duongdan; //path là đường dẫn đến file cần đọc
            object missing      = System.Reflection.Missing.Value;
            object vk_read_only = false;
            object vk_visible   = true;
            object vk_false     = false;

            // không sử dụng các thông số không cần thiết ngoai trừ đường dẫn đến file cần mở
            Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref fileName, ref missing,
                                                                                ref vk_read_only, ref missing,
                                                                                ref missing, ref missing,
                                                                                ref missing, ref missing,
                                                                                ref missing, ref missing,
                                                                                ref missing, ref vk_visible,
                                                                                ref missing, ref missing,
                                                                                ref missing, ref missing);

            doc.ActiveWindow.Selection.WholeStory();
            doc.ActiveWindow.Selection.Copy();
            IDataObject data = Clipboard.GetDataObject();

            rtbinfo.Text = data.GetData(DataFormats.UnicodeText).ToString();//hiển thị dữ liệu lên RichTextBox

            if (doc != null)
            {
                doc.Close(ref vk_false, ref missing, ref missing);
            }
            wordApp.Quit(ref vk_false, ref missing, ref missing);
        }
Beispiel #3
0
        public void readFileForContacts()
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss         = System.Reflection.Missing.Value;
            object path         = @"D:\Entergy-Files\doc\pxwhgen.doc";
            object readOnly     = true;
            bool   printMessage = false;

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

            for (int i = 0; i < docs.Paragraphs.Count; i++)
            {
                if (printMessage == true)
                {
                    Console.WriteLine(totaltext);
                }
                totaltext = docs.Paragraphs[i + 1].Range.Text.ToString();
                if (totaltext.Contains("SUBSYSTEM") || (totaltext.Contains("JOB FAILURE")))
                {
                    Console.WriteLine(totaltext);
                    printMessage = true;
                }
                else
                {
                    printMessage = false;
                }
            }
            //Console.WriteLine(totaltext);
            docs.Close();
            word.Quit();
        }
Beispiel #4
0
        public ActionResult Upload(List <HttpPostedFileBase> fileData)
        {
            string fileDestination = Server.MapPath("~/Uploads/");

            foreach (HttpPostedFileBase postedFile in fileData)
            {
                if (postedFile != null)
                {
                    string fileName = Path.GetFileName(postedFile.FileName);
                    string path     = fileDestination + fileName;
                    postedFile.SaveAs(path);

                    object pathObject = path;
                    Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                    object miss     = System.Reflection.Missing.Value;
                    object readOnly = true;
                    Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref pathObject, ref miss, ref readOnly, ref miss, ref miss,
                                                                                      ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                    string totaltext = "";
                    for (int i = 0; i < docs.Paragraphs.Count; i++)
                    {
                        totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
                    }
                    documentService.Add(fileName, totaltext, User.Identity.Name);

                    docs.Close();
                    word.Quit();
                }
            }

            return(Content("Success"));
        }
Beispiel #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            object missing = System.Reflection.Missing.Value;

            document = win_word.Documents.Add(filepath, false, ref missing, ref missing);

            for (int i = 0; i < labels.Count; i++)
            {
                string book_name  = labels[i].Text;
                string book_value = texts[i].Text;

                document.Bookmarks[book_name].Select();
                win_word.Selection.TypeText(book_value);
            }

            object copies   = "1";
            object pages    = "";
            object range    = Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintAllDocument;
            object items    = Microsoft.Office.Interop.Word.WdPrintOutItem.wdPrintDocumentContent;
            object pageType = Microsoft.Office.Interop.Word.WdPrintOutPages.wdPrintAllPages;
            object oTrue    = true;
            object oFalse   = false;

            document.PrintOut(ref oTrue, ref oFalse, ref range, ref missing, ref missing, ref missing,
                              ref items, ref copies, ref pages, ref pageType, ref oFalse, ref oTrue,
                              ref missing, ref oFalse, ref missing, ref missing, ref missing, ref missing);

            document.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges, ref missing, ref missing);
            document = null;
        }
        /// <summary>
        /// 读取word内容
        /// </summary>
        /// <param name="docpath">word文档路径</param>
        /// <returns></returns>
        public void DealWord(string docpath)
        {
            string moreThanCharacter = "Evaluation Only. Created with Aspose.Words. Copyright 2003-2014 Aspose Pty Ltd.";

            //实例化COM
            Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            object fileobj = docpath;
            object nullobj = System.Reflection.Missing.Value;

            //打开指定文件(不同版本的COM参数个数有差异,一般而言除第一个外都用nullobj就行了)
            Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref fileobj, ref nullobj, ref nullobj,
                                                                                ref nullobj, ref nullobj, ref nullobj,
                                                                                ref nullobj, ref nullobj, ref nullobj,
                                                                                ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
            foreach (Microsoft.Office.Interop.Word.Shape shape in doc.Shapes)
            {
                if (shape.Name.Equals(moreThanCharacter))
                {
                    shape.Delete();
                    break;
                }
            }

            //取得doc文件中的文本
            // string outText = doc.Content.Text;
            //关闭文件
            doc.Close(ref nullobj, ref nullobj, ref nullobj);
            //关闭COM
            wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
            //返回
            // return outText;
        }
        public string ReadMsword(string filePath)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

            try
            {
                object miss = System.Reflection.Missing.Value;
                object path = filePath;
                //lbWordDocs.Items.Add(filePath);
                //rtbox.Text()
                object readOnly = false;
                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);
                docs.ActiveWindow.Selection.WholeStory();
                docs.ActiveWindow.Selection.Copy();
                data = Clipboard.GetDataObject();
                //rtbox.Text = (string)(data.GetData(DataFormats.Text));
                docs.Close(ref miss, ref miss, ref miss);
                word.Quit(ref miss, ref miss, ref miss);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(word);
            }

            //return (data.GetData(DataFormats.Text).ToString());
            return(data.GetData(DataFormats.Text).ToString());
        }
Beispiel #8
0
        //TODO: REFACTOR!
        private void loadWordFile(FileInfo wordFile)
        {
            object filename  = wordFile.FullName;
            object readOnly  = false;
            object isVisible = true;
            object missing   = System.Reflection.Missing.Value;

            try
            {
                LectureRichTextBox.ReadOnly = false;
                LectureRichTextBox.Clear();
                LectureRichTextBox.Text = "...loading file";

                WordDocument = WordApplication.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
                WordDocument.Content.Select();
                WordDocument.Content.Copy();

                LectureRichTextBox.Clear();
                LectureRichTextBox.Paste();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR: " + ex.Message);
            }
            finally
            {
                WordDocument.Close(ref missing, ref missing, ref missing);
                LectureRichTextBox.ReadOnly = true;
            }
        }
Beispiel #9
0
        public int getpage(object file)
        {
            try
            {
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                object nullobj = System.Reflection.Missing.Value;

                Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(
                    ref file, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj);
                doc.ActiveWindow.Selection.WholeStory();
                doc.ActiveWindow.Selection.Copy();
                IDataObject data = Clipboard.GetDataObject();

                // get number of pages
                Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
                int pages = doc.ComputeStatistics(stat, Type.Missing);

                //string text = data.GetData(DataFormats.Text).ToString();  //获取具体内容,此项目不需要

                doc.Close(ref nullobj, ref nullobj, ref nullobj);
                app.Quit(ref nullobj, ref nullobj, ref nullobj);


                return(pages);
            }
            catch (Exception ex)
            {
                ex.ToString();
                return(0);
            }
        }
Beispiel #10
0
        private void listBoxSearchResults_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string      curItem     = ((ListBoxItem)listBoxSearchResults.SelectedItem).Key;
            string      url         = string.Format("{0}?objectId={1}", DownloadUrl, curItem);
            HttpContent httpcontent = HttpClientGetAsync(url).Result;

            byte[] result = httpcontent.ReadAsByteArrayAsync().Result;

            var tempFileName = string.Format("{0}\\{1}.docx", Path.GetTempPath(), curItem);

            File.WriteAllBytes(tempFileName, result);

            StringBuilder content = new StringBuilder();

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

            object miss     = System.Reflection.Missing.Value;
            object path     = tempFileName;
            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);
            Microsoft.Office.Interop.Word.Document  currentDocument = AddinModule.CurrentInstance.WordApp.ActiveDocument;
            Microsoft.Office.Interop.Word.Selection currentPos      = AddinModule.CurrentInstance.WordApp.Application.Selection;

            currentDocument.Range(currentPos.Range.Start, currentPos.Range.End).InsertAfter(docs.Content.Text);
            docs.Close();
        }
Beispiel #11
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            var    Name         = "Thapakorn";
            var    Age          = "40";
            string savePath     = Server.MapPath("~/PersonInfo.doc");
            string templatePath = Server.MapPath("~/wordTemplate2.doc");

            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = new Microsoft.Office.Interop.Word.Document();
            doc = app.Documents.Open(templatePath);
            doc.Activate();
            if (doc.Bookmarks.Exists("Name"))
            {
                doc.Bookmarks["Name"].Range.Text = Name;
            }
            if (doc.Bookmarks.Exists("Age"))
            {
                doc.Bookmarks["Age"].Range.Text = Age;
            }
            if (doc.Bookmarks.Exists("Time"))
            {
                doc.Bookmarks["Time"].Range.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }


            doc.SaveAs2(savePath);
            doc.Close();
            app.Application.Quit();

            DownloadFile(savePath);

            //Process.Start("WINWORD.EXE", "\"" + savePath + "\"");

            //Response.Write("Success");
        }
Beispiel #12
0
        private void CheckedListBoxProposals_SelectedIndexChanged(object sender, EventArgs e)
        {
            string t = (string)(CheckedListBoxProposals.SelectedItem);

            string[] res = t.Split('.');
            int      id;

            int.TryParse(res[0], out id);
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss = System.Reflection.Missing.Value;
            string ExecutableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string pathh = ctrlp.GetPathPaper(id);

            string[] dirfile  = pathh.Split('/');
            string   fin      = dirfile[0] + "\\" + dirfile[1];
            object   path     = Path.Combine(ExecutableLocation, fin);
            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 = docs.Content.Text;

            docs.Close();
            word.Quit();
            PaperContent.Font = new Font("Trebuchet MS", 13);
            PaperContent.Text = totaltext;
        }
Beispiel #13
0
        Node Word_Veri_Al(object adres, bool kelimeayir)
        {
            Node NodeWord = null;

            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss     = System.Reflection.Missing.Value;
            object readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref adres, 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);
            if (kelimeayir)
            {
                for (int i = 0; i < docs.Paragraphs.Count; i++)//Yakin eşleşmede kelime kelime NodeWord'e ekliyor.
                {
                    NodeWord = ekle(NodeWord, Kelime_Ayir(docs.Paragraphs[i + 1].Range.Text.ToString()));
                }
            }
            else
            {
                for (int i = 0; i < docs.Paragraphs.Count; i++)//Tam eşleşmede satir satir NodeWord'e ekliyor.
                {
                    NodeWord = ekle(NodeWord, docs.Paragraphs[i + 1].Range.Text.ToString());
                }
            }
            docs.Close(); //Sayfayi kapatiyor.
            word.Quit();  //Programi komple kapatiyor.
            return(NodeWord);
        }
Beispiel #14
0
        public void AddWord(string picture)
        {
            //Создаем объект документа
            Microsoft.Office.Interop.Word.Document doc = null;
            try
            {
                //Создаем объект приложения
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                app.Visible = false;

                //Путь до шаблона документа
                string source = @"C:\Users\ZJack\source\repos\ConsoleApp4\word.docx";

                //Открываем
                doc = app.Documents.Open(source);
                doc.Activate();

                //Добавляем картинку
                Microsoft.Office.Interop.Word.Range range;
                range = doc.Content;
                range.InlineShapes.AddPicture(picture);
                app.Visible = true;
            }catch (Exception ex)
            {
                doc.Close();
                doc = null;
                Console.WriteLine("Во время выполнения произошла ошибка!");
                Console.ReadLine();
            }
        }
Beispiel #15
0
 private void btnRead_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
         object miss = System.Reflection.Missing.Value;
         //object path = @"C:\TEXT\Cauhoi.docx";
         string filename = @"C:\TEXT\dapan.txt";
         object path     = txtPath.Text;
         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 = 6; i < docs.Paragraphs.Count; i += 5)
         {
             //totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
             totaltext += docs.Paragraphs[i + 1].Range.Text;
             //MessageBox.Show(totaltext);
         }
         //Console.WriteLine(totaltext);
         bll.WriteToText(totaltext, filename);
         docs.Close();
         word.Quit();
         MessageBox.Show("OK ", "Mess", MessageBoxButton.OK, MessageBoxImage.Information);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error + " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
        public MedicalModel AddFromFileDbFile(object path)// doc doctemplateservice - заменить
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss = System.Reflection.Missing.Value;

            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 allText = docs.Content.Text;

            string[] needTxt = allText.Split(new char[] { ' ', '\n', '\r' });

            MedicalModel md = new MedicalModel
            {
                Complaints     = tS.GetDataFromDoc("Жалобы:", "Анамнез:", needTxt),
                Anamnes        = tS.GetDataFromDoc("Анамнез:", "ОбщийСтатус:", needTxt),
                StatusPraesens = tS.GetDataFromDoc("ОбщийСтатус:", "МестныйСтатус:", needTxt),
                LocalStatus    = tS.GetDataFromDoc("МестныйСтатус:", "ПредварительныйДиагноз:", needTxt),
                Diagnos        = tS.GetDataFromDoc("ПредварительныйДиагноз:", "Рекомендации:", needTxt)
            };

            docs.Close();
            word.Quit();
            return(md);
        }
Beispiel #17
0
        private void DökümanHazırla()
        {
            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);
                }
            }

            document.SaveAs2(path1);
            document.Close();
            application.Quit();
            richEditControl1.LoadDocument(path1);
        }
Beispiel #18
0
        private void button4_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            object missing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Document doc = app.Documents.Add();

            doc.Content.SetRange(0, 0);

            //Doc파일에 제목
            Microsoft.Office.Interop.Word.Paragraph para1 = doc.Content.Paragraphs.Add(ref missing);
            //object styleHeading1 = "Heading 1";
            //para1.Range.set_Style(ref styleHeading1);
            para1.Range.Text = "인맥 정보";
            para1.Range.InsertParagraphAfter();

            //Doc파일에 테이블생성
            Microsoft.Office.Interop.Word.Table table;
            table = doc.Tables.Add(para1.Range, 2, 2, ref missing, ref missing);
            table.Borders.Enable = 1;

            //Doc파일에 테이블입력
            table.Cell(1, 1).Range.Text = "이름";
            table.Cell(1, 2).Range.Text = "내용";
            table.Cell(2, 1).Range.Text = textBox6.Text;
            table.Cell(2, 2).Range.Text = textBox2.Text;


            object filename = @"C:\Users\J\Desktop\personal connection.docx";

            doc.SaveAs2(ref filename);
            doc.Close();
        }
Beispiel #19
0
        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            try
            {
                if (!this.disposed)
                {
                    // If disposing equals true, dispose all managed
                    // and unmanaged resources.
                    if (disposing)
                    {
                        // Dispose managed resources.
                    }
                    oWordDoc.Close();
                    oWordDoc = null;
                    oWord.Quit(true);
                    oWord = null;
                    // Release unmanaged resources. If disposing is false,
                    // only the following code is executed.

                    // Note that this is not thread safe.
                    // Another thread could start disposing the object
                    // after the managed resources are disposed,
                    // but before the disposed flag is set to true.
                    // If thread safety is necessary, it must be
                    // implemented by the client.
                }
                disposed = true;
            }
            catch (Exception)
            {
            }
        }
        private string[] readDocx(string path)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss       = System.Reflection.Missing.Value;
            object pathObject = path;
            //object path2 = @"C:\Users\SA02- Frederik\Documents\Case05PigLatin\testInputFiles\InputText.txt";
            object readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref pathObject, 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 = "";

            //the whole document
            for (int i = 0; i < docs.Paragraphs.Count; i++)
            {
                //Determine the beginning of an entire paragraph and intercept the table name
                //Get the column name
                //......
                totalText += docs.Paragraphs[i + 1].Range.Text.ToString();
            }
            //Console.Write(totalText);
            docs.Close();
            word.Quit();
            string[] ret;

            if (_myFileType != ".txt")
            {
                ret = formatOddFileLayout(totalText);
            }
            else
            {
                ret = totalText.Split(_splitter, StringSplitOptions.None);
            }
            return(ret);
        }
Beispiel #21
0
        protected void download_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            if (fileUpload.HasFile)
            {
                try
                {
                    sb.AppendFormat(" Uploading file: {0}", fileUpload.FileName);

                    string pathToFile = System.Reflection.Assembly.GetExecutingAssembly().Location + fileUpload.FileName;

                    fileUpload.SaveAs(pathToFile);

                    //Showing the file information
                    sb.AppendFormat("\n Save As: {0}", fileUpload.PostedFile.FileName);
                    sb.AppendFormat("\n File type: {0}", fileUpload.PostedFile.ContentType);
                    sb.AppendFormat("\n File length: {0}", fileUpload.PostedFile.ContentLength);
                    sb.AppendFormat("\n File name: {0}", fileUpload.PostedFile.FileName);

                    if (fileUpload.PostedFile.ContentType.ToString().ToLower() == "text/plain")
                    {
                        textbox.Text = File.ReadAllText(pathToFile, Encoding.Default);
                    }
                    else if (fileUpload.PostedFile.ContentType.ToString().ToLower() == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || fileUpload.PostedFile.ContentType.ToString().ToLower() == "doc")
                    {
                        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                        object path = pathToFile;
                        Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path);
                        string text = "";

                        text = docs.Content.Text;

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

                        while (text[0] == ' ')
                        {
                            text.Remove(0, 1);
                        }

                        textbox.Text = text;
                    }
                    else
                    {
                        textbox.Text = fileUpload.PostedFile.ContentType.ToString().ToLower();
                    }
                }
                catch (Exception ex)
                {
                    sb.Append("\n Error \n");
                    sb.AppendFormat("Unable to save file \n {0}", ex.Message);
                    textbox.Text = sb.ToString();
                }
            }
            else
            {
                lblmessage.Text = sb.ToString();
            }
        }
        //打开word文档并加载到richTextBox
        private void OpenButton_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog2.ShowDialog() == DialogResult.Cancel)
            {
                return;                                   //获取正在打开的文件名
            }
            editingFilename = this.openFileDialog2.FileName;
            Microsoft.Office.Interop.Word.Application myApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    myDoc = null;
            object missing  = System.Reflection.Missing.Value;
            object fileName = this.openFileDialog2.FileName;

            try
            {
                myDoc = myApp.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);
                myDoc.ActiveWindow.Selection.WholeStory(); //全选word文档中的数据
                myDoc.ActiveWindow.Selection.Copy();       //复制数据到剪切板
                richTextBox1.Paste();                      //richTextBox粘贴数据;richTextBox1.Text = doc.Content.Text;//显示无格式数据
                myDoc.Close();
                myApp.Quit();
            }
            catch (Exception ex)
            {
                MessageBox.Show("WORD文件打开失败!\n" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Beispiel #23
0
        private void btn_SaveDocument_Click(object sender, RoutedEventArgs e)
        {
            forms.SaveFileDialog save = new forms.SaveFileDialog();

            save.DefaultExt = ".doc";

            if (save.ShowDialog() == forms.DialogResult.OK)
            {
                document_address = save.FileName;
                document.SaveToFile(document_address);

                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                app.Visible = false;
                Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(document_address);
                Microsoft.Office.Interop.Word.Range    r   = doc.Content;
                r.Find.ClearFormatting();
                r.Find.Execute(FindText: "Evaluation Warning: The document was created with Spire.Doc for .NET.", ReplaceWith: "");
                doc.SaveAs(document_address);

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

                MessageBox.Show("Документ успешно сохранен");
            }
        }
Beispiel #24
0
        private void ExportPdfFile(string FileName)
        {
            try
            {
                Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(string.Format("{0}\\{1}", txtBaseFolderPath.Text, FileName), ReadOnly: false, Visible: true);

                FileName = System.IO.Path.GetFileNameWithoutExtension(FileName);
                for (int i = 0; i < 20; i++)
                {
                    FileName = FileName.Replace("-V" + i.ToString(), "");
                }
                if (System.IO.File.Exists(string.Format("{0}\\{1}.pdf", txtBaseFolderPath.Text, FileName)))
                {
                    System.IO.File.Delete(string.Format("{0}\\{1}.pdf", txtBaseFolderPath.Text, FileName));
                }

                aDoc.Activate();

                ReplaceFields(aDoc);

                aDoc.SaveAs2(string.Format("{0}\\{1}.pdf", txtBaseFolderPath.Text, FileName), Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);

                aDoc.Close();


                releaseObject(aDoc);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public MedicalModel AddFromFileClass(object path)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss = System.Reflection.Missing.Value;

            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 allText = docs.Content.Text;

            string[] needTxt = allText.Split(new char[] { ' ', '\n', '\r' });

            MedicalModel md = new MedicalModel
            {
                Complaints     = tS.GetDataFromDoc("Жалобы:", "Anamnes:", needTxt),
                Anamnes        = tS.GetDataFromDoc("Anamnes:", "StatusPraesens:", needTxt),
                StatusPraesens = tS.GetDataFromDoc("StatusPraesens:", "LocalStatus:", needTxt),
                LocalStatus    = tS.GetDataFromDoc("LocalStatus:", "Diagnos:", needTxt),
                Diagnos        = tS.GetDataFromDoc("Diagnos:", "Рекомендации:", needTxt)
            };

            docs.Close();
            word.Quit();
            return(md);
        }// doc
Beispiel #26
0
        private void assessmentMsg_Load(object sender, EventArgs e)
        {
            textBox1.Text = assessmentmsg.assessmenttxtbox.Text;
            object filename = textBox1.Text;

            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;

            try
            {
                doc = ac.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);
                doc.Content.Select();
                doc.Content.Copy();
                richTextBox1.Paste();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR:" + ex.Message);
            }
            finally
            {
                doc.Close(ref missing, ref missing, ref missing);
            }
        }
Beispiel #27
0
 private void button2_Click(object sender, EventArgs e)
 {
     saveFileDialog1.Filter       = "Microsoft Word document(*.docx)|*.docx";
     saveFileDialog1.AddExtension = true;
     saveFileDialog1.ShowDialog();
     if (saveFileDialog1.FileName != "")
     {
         try
         {
             string[] mas = new string[5];
             mas = saveFileDialog1.FileName.Split('.');
             if (mas[1] == "docx" || mas[1] == "doc")
             {
                 Microsoft.Office.Interop.Word._Application app = new Microsoft.Office.Interop.Word.Application();
                 Microsoft.Office.Interop.Word.Document     doc = app.Documents.Add();
                 doc.Paragraphs[1].Range.Text = doc_content;
                 Clipboard.SetImage(pictureBox1.Image);
                 doc.Paragraphs[doc.Paragraphs.Count].Range.Paste();
                 app.Visible = false;
                 doc.SaveAs2(saveFileDialog1.FileName);
                 doc.Close();
                 app.Quit();
                 MessageBox.Show("Файл сохранен!", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
             }
             else
             {
                 MessageBox.Show("Недопустимый тип файла!", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
         }
         catch (Exception exc)
         {
             MessageBox.Show(exc.Message.ToString(), exc.Source.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Beispiel #28
0
        private static void ConvertWord(Microsoft.Office.Interop.Word.WdSaveFormat format, string fileName, string sourceFile)
        {
            Microsoft.Office.Interop.Word.Document    wordDoc = null;
            Microsoft.Office.Interop.Word.Application word    = null;

            try
            {
                word = new Microsoft.Office.Interop.Word.Application
                {
                    Visible = false
                };
                wordDoc = word.Documents.Open(sourceFile, false);

                wordDoc.SaveAs2(FileName: fileName, FileFormat: format);
                wordDoc.Close();
                word.Quit();
            }
            catch (Exception ex)
            {
                try
                {
                    wordDoc?.Close();
                    word?.Quit();
                }
                catch { }

                throw;
            }
        }
        public PrintHelper(string helper, string printerName)
        {
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            wordApp.Visible = false;
            Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Add(helper);
            wordApp.ActivePrinter = printerName;
            object background = false;
            object oMissing   = System.Reflection.Missing.Value;

            try
            {
                wordApp.ActiveDocument.PrintOut(background, oMissing, oMissing, oMissing, oMissing,
                                                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                                                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                                                oMissing);
            }
            catch (Exception e)
            {
                var a = e;
            }

            doc.Close(SaveChanges: false);
            doc = null;
            ((Microsoft.Office.Interop.Word._Application)wordApp).Quit(SaveChanges: false);
            wordApp = null;
        }
Beispiel #30
0
        private void button8_Click(object sender, EventArgs e)
        {
            dataGridView3.DataSource = Base.customersWithAdvance(!textBox10.Text.Equals("") ? textBox10.Text : "0");

            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = app.Documents.Open(Application.StartupPath.ToString() + "\\goodCustomersMore0.docx");
            object missing = System.Reflection.Missing.Value;
            string sum     = "                                               Customers who have money on the bill! \n\n";

            try
            {
                string[] array = wateBase.getBaseContent("SELECT * FROM customers WHERE SUMMERY < " + (!textBox10.Text.Equals("")?textBox10.Text:"0"));
                for (int i = 0; i < array.Length; i++)
                {
                    string a = array[i];
                    sum += "" + a + "\n";
                }
                doc.Content.Text = sum;
                doc.Save();
                doc.Close(ref missing);
                app.Quit(ref missing);
                MessageBox.Show("File successfully created\n" + Application.StartupPath.ToString());
            }
            catch (Exception)
            {
                MessageBox.Show("Imposible to create file");
            }
        }
Beispiel #31
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);
 }
        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 #33
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);
        }
        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 #35
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();
                }
            }
        }
        /// <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 #37
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);
     }
 }