Ejemplo n.º 1
0
        private void button1_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc  = new Microsoft.Office.Interop.Word.Document();
            object fileName = @"C:\Users\334262\Desktop\test2.docx";

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

            doc = word.Documents.Open(ref fileName,
                                      ref missing, ref missing, ref missing, ref missing,
                                      ref missing, ref missing, ref missing, ref missing,
                                      ref missing, ref missing, ref missing, ref missing,
                                      ref missing, ref missing, ref missing);
            string ReadValue = string.Empty;

            // Activate the document
            doc.Activate();

            foreach (Microsoft.Office.Interop.Word.Range tmpRange in doc.StoryRanges)
            {
                ReadValue += tmpRange.Text;
            }

            richTextBox1.Text = ReadValue;
        }
Ejemplo n.º 2
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");
        }
        public GenerateResult ShowGeneratedFile()
        {
            GenerateResult result = new GenerateResult();

            try
            {
                if (txtGenerateFilePath.Text != "")
                {
                    Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                    Microsoft.Office.Interop.Word.Document    doc  = new Microsoft.Office.Interop.Word.Document();

                    doc = word.Documents.Open(txtGenerateFilePath.Text);
                    doc.Activate();
                    word.Visible  = true;
                    result.Result = true;
                }
                else
                {
                    result.Result    = false;
                    result.Exception = "فایلی موجود نمی باشد";
                }
            }
            catch (Exception ex)
            {
                result.Result    = false;
                result.Exception = ex.Message;
            }
            return(result);
        }
        //public void EnableFileAttachmentToDefault()
        //{
        //    optGenerate.IsEnabled = true;
        //    optSelective.IsEnabled = true;
        //    grdExistingFile.Visibility = Visibility.Collapsed;
        //    lblShowFile.Visibility = Visibility.Collapsed;
        //    optSelective.IsChecked = true;
        //    lblGenerateFile.Visibility = Visibility.Collapsed;
        //    grdGenerateFile.Visibility = Visibility.Collapsed;
        //    grdSelectFile.Visibility = Visibility.Visible;
        //    lblSelectFile.Visibility = Visibility.Visible;
        //}

        public GenerateResult ShowGeneratedFile(byte[] generatedFile, string fileName, string fileExtension)
        {
            GenerateResult result = new GenerateResult();

            try
            {
                string path     = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string filePath = path + @"\\" + fileName + "." + fileExtension;
                File.WriteAllBytes(filePath, generatedFile);
                txtGenerateFilePath.Text = filePath;
                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    doc  = new Microsoft.Office.Interop.Word.Document();

                doc = word.Documents.Open(filePath);
                doc.Activate();
                word.Visible  = true;
                result.Result = true;
            }
            catch (Exception ex)
            {
                result.Result    = false;
                result.Exception = ex.Message;
            }
            return(result);
            //doc.Save();
            //doc.Close();
            //word.Quit();
        }
Ejemplo n.º 5
0
        private static Microsoft.Office.Interop.Word.Document oDoc;                                                                       // a reference to the document

        // Open a file (the file must exists) and activate it
        public static void Open(string strFileName)
        {
            object fileName  = strFileName;
            object readOnly  = false;
            object isVisible = true;
            object missing   = System.Reflection.Missing.Value;

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

            //String read = string.Empty;
            //List<string> data = new List<string>();
            //for (int i = 0; i < oDoc.Paragraphs.Count; i++)
            //{
            //    string temp = oDoc.Paragraphs[i + 1].Range.Text.Trim();
            //    if (temp != string.Empty)
            //        data.Add(temp);
            //}
            //((_Document)oDoc).Close();
            //((_Application)oWordApplic).Quit();
            //return data;

            //GridView1.DataSource = data;
            //GridView1.DataBind();

            oDoc.Activate();
            //((_Document)oDoc).Close();
            //((_Application)oWordApplic).Quit();
        }
Ejemplo n.º 6
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;
            }
        }
Ejemplo n.º 7
0
        public async void NapravleniyaMed(List <PersonShortViewModel> persons)
        {
            try
            {
                // await new ProgressRunner().RunAsync(doAction);
                await new ProgressRunner().RunAsync(
                    new Action <ProgressHandler>((progressChanged) =>
                {
                    progressChanged(1, "Формирование направлений");

                    var path = (string.Format("{0}\\_шаблоны\\" + "Направление мед.dotx", AppDomain.CurrentDomain.BaseDirectory));
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application {
                        Visible = false
                    };
                    Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Add(path /*, ReadOnly: false, Visible: true*/);
                    aDoc.Activate();

                    object missing = Missing.Value;
                    object what    = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine;
                    object which   = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToLast;


                    Microsoft.Office.Interop.Word.Range baseRange = aDoc.Content;
                    baseRange.Cut();

                    Microsoft.Office.Interop.Word.Range range = null;

                    progressChanged(5);
                    var share = 95.0 / persons.Count;
                    foreach (var p in persons)
                    {
                        if (range != null)    //!firstRow
                        {
                            range = aDoc.GoTo(ref what, ref which, ref missing, ref missing);
                            range.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);
                        }

                        range = aDoc.GoTo(ref what, ref which, ref missing, ref missing);

                        range.Paste();

                        range.Find.ClearFormatting();
                        range.Find.Execute(FindText: "{fio}", ReplaceWith: p.Fio, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
                        if (p.BirthDat.HasValue)
                        {
                            range.Find.Execute(FindText: "{birthDat}", ReplaceWith: p.BirthDat.Value.ToString("dd.MM.yyyy"), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
                        }

                        progressChanged(share);
                    }
                    // string otchetDir = @"C:\_provodnikFTP";
                    //  aDoc.SaveAs(FileName: otchetDir + @"\Согласие на обработку персональных данных.DOCX");
                    wordApp.Visible = true;
                })


                    );
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
Ejemplo n.º 8
0
      public void Soglasie()
      {
          var path = (string.Format("{0}\\_шаблоны\\" + "Согласие на обработку персональных данных.dotx", AppDomain.CurrentDomain.BaseDirectory));

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

          // var vm = DataContext as SendGroupViewModel;

          var db = new ProvodnikContext();

          var p = this.DataContext as PersonViewModel;

          Microsoft.Office.Interop.Word.Range range = aDoc.Content;
          range.Find.ClearFormatting();
          range.Find.Execute(FindText: "{today}", ReplaceWith: DateTime.Today.ToString("dd.MM.yyyy"), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          range.Find.Execute(FindText: "{till}", ReplaceWith: DateTime.Today.AddYears(1).ToString("dd.MM.yyyy"), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          string passport = $"{p.PaspSeriya} {p.PaspNomer} выдан {p.PaspVidan} {p.VidanDat}";

          range.Find.Execute(FindText: "{passport}", ReplaceWith: passport, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          range.Find.Execute(FindText: "{fio}", ReplaceWith: p.Fio, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          range.Find.Execute(FindText: "{addres}", ReplaceWith: p.PaspAdres, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          range.Find.Execute(FindText: "{till}", ReplaceWith: DateTime.Today.AddYears(1).ToString("dd.MM.yyyy"), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);


          //string otchetDir = @"C:\_provodnikFTP";
          //aDoc.SaveAs(FileName: otchetDir + @"\Согласие на обработку персональных данных.DOCX");
      }
Ejemplo n.º 9
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();
            }
        }
Ejemplo n.º 10
0
 private void PrintReport(object sender, EventArgs e)
 {
     Microsoft.Office.Interop.Word.Application app      = new Microsoft.Office.Interop.Word.Application();
     Microsoft.Office.Interop.Word.Document    document = app.Documents.Open($"{reportsPath}\\{countryBox.Text} Report.docx");
     document.Activate();
     document.PrintOut();
 }
Ejemplo n.º 11
0
        public void CreateWordDocument(object filename, object savaAs, object image)
        {
            object missing  = Missing.Value;
            string tempPath = null;

            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    aDoc    = null;

            if (File.Exists((string)filename))
            {
                DateTime today    = DateTime.Now;
                object   readOnly = false;
                wordApp.Visible = false;
                aDoc            = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                         ref missing, ref missing, ref missing,
                                                         ref missing, ref missing, ref missing,
                                                         ref missing, ref missing, ref missing,
                                                         ref missing, ref missing, ref missing, ref missing);
                aDoc.Activate();
                this.FindAndReplace(wordApp, @"Doc1.docx", "asdd");
            }
            else
            {
                return;
            }
            aDoc.SaveAs2(ref savaAs, ref missing, ref missing, ref missing,
                         ref missing, ref missing, ref missing,
                         ref missing, ref missing, ref missing,
                         ref missing, ref missing, ref missing,
                         ref missing, ref missing, ref missing);
            aDoc.Close(ref missing, ref missing, ref missing);
            File.Delete(tempPath);
        }
Ejemplo n.º 12
0
        // Open a new document
        public static void Open()
        {
            object missing = System.Reflection.Missing.Value;

            oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            oDoc.Activate();
        }
Ejemplo n.º 13
0
 private void Print(Microsoft.Office.Interop.Word.Document doc)
 {
     // do the actual printing:
     doc.Activate();
     Thread.Sleep(TimeSpan.FromSeconds(1)); // emperical testing found this to be sufficient for our system
     // (a delay may not be required for you if you are printing only one document at a time)
     doc.PrintOut(/* ref objects */);
 }
Ejemplo n.º 14
0
        public void ReestrPeredachi()
        {
            var vm = DataContext as SendGroupViewModel;

            var db  = new ProvodnikContext();
            var ids = vm.Persons.Select(pp => pp.PersonId);
            var pe  = db.Persons.Where(pp => ids.Contains(pp.Id)).ToList();

            if (pe.Count == 0)
            {
                return;
            }


            var path = (string.Format("{0}\\_шаблоны\\" + "Акт передачи документов.docx", AppDomain.CurrentDomain.BaseDirectory));

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

            object missing = Missing.Value;

            Microsoft.Office.Interop.Word.Range range = aDoc.Content;
            range.Find.ClearFormatting();

            range.Find.Execute(FindText: "{City}", ReplaceWith: vm.City, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            range.Find.Execute(FindText: "{Filial}", ReplaceWith: vm.Filial, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            range.Find.Execute(FindText: "{Sp}", ReplaceWith: vm.Sp, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            range.Find.Execute(FindText: "{Ochniki}", ReplaceWith: vm.Persons.Count(x => x.UchForma == UchFormaConsts.Ochnaya), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            range.Find.Execute(FindText: "{Count}", ReplaceWith: vm.Persons.Count(), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            range.Find.Execute(FindText: "{ВЧ}", ReplaceWith: vm.DepoRod, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            var table = aDoc.Tables[3];
            int iRow  = 2;

            foreach (var p in vm.Persons)
            {
                if (iRow > 2)
                {
                    table.Rows.Add(ref missing);
                }
                table.Cell(iRow, 1).Range.Text = (iRow - 1).ToString() + '.';
                table.Cell(iRow, 2).Range.Text = p.Fio;
                table.Cell(iRow, 3).Range.Text = p.UchForma;
                table.Cell(iRow, 4).Range.Text = "ЕСТЬ";

                iRow++;
            }

            aDoc.SaveAs(FileName: otchetDir + $@"\Акт передачи документов.docx");
            aDoc.Close();
        }
Ejemplo n.º 15
0
        // Open a file (the file must exists) and activate it
        public void Open(string strFileName)
        {
            object fileName = strFileName;
            object readOnly = false;
            object isVisible = true;

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

            oDoc.Activate();
        }
Ejemplo n.º 16
0
        public void LeerDeBD()
        {
            PGJ.ConnectServer();
            SqlCommand comm = new SqlCommand("SELECT * FROM CAT_PLANTILLAS " + " WHERE ID_PLANTILLA = " + Archivos.IdPlantilla, Data.CnnCentral);

            comm.CommandType = CommandType.Text;
            SqlDataAdapter da = new SqlDataAdapter(comm);
            DataSet        ds = new DataSet("Binarios");

            da.Fill(ds);
            //Creamos un array de bytes que contiene los bytes almacenados
            //en el campo Documento de la tabla
            byte[] bits = ((byte[])(ds.Tables[0].Rows[0].ItemArray[3]));
            //Vamos a guardar ese array de bytes como un fichero en el
            //disco duro, un fichero temporal que después se podrá descartar.
            string sFile = "tmp.doc";

            //Creamos un nuevo FileStream, que esta vez servirá para
            //crear un fichero con el nombre especificado
            fs = new FileStream(Server.MapPath(".") +
                                @"\DocTmp\" + sFile, FileMode.Create);
            //Y escribimos en disco el array de bytes que conforman
            //el fichero Word
            fs.Write(bits, 0, Convert.ToInt32(bits.Length));
            if (File.Exists((string)fs.Name))
            {
                object readOnly  = true;
                object isVisible = true;
                Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                wordApp.Visible = true;
                Documento       = wordApp.Documents.Open(fs.Name, 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);
                fs.Close();
                Documento.Activate();
                //object saveChanges = true;
                //object FormatOriginal = true;
                traerMarcadoresProcedimientos(Archivos.IdPlantilla);
                //traermarcadoresText(Archivos.IdPlantilla);
                Documento = wordApp.Documents["tmp.doc"] as Microsoft.Office.Interop.Word.Document;
                Documento.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges);
                //wordApp.Documents.Close();
                wordApp.Application.Quit();

                string script = "<script languaje='javascript'> ";
                script += "mostrarFichero('DocTmp/tmp.doc') ";
                script += "</script>" + Environment.NewLine;
                Page.RegisterStartupScript("mostrarFichero", script);
            }
            //LeerPDF();
        }
Ejemplo n.º 17
0
        public void CreateDoc(string path, string fullname, string moneydep, string id, string proc, string datelong, string currdate)
        {
            object filename = @"E:\Users\Alex\Desktop\1.doc";
            object tempname = @"TEMPLATE.doc";

            File.Copy((string)tempname, (string)filename, true);
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application {
                Visible = true
            };
            Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(filename, ReadOnly: false, Visible: true);
            FindAndReplace(wordApp, "{id}", "12345");
            aDoc.Activate();
        }
Ejemplo n.º 18
0
        public String Replace(PrintModel printModel)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            String filePath = String.Format("{0}\\{1}", printModel.BasePath, printModel.InputFileName);
            String output   = String.Format("{0}\\{1}\\{2}", printModel.BasePath, printModel.BasePathReplaced, printModel.InputFileName);

            // CreateDirIfNotExists(printModel.BasePath);
            CreateDirIfNotExists(string.Format("{0}\\{1}", printModel.BasePath, printModel.BasePathReplaced));

            object missing        = System.Type.Missing;
            object fileName       = filePath;
            object fileNameOutput = output;


            Microsoft.Office.Interop.Word.Document doc = word.Documents.Add(ref fileName, ref missing, ref missing, ref missing);

            try
            {
                doc.Activate();
                foreach (Microsoft.Office.Interop.Word.Range tmpRange in doc.StoryRanges)
                {
                    foreach (ReplaceModel replace in printModel.Replaces)
                    {
                        tmpRange.Find.Text             = printModel.KeyPrefix + replace.Key;
                        tmpRange.Find.Replacement.Text = replace.Value;

                        tmpRange.Find.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
                        object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

                        tmpRange.Find.Execute(ref missing, ref missing, ref missing,
                                              ref missing, ref missing, ref missing, ref missing,
                                              ref missing, ref missing, ref missing, ref replaceAll,
                                              ref missing, ref missing, ref missing, ref missing);
                    }
                }

                DeleteIfExists(output);
                doc.SaveAs2(ref fileNameOutput);
                return(output);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CloseDoc(word, doc);
            }
        }
Ejemplo n.º 19
0
        public async void Badges(List <PersonShortViewModel> persons)
        {
            try
            {
                // await new ProgressRunner().RunAsync(doAction);
                await new ProgressRunner().RunAsync(
                    new Action <ProgressHandler>((progressChanged) =>
                {
                    progressChanged(1, "Формирование документа");

                    var path = (string.Format("{0}\\_шаблоны\\" + "Бейджи.dotx", AppDomain.CurrentDomain.BaseDirectory));
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application {
                        Visible = false
                    };
                    Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Add(path /*, ReadOnly: false, Visible: true*/);
                    aDoc.Activate();

                    object missing = Missing.Value;

                    var table = aDoc.Tables[1];
                    int iRow  = 2;

                    progressChanged(5);
                    var share = 95.0 / persons.Count;
                    //for (int i=0;i<persons.Count-1;i++) table.Rows.Add(table.Rows[i+2]); //table.Rows.Add(ref missing);
                    foreach (var p in persons)
                    {
                        if (iRow > 2)
                        {
                            table.Rows.Add(ref missing);
                        }
                        table.Cell(iRow, 1).Range.Text = (iRow - 1).ToString() + '.';
                        table.Cell(iRow, 2).Range.Text = p.BadgeRus;
                        table.Cell(iRow, 3).Range.Text = p.BadgeEng;

                        iRow++;
                        progressChanged(share);
                    }
                    // string otchetDir = @"C:\_provodnikFTP";
                    //  aDoc.SaveAs(FileName: otchetDir + @"\Согласие на обработку персональных данных.DOCX");
                    wordApp.Visible = true;
                })


                    );
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
Ejemplo n.º 20
0
        private void bttDY_Click(object sender, EventArgs e)
        {
            try
            {
                if (!System.IO.File.Exists(wordPath.ToString()))
                {
                    return;
                }
                List <string> newValue = GettxtValue();
                //word应用
                Microsoft.Office.Interop.Word.ApplicationClass App = new Microsoft.Office.Interop.Word.ApplicationClass(); //Word应用程序对象
                Microsoft.Office.Interop.Word.Document         doc = new Microsoft.Office.Interop.Word.Document();         //Word文档对象
                App.Visible = false;
                String[] bmsTest = { "biaohao",    "zhibiaoriqi", "shujuneirong", "tigongdanwei", "suoqudanwei", "chulibumen", "xieyibianhao", "teshushuiming", "shujufanwei", "zhuyaoyongtu", "guodixin",   "miji",  "txtsn",     "txtpn",          "geshi", "shijitufushu", "jishufuwufeiyong", "shujuliang", "bumenfuzeren", "bumenqianzi", "jishujiagong", "txtjishujiang", "chenggujianchare",
                                     "qianziriqi", "jieshouren",  "aaaaa",        "querenqian",   "bbbbb",       "ddddd",      "ccccc",        "lianxiren",     "dianhua",     "youzheng",     "emaildizhi", "fffff", "beizhutxt", "zhibiaorenyuan", };
                object   oMissing     = System.Reflection.Missing.Value;
                object   readOnly     = false;
                object   saveFileName = Application.StartupPath + "\\..\\OrderTask\\teste.doc";

                doc = App.Documents.Open(ref wordPath, ref oMissing, ref readOnly,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                doc.Activate();
                int m = 0;
                //替换
                foreach (String s in bmsTest)
                {
                    Replace(doc, s, newValue[m]);
                    m++;
                }

                doc.SaveAs(ref saveFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                           ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                doc.Close(ref oMissing, ref oMissing, ref oMissing);
                App.Quit(ref oMissing, ref oMissing, ref oMissing);

                //打开
                if (System.IO.File.Exists(saveFileName.ToString()))
                {
                    System.Diagnostics.Process.Start(saveFileName.ToString());
                }
                this.WindowState = FormWindowState.Minimized;
            }
            catch
            {
            }
        }
Ejemplo n.º 21
0
        //Creeate the Doc Method
        private void CreateWordDocument(object filename, object SaveAs)
        {
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            object missing = Missing.Value;

            Microsoft.Office.Interop.Word.Document myWordDoc = null;

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

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

                //find and replace
                this.FindAndReplace(wordApp, "<name>", txtb1.Text);
                this.FindAndReplace(wordApp, "<firstname>", txtb2.Text);
                this.FindAndReplace(wordApp, "<birthday>", txtb3.Text);
                this.FindAndReplace(wordApp, "<date>", DateTime.Today);
            }
            else
            {
                this.lblm.Text = "No se creo el documento!";

                //MessageBox.Show("File not Found!");
            }

            //Save as
            myWordDoc.SaveAs2(ref SaveAs, 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);

            myWordDoc.Close();
            wordApp.Quit();
            this.lblm.Text = "Se creo el documento!";
            Process.Start(@"C:\Users\Usuario\Documents\SIGEDOC_N\Solucion SIGEDOC\SIGEDOC\documentos word\documento creado\PQS.docx");

            //MessageBox.Show("File Created!");
        }
Ejemplo n.º 22
0
 private void SendWordToPrinter(string path)
 {
     try
     {
         Microsoft.Office.Interop.Word.Application wordInstance = new Microsoft.Office.Interop.Word.Application();
         FileInfo wordFile   = new FileInfo(path);
         object   fileObject = wordFile.FullName;
         object   oMissing   = System.Reflection.Missing.Value;
         Microsoft.Office.Interop.Word.Document doc = wordInstance.Documents.Open(ref fileObject, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
         doc.Activate();
         doc.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
         wordInstance.Quit();
     }
     catch (Exception exp)
     {
         string errorMsg = exp.Message;
     }
 }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            string strPath =
                System.AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/");

            // Instantiate Object
            APServer.Server server = new APServer.Server();

            // Path and filename of output
            server.NewDocumentName = "Server.WordPrinting.pdf";
            server.OutputDirectory = strPath;

            // Start the print job
            ServerDK.Results.ServerResult result = server.BeginPrintToPDF();
            if (result.ServerStatus == ServerDK.Results.ServerStatus.Success)
            {
                // Automate Word to print a document to Server
                // NOTE: You must add the 'Microsoft.Office.Interop.Word'
                // reference
                Microsoft.Office.Interop.Word._Application oWORD =
                    new Microsoft.Office.Interop.Word.Application();
                oWORD.ActivePrinter = server.NewPrinterName;
                oWORD.DisplayAlerts =
                    Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
                oWORD.Visible = false;
                Microsoft.Office.Interop.Word.Document oDOC =
                    oWORD.Documents.Open($"{strPath}Server.Word.Input.doc");
                oDOC.Activate();
                oWORD.PrintOut();
                oWORD.Documents.Close();
                oWORD.Quit();

                // Wait(seconds) for job to complete
                result = server.EndPrintToPDF(waitTime: 30);
            }

            // Output result
            WriteResult(result);

            // Process Complete
            Console.WriteLine("Done!");
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Ejemplo n.º 24
0
        private void btnReportMAT_Click(object sender, EventArgs e)
        {
            int id = TextUtils.ToInt(grvData.GetFocusedRowCellValue(colID));

            if (id > 0)
            {
                string code = grvData.GetFocusedRowCellValue(colCode).ToString();
                string name = grvData.GetFocusedRowCellValue(colName).ToString();

                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    doc  = new Microsoft.Office.Interop.Word.Document();
                try
                {
                    Directory.CreateDirectory(@"D:\\ReportData\\KIEM TRA THIET KE\\");
                    string reportPath = @"D:\\ReportData\\KIEM TRA THIET KE\\" + code + ".docx";
                    File.Copy(Application.StartupPath + "\\Templates\\ReportHSCK.docx", reportPath, true);

                    string productname = name;
                    string productcode = code;

                    doc = word.Documents.Open(reportPath);
                    doc.Activate();

                    repalaceText(doc, "<productname>", productname);
                    repalaceText(doc, "<productcode>", productcode);
                    repalaceText(doc, "<username>", Global.AppFullName);

                    repalaceText(doc, "<day>", DateTime.Now.Day.ToString());
                    repalaceText(doc, "<month>", DateTime.Now.Month.ToString());
                    repalaceText(doc, "<year>", DateTime.Now.Year.ToString());

                    doc.Save();
                    Process.Start(reportPath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                }
            }
        }
Ejemplo n.º 25
0
        //Create the Doc Method
        private void CreateWordDocument(object filename, object SaveAs)
        {
            try
            {
                wordApp   = new Microsoft.Office.Interop.Word.Application();
                missing   = Missing.Value;
                myWordDoc = null;
                if (File.Exists((string)filename))
                {
                    object readOnly  = false;
                    object isVisible = false;
                    wordApp.Visible = false;

                    myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                       ref missing, ref missing, ref missing,
                                                       ref missing, ref missing, ref missing,
                                                       ref missing, ref missing, ref missing,
                                                       ref missing, ref missing, ref missing, ref missing);
                    myWordDoc.Activate();
                    Content();
                }
                else
                {
                    MessageBox.Show("File not Found!");
                }

                //Save as
                myWordDoc.SaveAs2(ref SaveAs, 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);
                myWordDoc.Close();
                wordApp.Quit();
            }
            catch (Exception ex)
            {
                myWordDoc.Close();
                wordApp.Quit();
                MessageBox.Show(ex.ToString(), "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 26
0
        private Microsoft.Office.Interop.Word.Document OpenWordTemplateFile(string FileNameStr)
        {
            Microsoft.Office.Interop.Word.Document oDoc = new Microsoft.Office.Interop.Word.Document();

            object Obj_FileName = FileNameStr;
            object Visible      = false;
            object ReadOnly     = false;
            object missing      = System.Reflection.Missing.Value;

            _WordApplicMain = new Microsoft.Office.Interop.Word.Application();
            Object Nothing = System.Reflection.Missing.Value;

            oDoc = _WordApplicMain.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                                                  ref missing, ref missing, ref missing, ref missing,
                                                  ref missing, ref missing, ref missing, ref Visible,
                                                  ref missing, ref missing, ref missing,
                                                  ref missing);
            oDoc.Activate();

            return(oDoc);
        }
Ejemplo n.º 27
0
        public static void Print()
        {
            //zmienna do wysylania i pobierania plików
            WebClient request = new WebClient();
            //missing oject to use with various word commands
            object missing = System.Reflection.Missing.Value;

            //dane logowania
            request.Credentials = new NetworkCredential(Polaczenia.ftpLogin, Polaczenia.ftpHaslo);
            //pobieranie pliku
            request.DownloadFile(new Uri("ftp://finanse.focik.net/Pliki/Wzory/wniosek_urlopowy.doc"), temp + "\\wniosek_urlopowy.doc");

            //the template file you will be using, you need to locate the template we   previously made
            object fileToOpen = (object)temp + "\\wniosek_urlopowy.doc";


            //Create new instance of word and create a new document
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc     = null;

            //Properties for the new word document, so everything happens in the background. If this isn’t set all the word documents will be visible
            object readOnly  = false;
            object isVisible = false;

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

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

            doc.Activate();

            //Making word visible to be able to show the print preview.
            wordApp.Visible = true;
            doc.PrintPreview();
        }
Ejemplo n.º 28
0
        public void PismoLgoti()
        {
            var vm = DataContext as SendGroupViewModel;

            var db  = new ProvodnikContext();
            var ids = vm.Persons.Select(pp => pp.PersonId);
            var pe  = db.Persons.Where(pp => ids.Contains(pp.Id) && !(/*pp.HasLgota*/ pp.UchForma == UchFormaConsts.Ochnaya)).ToList();

            if (pe.Count == 0)
            {
                return;
            }


            var path = (string.Format("{0}\\_шаблоны\\" + "Письмо об отсутствии льготы.docx", AppDomain.CurrentDomain.BaseDirectory));

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


            Microsoft.Office.Interop.Word.Range range = aDoc.Content;
            range.Find.ClearFormatting();

            var list = new List <string>();

            for (int i = 0; i < pe.Count; i++)
            {
                list.Add($"{i + 1}. {pe[i].Fio}");
            }

            range.Find.Execute(FindText: "{list}", ReplaceWith: string.Join("\r", list), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            aDoc.SaveAs(FileName: otchetDir + @"\Письмо об отсутствии льготы.docx");
            aDoc.Close();
        }
Ejemplo n.º 29
0
        void createDocument()
        {
            object missing = System.Reflection.Missing.Value;

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

            Microsoft.Office.Interop.Word.Document aDoc = null;

            if (File.Exists((string)"C:\\Users\\Ignacio\\Desktop\\CartaMR_Test.docx"))
            {
                DateTime today = DateTime.Now;

                object readOnly  = false;
                object isVisible = false;

                wordApp.Visible = false;

                aDoc = wordApp.Documents.Open("C:\\Users\\Ignacio\\Desktop\\CartaMR_Test.docx", ref missing,
                                              ref readOnly, ref missing, ref missing, ref missing,
                                              ref missing, ref missing, ref missing, ref missing,
                                              ref missing, ref isVisible, ref missing, ref missing,
                                              ref missing, ref missing);

                aDoc.Activate();

                //REPLACE TEXT

                //aDoc.ActiveWindow.Selection.WholeStory();
                //aDoc.ActiveWindow.Selection.Copy();

                //IDataObject data = Clipboard.GetDataObject();
                //richTextBox1.Text = data.GetData(DataFormats.Text).ToString();
                ////aDoc.Close(ref missing, ref missing, ref missing);
            }
            aDoc.SaveAs2(pathSave + "\\PM_" + idPedidoMuestra.ToString() + "_Carta.docx", 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, ref missing);

            aDoc.Close(ref missing, ref missing, ref missing);
        }
Ejemplo n.º 30
0
        private void InsertUnloadFileToDocument(string bookmark, string documentLocation, string unloadLocation)
        {
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();

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

            //Full file name
            object objFileName = documentLocation;
            object visible     = false;
            object readOnly    = false;
            object IsSave      = true;

            object bookMarkName = bookmark;
            object oClassType   = "MSGraph.Chart";
            object oFileName    = unloadLocation;
            object oMissing     = System.Reflection.Missing.Value;
            object missingValue = System.Reflection.Missing.Value;

            try
            {
                //打开文件
                doc = WordApp.Documents.Open(ref objFileName, ref missingValue, ref readOnly, ref missingValue,
                                             ref missingValue, ref missingValue, ref missingValue, ref missingValue,
                                             ref missingValue, ref missingValue, ref missingValue, ref missingValue,
                                             ref missingValue, ref missingValue, ref missingValue,
                                             ref missingValue);
                doc.Activate();
                Microsoft.Office.Interop.Word.Bookmark titleBookmark = doc.Bookmarks.get_Item(ref bookMarkName);
                titleBookmark.Range.InlineShapes.AddOLEObject(ref oClassType, ref oFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                //doc. Close(ref IsSave, ref missingValue, ref missingValue);
            }
            finally
            {
                doc.Close(ref IsSave, ref missingValue, ref missingValue);
            }
        }
Ejemplo n.º 31
0
        private void button_ok_Click(object sender, EventArgs e)
        {
            object fileName = Path.Combine(Application.StartupPath, "Templates\\template_recount.doc");

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

            var counterType = string.Empty;

            switch (comboBox_counterType.SelectedIndex)
            {
            case 0:
                counterType = "хол. воды";
                break;

            case 1:
                counterType = "гор. воды";
                break;

            case 2:
                counterType = "электричетсва";
                break;
            }

            FindAndReplace(wordApp, "{date}", dateTimePicker1.Value.ToString("D"));
            FindAndReplace(wordApp, "{name}", textBox_name.Text);
            FindAndReplace(wordApp, "{address}", textBox_address.Text);
            FindAndReplace(wordApp, "{countertype}", counterType);
            FindAndReplace(wordApp, "{count}", textBox_count.Text);


            Close();
        }
Ejemplo n.º 32
0
        private Microsoft.Office.Interop.Word.Document OpenWordTemplateFile(string FileNameStr)
        {
            Microsoft.Office.Interop.Word.Document oDoc = new Microsoft.Office.Interop.Word.Document();

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

            return oDoc;
        }
Ejemplo n.º 33
0
        public void downOffice()
        {
            try
            {
                var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
                //@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
                var templateName = direc + "办公室函件模板.doc";
                Microsoft.Office.Interop.Word.ApplicationClass wordApp;
                Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
                object Obj_FileName = templateName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;
                wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Object Nothing = System.Reflection.Missing.Value;
                wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                wordDocument.Activate();

                var Oid = Request.GetInt("officeItemID");

                var OfficeBudgetDetail = Database.OfficeBudgetDetails.SingleOrDefault(cti => cti.ID == Oid);

                wordDocument.Bookmarks.get_Item("DocNumber").Range.Text = OfficeBudgetDetail.DocNumber;
                wordDocument.Bookmarks.get_Item("DocName").Range.Text = OfficeBudgetDetail.DocName;
                wordDocument.Bookmarks.get_Item("DocContent").Range.Text = OfficeBudgetDetail.DocContent;
                wordDocument.Bookmarks.get_Item("DocYear").Range.Text = OfficeBudgetDetail.ReportYear;
                wordDocument.Bookmarks.get_Item("DocSource").Range.Text = OfficeBudgetDetail.FundSource.ToString();
                wordDocument.Bookmarks.get_Item("Time").Range.Text = DateTime.Now.ToShortDateString();
                //var OfficeBudgetDetailItem = Database.OfficeBudgetDetailItems.SingleOrDefault(ctii => ctii.OfficeBudgetDetailID == Oid);
                //wordDocument.Bookmarks.get_Item("DocContactor").Range.Text = OfficeBudgetDetailItem.AssetFundApplyItem.ContractItem.BidResultItem.PurchaseOrderItem.PurchasePlanItem.ConstructTaskItem.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Contactor.Name;
                //wordDocument.Bookmarks.get_Item("DocContactorPhone").Range.Text = OfficeBudgetDetailItem.AssetFundApplyItem.ContractItem.BidResultItem.PurchaseOrderItem.PurchasePlanItem.ConstructTaskItem.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Contactor.MobilePhone;

                SaveDocument(wordDocument, wordApp, direc + "办公室函件.doc");

                downLoad(direc + "办公室函件.doc", "办公室函件.doc");

                var downLoadInfo = string.Format("{0}下载设备:{1},办公室函件", User.Name, OfficeBudgetDetail.Operator);
                BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
            }
            catch (System.Exception ex)
            {
                new PackedException("办公室函件", ex).Hanldle();
            }
        }
Ejemplo n.º 34
0
        public void downTable()
        {
            try
            {
                var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
                //@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
                var templateName = direc + "附件1-985大型设备购置论证报告_模板.doc";
                Microsoft.Office.Interop.Word.ApplicationClass wordApp;
                Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
                object Obj_FileName = templateName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;
                wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Object Nothing = System.Reflection.Missing.Value;
                wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                wordDocument.Activate();

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

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

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

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

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

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

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

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

                var downLoadInfo = string.Format("{0}下载设备:{1},购置论证报告", User.Name, memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName);
                BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
            }
            catch (System.Exception ex)
            {
                new PackedException("大型设备购置论证报告", ex).Hanldle();
            }
        }
Ejemplo n.º 35
0
        public void s()
        {
            try
            {
                var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
                //@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
                var templateName = direc + "大型精密仪器设备论证一览表_模板.doc";
                Microsoft.Office.Interop.Word.ApplicationClass wordApp;
                Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
                object Obj_FileName = templateName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;
                wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Object Nothing = System.Reflection.Missing.Value;
                wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                wordDocument.Activate();

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

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

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

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

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

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

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

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

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

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

                var downLoadInfo = string.Format("国资处:{0},下载设备:{1} 的大型设备论证报告", User.Name, memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName);
                BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
            }
            catch (System.Exception ex)
            {
                new PackedException("导出大型精密仪器论证一览表", ex).Hanldle();
            }
        }
Ejemplo n.º 36
0
        // Open a new document
        public void Open()
        {
            oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            oDoc.Activate();
        }
Ejemplo n.º 37
0
        /// <summary>
        /// 附加dot模版文件
        /// </summary>
        private void LoadDotFile(string strDotFile)
        {
            if (!string.IsNullOrEmpty(strDotFile))
            {
                Microsoft.Office.Interop.Word.Document wDot = null;
                if (oWordApplic != null)
                {
                    oDoc = oWordApplic.ActiveDocument;

                    oWordApplic.Selection.WholeStory();

                    //string strContent = oWordApplic.Selection.Text;

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

                    object bkmC = "Content";

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

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

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

                }
            }
        }
Ejemplo n.º 38
0
        /// <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;
            }
        }