Ejemplo n.º 1
1
        public UrlListForm(Word.Document doc)
        {
            InitializeComponent();

            if (doc == null)
                return;
            wordDoc = doc;

            hyperlink_urls = WordUrlManager.GetListOfHyperlinkUrls(doc);
            hyperlink_requests = new HttpWebRequest[hyperlink_urls.Length];
            autofind_urls = WordUrlManager.GetListOfAllUrls(doc);
            autofind_requests = new HttpWebRequest[autofind_urls.Length];
            active_urls = hyperlink_urls;
            active_requests = hyperlink_requests;

            InitializeUrlViewList();

            progressBar.Visible = true;
            if (active_urls.Length == 0)
                progressBar.Visible = false;
            progressBar.Minimum = 0;
            progressBar.Maximum = active_urls.Length;
            progressBar.Step = 1;
            progressBar.Value = 0;

            button_RecheckEveryURL.Enabled = false;
            radioButton_autofindUrls.Enabled = false;
            radioButton_wordHyperlinks.Enabled = false;
            listView.BeginUpdate();

            urlTesterThread = null;
            RestartTestingThread = null;
            urlTesterThread_shouldStop = false;
        }
Ejemplo n.º 2
0
 public void setup()
 {
     wordApp = WordApplicationHelper.GetApplication();
     if (wordApp.Documents.Exists(IOHelpers.FirmAddressTestData))
         wordApp.Documents.First(IOHelpers.FirmAddressTestData).Close(Wd.WdSaveOptions.wdDoNotSaveChanges);
     doc = wordApp.Documents.Open(IOHelpers.FirmAddressTestData.FullName);
 }
        public TEditSidebar(Word.Document WordDoc)
        {
            InitializeComponent();
            AxiomIRISRibbon.Utility.setTheme(this);

            this.tabDebug.Visibility = System.Windows.Visibility.Hidden;
            if (Globals.ThisAddIn.getDebug())
            {
                this.tabDebug.Visibility = System.Windows.Visibility.Visible;
            }

            this.D = Globals.ThisAddIn.getData();
            this.Doc = WordDoc;

            // Initiatlise the tables to hold the XML
            this.DTClauseXML = new DataTable();
            this.DTClauseXML.TableName = "ClauseXML";
            this.DTClauseXML.Columns.Add(new DataColumn("Id", typeof(String)));
            this.DTClauseXML.Columns.Add(new DataColumn("XML", typeof(String)));

            this.CurrentConceptId = "";
            this.CurrentClauseId = "";
            this.CurrentElementId = "";

            this.RefreshConceptList();
            this.GetDropDowns();

            this.ClauseLock = true;
            this.ForceRereshClauseXML = false;
        }
Ejemplo n.º 4
0
 public void CloseWordApp()
 {
     document.Close(ref falseObj, ref  missingObj, ref missingObj);
     application.Quit(ref missingObj, ref  missingObj, ref missingObj);
     document = null;
     application = null;
 }
Ejemplo n.º 5
0
        public void AddToc()
        {
            wordApp = new Application();
            object file = filePath;

            try
            {

                wordDocument = wordApp.Documents.Open(ref file, ref paramMissing, ref paramMissing,
                                    ref paramMissing, ref paramMissing, ref paramMissing,
                                    ref paramMissing, ref paramMissing, ref paramMissing,
                                    ref paramMissing, ref paramMissing, ref paramMissing,
                                    ref paramMissing, ref paramMissing, ref paramMissing,
                                    ref paramMissing
                );

                Range tocRange = wordDocument.Range(0, 0);
                TableOfContents toc = wordDocument.TablesOfContents.Add(tocRange, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing);
                toc.Update();

                int end = toc.Range.End;
                Range tocEnd = wordDocument.Range(end, end);

                tocEnd.InsertParagraphBefore();
                tocEnd.InsertBreak(WdBreakType.wdPageBreak);

            }
            catch (COMException ex)
            {
                throw new InvalidOperationException("Invalid Document", ex);
            }
            finally {
                Dispose();
            }
        }
Ejemplo n.º 6
0
        public A()
        {
            oracon = new OracleConnection("server = 127.0.0.1/orcx; user id = qzdata; password = xie51");
            oracon2 = new OracleConnection("server = 10.5.67.11/pdbqz; user id = qzdata; password = qz9401tw");
            wordapp = new word.Application();
            worddoc = new word.Document();
            worddoc = wordapp.Documents.Add();

            worddoc.SpellingChecked = false;
            worddoc.ShowSpellingErrors = false;

     //       wordapp.Visible = true;
            ta.wordapp = wordapp;
            ta.worddoc = worddoc;
            if (IS_YEAR)
            {
                datestr = dsf.GetDateStr(the_year_begin_int, the_month_begin_int, the_year_end_int, the_month_end_int);
            }
            else
            {
                datestr = dsf.GetDateStr(the_date);
            }
            
       //     datestr_abid = "(" + datestr + "and a.ab_id >=1 and a.ab_id <= 7)";
            datestr_abid = "(" + datestr + "and" + abidstr + ")";
            oracon2.Open();
            orahlper = new OraHelper(oracon2);
            orahlper.feedback = true;

            the_month_begin = new DateTime(the_date.Year, the_date.Month, 1, 0, 0, 0);
            the_month_end = the_month_begin.AddMonths(1).AddSeconds(-1);

        }
Ejemplo n.º 7
0
        public TechDoc2(string TemplateFilename, bool Visible)
        {
            CurrentTechSection = 0;
            CurrentTechLine = 0;
            ItemSectionFormat = "{0}. ";
            ItemLineFormat = "{0}.{1}. ";

            WORDApp = new Word.ApplicationClass();
            WORDApp.Visible = true;

            object useDefaultValue = Type.Missing;
            object visible = Visible;
            object template = TemplateFilename;

            doc = WORDApp.Documents.Add(ref template, ref useDefaultValue, ref useDefaultValue, ref visible);

            //настройка стилей
            Word.Style SectionStyle = doc.Styles[Word.WdBuiltinStyle.wdStyleHeading1];
            SectionStyle.Font.Color = Word.WdColor.wdColorBlack;
            SectionStyle.Font.Name = "Calibri";
            SectionStyle.Font.Size = 16;

            Word.Style NormalStyle = doc.Styles[Word.WdBuiltinStyle.wdStyleNormal];
            NormalStyle.Font.Color = Word.WdColor.wdColorBlack;
            NormalStyle.Font.Name = "Calibri";
            NormalStyle.Font.Size = 12;
            //список таблиц документа
            TablesList = new Dictionary<string, Word.Table>();
            //список литературы
            BiblioList = new List<BiblioSource>();
        }
Ejemplo n.º 8
0
        public WordDocument(String templateName, bool visible)
        {
            List<int> startedWords = new List<int>();

            foreach (Process p in System.Diagnostics.Process.GetProcessesByName("winword"))
            {
                startedWords.Add(p.Id);
            }

            Object missingValue = Missing.Value;
            Object template = templateName;
            if (wordapp == null)
                wordapp = new Word.Application();

            foreach (Process p in System.Diagnostics.Process.GetProcessesByName("winword"))
            {
                if (!startedWords.Contains(p.Id))
                {
                    IDs.Add(p.Id);
                }
            }
            wordapp.Visible = visible;
            doc = wordapp.Documents.Add(ref template,
            ref missingValue, ref missingValue, ref missingValue);
            doc.ActiveWindow.Selection.MoveEnd(Word.WdUnits.wdStory);

            tempFileName = Path.Combine(Path.GetDirectoryName(templateName), tempFileName);
        }
Ejemplo n.º 9
0
 public String getAttrValueInTag(String tag, String attr, String subject)
 {
     if (log.IsInfoEnabled) log.Info("Begin");
     if (log.IsDebugEnabled) log.Debug("getAttrValueInTag(tag: " + tag + ", attr: " + attr + ")");
     /* Declaración de variables */
     String subjectString = null;
     String result = null;
     String pattern = null;
     Regex regexObj = null;
     Match matchResults = null;
     RegexOptions options = RegexOptions.IgnoreCase;
     /* Inicializamos variables */
     ActiveDocument = Globals.ThisAddIn.Application.ActiveDocument;
     pattern = @"\[" + tag + ".*?" + attr + @"=("".*?""|'.*?'|[^\ \]]*).*?\]";
     pattern = "\\[" + tag + ".*?" + attr + "=(\\\".*?\\\"|\\'.*?\\'|[^\\ \\]]*).*?\\]";
     subjectString = ActiveDocument.Content.Text;
     if (subject != null)
         subjectString = subject;
     /* Verificamos que haya coincidencia */
     regexObj = new Regex(pattern, options);
     matchResults = regexObj.Match(subjectString);
     if (matchResults.Success)
     {
         result = matchResults.Groups[1].Value;
         if (result.EndsWith("\"") || result.EndsWith("'"))
         {
             result = result.Substring(1, result.Length - 2);
         }
     }
     if (log.IsInfoEnabled) log.Info("End");
     return result;
 }
Ejemplo n.º 10
0
        public override void Convert(String inputFile, String outputFile)
        {
            Object nothing = System.Reflection.Missing.Value;
            try
            {
                if (!File.Exists(inputFile))
                {
                    throw new ConvertException("File not Exists");
                }

                if (IsPasswordProtected(inputFile))
                {
                    throw new ConvertException("Password Exist");
                }

                app = new Word.Application();
                docs = app.Documents;
                doc = docs.Open(inputFile, false, true, false, nothing, nothing, true, nothing, nothing, nothing, nothing, false, false, nothing, true, nothing);
                doc.ExportAsFixedFormat(outputFile, Word.WdExportFormat.wdExportFormatPDF, false, Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 1, 1, Word.WdExportItem.wdExportDocumentContent, false, false, Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, false, false, nothing);
            }
            catch (Exception e)
            {
                release();
                throw new ConvertException(e.Message);
            }
            release();
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Generates a word instance
 /// </summary>
 /// <param name="settings"></param>
 private WordGenerator(NamedLookup settings, bool silent) : base(settings, silent)
 {
     app = new Word.Application();
     app.Visible = !this.silent;
     document = app.Documents.Add(Type.Missing, Type.Missing,
     Word.WdNewDocumentType.wdNewBlankDocument, !this.silent);
     document.UserControl = !this.silent;
 }
Ejemplo n.º 12
0
 public WordDocument()
 {
     Object missingValue = Missing.Value;
     Object template = Type.Missing;
     if (wordapp == null)
         wordapp = new Word.Application();
     doc = wordapp.Documents.Add(ref template,
     ref missingValue, ref missingValue, ref missingValue);
 }
Ejemplo n.º 13
0
 private void ComposeDocument(RepositoryInfo repositoryInfo, IList<Issue> issues, Document document)
 {
     foreach (Range tmpRange in document.StoryRanges)
     {
         Replace(repositoryInfo.ProjectName, ProjectNameContainer, tmpRange);
         Replace(repositoryInfo.Hash, VersionContainer, tmpRange);
         Replace(repositoryInfo.Date, PublicationDateContainer, tmpRange);
         Replace(issues.ToText(), SolvedTicketsContainer, tmpRange);
     }
 }
Ejemplo n.º 14
0
 public AnnotationDisplay(Word.Document doc)
 {
     this.document = doc;
     displayedAnnotations = new List<Microsoft.Office.Interop.Word.Comment>();
     document.TextLineEnding = Microsoft.Office.Interop.Word.WdLineEndingType.wdLFOnly;
     document.Content.TextRetrievalMode.IncludeFieldCodes = true;
     document.Content.TextRetrievalMode.IncludeHiddenText = true;
     deletedCharsMap = document.Content.MapDeletedCharsOffsets();
     clearContent = document.Content.GetCleanedText();
 }
Ejemplo n.º 15
0
 private void documentListBox_SelectedIndexChanged(object sender, EventArgs e)
 {
     // When a document is selected in the list, change the current selected document
     if (documentListBox.SelectedIndex >= 0)
     {
         if (wordObj != null)
         {
             docObj = wordObj.Documents[documentListBox.SelectedIndex + 1];
         }
     }
 }
Ejemplo n.º 16
0
 public ConfirmForm(ThisAddIn myThisAddIn, Word.Application WordApp, object FileName)
 {
     InitializeComponent();
     this.myThisAddIn = myThisAddIn;
     this.WordApp = WordApp;
     this.FileName = FileName;
     OldDocument = WordApp.ActiveDocument;
     isCancelFlag = false;
     ClosePrintPreviewThread = new Thread(new ThreadStart(ClosePrintPreviewListener));
     ClosePrintPreviewThread.Start();
 }
Ejemplo n.º 17
0
 private void translateButton_Click(object sender, RibbonControlEventArgs e)
 {
     document = (Word.Document)inspector.WordEditor;
     if (document != null)
     {
         string selected = document.Application.Selection.Text;
         if (selected.Length > 0)
         {
             document.Application.Selection.Text = translate(selected);
         }
     }
 }
Ejemplo n.º 18
0
        private void WordOpen(string strFileName)
        {
            object fileName = strFileName;
            object readOnly = false;
            object isVisible = true;
            

            _WordDoc = _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, ref missing, ref missing, ref missing, ref missing);

            _WordDoc.Activate();
        }
Ejemplo n.º 19
0
 public Generator(System.Data.DataTable dt)
 {
     path = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "uploadfile\\岗位责任书.doc";
     wordApp = new MSWord.Application();
     if (File.Exists((string)path))
     {
         File.Delete((string)path);
     }
     Nothing = Missing.Value;
     wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
     wordApp.Selection.ParagraphFormat.LineSpacing = 16;
     this.dt = dt;
 }
Ejemplo n.º 20
0
 public DocParser(object fileName)
 {
     WordApp = new Word.Application();
     doc = 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 isVisible,
                                                     ref missing, ref missing, ref missing,
                                                     ref missing);
     parsedFile = new ContentFile()
     {
         contentRaw = doc.WordOpenXML,
         contentText = GetFileContent(),
     };
 }
Ejemplo n.º 21
0
 public override void Close()
 {
     try
     {
         if (oDoc != null) oDoc.Close(WdSaveOptions.wdDoNotSaveChanges, missing, missing);
         oDoc = null;
         object save = false;
         if (oWord != null) oWord.Quit(ref save, ref missing, ref missing);
         oWord = null;
     }
     catch (Exception)
     {
         oDoc = null;
         oWord = null;
         throw new InternalErrorException();
     }
 }
Ejemplo n.º 22
0
 /// <summary>
 /// 打开Word文档
 /// </summary>
 public void Open()
 {
     object path = this.fileName;
     cls = new Microsoft.Office.Interop.Word.Application();
     cls.Visible = true;
     //object missing = System.Reflection.Missing.Value;
     //object strNewPath = "E:\\堆芯\\附件4-CoreEasy输出参数表.docx";
     try
     {
         doc = cls.Documents.Open(ref path, 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);
         openState = true;
     }
     catch
     {
         openState = false;
         MessageBox.Show("打开< "+ path +" >失败!","提示");
     }
 }
        public bool SaveContract(bool ForceSave, bool SaveDoc)
        {
            string strFileAttached = _fileName;
            //Save the Contract
            Globals.ThisAddIn.RemoveSaveHandler(); // remove the save handler to stop the save calling the save etc.

            Globals.ThisAddIn.ProcessingStart("Save Contract");
            DataReturn dr;
              _doc = Globals.ThisAddIn.Application.ActiveDocument;

            dr = AxiomIRISRibbon.Utility.HandleData(_d.SaveVersion(_versionid, _matterid, _templateid, _versionName, _versionNumber));
            if (!dr.success) return false;
            _versionid = dr.id;

            if (SaveDoc)
            {

                //Save the file as an attachment
                //save this to a scratch file
                Globals.ThisAddIn.ProcessingUpdate("Save Scratch");
             //   string filename = AxiomIRISRibbon.Utility.SaveTempFile(_versionid);
                _doc.SaveAs2(FileName: strFileAttached, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);

                //Save a copy!
                Globals.ThisAddIn.ProcessingUpdate("Save Copy");
                string filenamecopy =  AxiomIRISRibbon.Utility.SaveTempFile(_versionid + "X");
                Word.Document dcopy = Globals.ThisAddIn.Application.Documents.Add(strFileAttached, Visible: false);
                dcopy.SaveAs2(FileName: filenamecopy, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);

                var docclose = (Microsoft.Office.Interop.Word._Document)dcopy;
                docclose.Close();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(docclose);

                //Now save the file - change this to always save as the version name

                Globals.ThisAddIn.ProcessingUpdate("Save To SalesForce");
                string vfilename = _versionName.Replace(" ", "_") + ".docx";
                dr = AxiomIRISRibbon.Utility.HandleData(_d.UpdateFile(_attachmentid, vfilename, filenamecopy));

            }
            Globals.ThisAddIn.AddSaveHandler(); // add it back in
            Globals.ThisAddIn.ProcessingStop("End");
            return true;
        }
        public void GeneraDocumentoWord()
        {
            oWord = new Microsoft.Office.Interop.Word.Application();
            oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            Microsoft.Office.Interop.Word.Paragraph par = oDoc.Content.Paragraphs.Add(ref oMissing);

            foreach (Funcionarios funcionario in funcionarios)
            {
                par.Range.Font.Bold = 0;
                par.Range.Font.Size = Convert.ToInt32(ConfigurationManager.AppSettings["FontSize"]);
                par.Range.Font.Name = ConfigurationManager.AppSettings["FontFamily"];

                par.Range.Text = String.Format("{0} {1} {2}", funcionario.Puesto, funcionario.Apellidos, funcionario.Nombre);
                par.Range.InsertParagraphAfter();
            }

            oWord.Visible = true;
        }
Ejemplo n.º 25
0
        public void Dispose()
        {
            if (wordDocument != null)
            {
                wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                wordDocument = null;
            }

            // Quit Word and release the ApplicationClass object.
            if (wordApp != null)
            {
                wordApp.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                wordApp = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Ejemplo n.º 26
0
        private void populateListBox()
        {
            try
            {
                wordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
            }
            catch
            {
                // No word
                documentListBox.Items.Clear();
                wordObj = null;
                docObj = null;
            }

            try
            {
                if (wordObj != null)
                {
                    int currentIndex = documentListBox.SelectedIndex;

                    string[] documentNames = new string[wordObj.Documents.Count];

                    for (int i = 0; i < wordObj.Documents.Count; i++)
                    {
                        documentNames[i] = wordObj.Documents[i + 1].Name.ToString();
                    }

                    documentListBox.Items.Clear();
                    documentListBox.Items.AddRange(documentNames);

                    documentListBox.SelectedIndex = currentIndex;
                }
            }
            catch
            {
                // No word
                documentListBox.Items.Clear();
                wordObj = null;
                docObj = null;
            }
        }
Ejemplo n.º 27
0
        Word.Range wordRange; // диапазон документа Word

        #endregion Fields

        #region Constructors

        public WordApplication(string fileToWord)
            : base(fileToWord)
        {
            //создаем обьект приложения word
            application = new Word.Application();

            // создаем путь к файлу шаблона
            Object templatePathObj = fileToWord;

            // если вылетим не этом этапе, приложение останется открытым
            try
            {
                document = application.Documents.Add(ref  templatePathObj, ref missingObj, ref missingObj, ref missingObj);
            }

            catch (Exception error)
            {
                CloseWordApp();
                throw error;
            }
        }
        //public async Task<IReadOnlyCollection<Word>> GetWordsAsync(n.Document nativeDocument)
        //{
        //    var words = new ConcurrentBag<Word>();

        //    await System.Threading.Tasks.Task.Run(
        //        () =>
        //        {
        //            Parallel.ForEach(
        //                nativeDocument.Content.Words.Cast<n.Range>(),
        //                nativeWord =>
        //                {
        //                    var trimmedText = _textServant.GetTrimmedText(nativeWord);
        //                    if (!string.IsNullOrEmpty(trimmedText))
        //                    {
        //                        var font = new Models.Font(nativeWord.Font.Name, nativeWord.Font.Size);
        //                        words.Add(new Word(nativeWord.Start, trimmedText, font));
        //                    }
        //                });
        //        });

        //    var sortedWords = words.OrderBy(word => word.StartPosition).ToList();
        //    return sortedWords;
        //}

        public Task <Characters> GetCharactersAsync(n.Document nativeDocument)
        {
            throw new System.NotImplementedException();
        }
Ejemplo n.º 29
0
        private void CreateWordDocument(object filename, object SaveAs)//file name is the temple file y saveAs es el que generamos
        {
            // List<int> processesbeforegen = getRunningProcesses();


            Word.Application wordApp = new Word.Application(); // se crea una word aplication
            object           missing = Missing.Value;          //la función tiene muchos paramtros y no queremos utilizarlos todos

            Word.Document myWordDoc = null;                    //myWordDoc es el documento que vamos a generar y guardar en saveAs file

            if (File.Exists((string)filename))
            {
                object readOnly  = false;//tenemos que escribir en ese documento
                object isVisible = false;
                wordApp.Visible = false;

                myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,//abrimos el machote, ponemos el nombre del maquite que quereos abrir
                                                   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
                if (textBox1.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<escrituranumeroradicacion>", textBox1.Text);
                }
                if (textBox2.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<volumenradicacion>", textBox2.Text);
                }
                if (textBox3.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<de cujus>", textBox3.Text);
                }
                if (textBox4.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<albacea>", textBox4.Text);
                }

                if (textBox5.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<testamentonumero>", textBox5.Text);
                }

                if (textBox6.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<testamentovolumen>", textBox6.Text);
                }

                if (textBox7.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<notariotestamento>", textBox7.Text);
                }

                if (textBox8.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<numeronotariotestamento>", textBox8.Text);
                }

                if (textBox9.Text == "")
                {
                }
                else
                {
                    string contenido = textBox9.Text, contenido1 = "", contenido2 = "", contenido3 = "", contenido4 = "", contenido5 = "";
                    string contenido6 = "", contenido7 = "", contenido8 = "", contenido9 = "", contenido10 = "";
                    int    conte = contenido.Length;
                    int    conte1;

                    conte1     = conte / 10;
                    contenido1 = contenido.Substring(0, conte1);//(DE DÓNDE, CUÁNTOS)

                    contenido2 = contenido.Substring(conte1, conte1);

                    contenido3 = contenido.Substring((conte1 + conte1), (conte1));

                    contenido4  = contenido.Substring((3 * conte1), conte1);
                    contenido5  = contenido.Substring((4 * conte1), conte1);
                    contenido6  = contenido.Substring((5 * conte1), conte1);
                    contenido7  = contenido.Substring((6 * conte1), conte1);
                    contenido8  = contenido.Substring((7 * conte1), conte1);
                    contenido9  = contenido.Substring((8 * conte1), conte1);
                    contenido10 = contenido.Substring((9 * conte1), conte1);



                    //this.FindAndReplace(wordApp, "<clausulastestamento>", textBox9.Text);//dynamicTextBox.Text;textBox9.Text
                    this.FindAndReplace(wordApp, "<clausulastestamento1>", contenido1);

                    this.FindAndReplace(wordApp, "<clausulastestamento2>", contenido2);

                    this.FindAndReplace(wordApp, "<clausulastestamento3>", contenido3);

                    this.FindAndReplace(wordApp, "<clausulastestamento4>", contenido4);
                    this.FindAndReplace(wordApp, "<clausulastestamento5>", contenido5);
                    this.FindAndReplace(wordApp, "<clausulastestamento6>", contenido6);
                    this.FindAndReplace(wordApp, "<clausulastestamento7>", contenido7);
                    this.FindAndReplace(wordApp, "<clausulastestamento8>", contenido8);
                    this.FindAndReplace(wordApp, "<clausulastestamento9>", contenido9);
                    this.FindAndReplace(wordApp, "<clausulastestamento10>", contenido10);
                }

                if (textBox10.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<nacionalidad>", textBox10.Text);
                }

                if (textBox11.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<ciudadfallecimiento>", textBox11.Text);
                }

                if (textBox12.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<estadocivilalbacea>", textBox12.Text);
                }

                if (textBox13.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<ocupacionalbacea>", textBox13.Text);
                }

                if (textBox14.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<originarioalbacea>", textBox14.Text);
                }

                if (textBox15.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<domicilioalbacea>", textBox15.Text);
                }

                if (textBox16.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<codigopostalalbacea>", textBox16.Text);
                }

                if (textBox17.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<curpalbacea>", textBox17.Text);
                }

                if (textBox18.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<rfcalbacea>", textBox18.Text);
                }

                if (textBox19.Text == "")
                {
                }
                else
                {
                    this.FindAndReplace(wordApp, "<inealbacea>", textBox19.Text);
                }


                this.FindAndReplace(wordApp, "<fecha>", dateTimePicker1.Value.ToLongDateString());
                this.FindAndReplace(wordApp, "<fechatestamento>", dateTimePicker2.Value.ToLongDateString());
                this.FindAndReplace(wordApp, "<fechanacimientoalbacea>", dateTimePicker3.Value.ToLongDateString());
                this.FindAndReplace(wordApp, "<fechafallecimiento>", dateTimePicker4.Value.ToLongDateString());
                this.FindAndReplace(wordApp, "<fechacertificadotestamento>", dateTimePicker5.Value.ToLongDateString());

                this.FindAndReplace(wordApp, "<fecha1>", DateTime.Now.ToLongDateString());
            }
            else
            {
                MessageBox.Show("File not Found!");
            }
            //SaveAs2 es el lugar en el que se va a guardar, SaveAs es el camino para generar el documento
            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(); //esto sí estaba
            wordApp.Quit();    // esto sí estaba
            //MessageBox.Show("File Created!");

            //List<int> processesaftergen = getRunningProcesses();
            //killProcesses(processesbeforegen, processesaftergen);
        }
Ejemplo n.º 30
0
        public static async Task <List <CockleFilePdf> > CreatePdf(
            IProgress <string> _progress,
            System.Threading.CancellationToken _cancellationToken,
            List <CockleFile> _latestFiles,
            List <CockleFile> _selectedFiles,
            bool _isSingleTicket,
            string _destinationFolderConvertedFiles)
        {
            var pdfCreationModel = new PdfCreationModel(
                _progress,
                _cancellationToken,
                _latestFiles,
                _selectedFiles,
                _isSingleTicket,
                _destinationFolderConvertedFiles);

            bool exceptionThrownInAwait = false; // tracks excptn in await

            List <CockleFile> filesSelectedForConversion;
            bool convertAll = false;

            // get files from grid if null
            if (null == pdfCreationModel.latestFiles)
            {
                filesSelectedForConversion = pdfCreationModel.selectedFiles;
            }
            else
            {
                convertAll = true; filesSelectedForConversion = pdfCreationModel.latestFiles;
            }

            if (filesSelectedForConversion.Count < 1)
            {
                throw new Exception();
            }


            // begin AWAIT
            var filesToReturnFromTask = await System.Threading.Tasks.Task.Run(() =>
            {
                // I think this line can go, as can the OpenMSWordAndCreatePdfs class
                //var files = new OpenMSWordAndCreatePdfs().FilesPrintedSuccessfully;

                //instantiate Word Application & Document
                Word.Application app = new Word.Application();
                app.Visible          = true;
                Word.Document doc    = null;

                //get original printer & prepare to create PDF
                var current_printer   = app.ActivePrinter;
                var adobe_pdf_printer = "Adobe PDF";
                app.ActivePrinter     = adobe_pdf_printer;

                // collection of special class to track files
                var filesPrintedSuccessfully = new List <FilePrintedSuccessfully>();
                //the Word file saved to scratch
                try
                {
                    // counter to track files printed
                    int i = 0;

                    // loop through files
                    foreach (CockleFile fileSelected in filesSelectedForConversion)
                    {
                        // cancel if requested
                        try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                        catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }

                        // catch pdf files saved to Current
                        if (System.IO.Path.GetExtension(fileSelected.FullName).Equals(".pdf"))
                        {
                            // don't try to open, just save to scratch and add to list
                            var pdfFileInCurrent = System.IO.Path.Combine(@"C:\scratch", System.IO.Path.GetFileName(fileSelected.FullName));
                            System.IO.File.Copy(fileSelected.FullName, pdfFileInCurrent);
                            // here, just a string & no cover length
                            filesPrintedSuccessfully.Add(
                                new FilePrintedSuccessfully
                            {
                                CockleFile    = null,
                                TempWordFile  = null,
                                PdfFilename   = pdfFileInCurrent,
                                Filetype      = SourceFileTypeEnum.Camera_Ready, // may have to adjust type here
                                LengthOfCover = null
                            });
                            continue;
                        }

                        // Open docx files in Word, clean up, and convert
                        try
                        {
                            doc = app.Documents.Open(FileName: fileSelected.FullName, ReadOnly: true);
                        }
                        catch
                        {
                            System.Diagnostics.Debug.WriteLine($"{fileSelected.FullName} failed to open");
                        }

                        // save to c:\scratch (overwriting existing files)
                        var tempFileSavedToScratch = System.IO.Path.Combine(@"c:\scratch", System.IO.Path.GetFileName(fileSelected.FullName));
                        if (System.IO.File.Exists(tempFileSavedToScratch))
                        {
                            System.IO.File.Delete(tempFileSavedToScratch);
                        }
                        doc.SaveAs2(FileName: tempFileSavedToScratch);

                        // ctrl shift f9 (had problem with links in index: removes links from main story)
                        Word.Range r = doc.StoryRanges[Word.WdStoryType.wdMainTextStory];
                        r.Fields.Unlink();

                        // delete footer
                        MicrosoftWordStaticClass.WordDoc_DeleteFooters(fileSelected, doc);

                        // line to capture length of cover
                        int?lengthOfCover = null;
                        if (fileSelected.FileType == SourceFileTypeEnum.Cover)
                        {
                            lengthOfCover = MicrosoftWordStaticClass.CaptureCoverLength(doc);
                        }

                        // cancel if requested
                        try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                        catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }

                        // print to pdf, reporting progress
                        var newPdfConvertedFromWord = string.Empty;
                        newPdfConvertedFromWord     = MicrosoftWordStaticClass.PrintToFile(app, doc.FullName);
                        // halt process here: wait for COM background status to end
                        while (app.BackgroundPrintingStatus > 0)
                        {
                            System.Diagnostics.Debug.WriteLine($"app.BackgroundPrintingStatus is {app.BackgroundPrintingStatus}");
                            // cancel if requested
                            try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }
                        while (app.BackgroundSavingStatus > 0)
                        {
                            System.Diagnostics.Debug.WriteLine($"app.BackgroundSavingStatus is {app.BackgroundSavingStatus}");
                            // cancel if requested
                            try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }

                        // add to files_printed list
                        filesPrintedSuccessfully.Add(
                            new FilePrintedSuccessfully
                        {
                            CockleFile    = fileSelected,
                            TempWordFile  = tempFileSavedToScratch,
                            PdfFilename   = newPdfConvertedFromWord,
                            Filetype      = SourceFileTypeEnum.Unrecognized,
                            LengthOfCover = lengthOfCover
                        });

                        // report to ui

                        // make sure file exists before closing
                        while (!System.IO.File.Exists(newPdfConvertedFromWord))
                        {
                            System.Diagnostics.Debug.WriteLine($"Waiting to print to pdf: {newPdfConvertedFromWord}");
                            // cancel if requested
                            try { pdfCreationModel.cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }
                        // close document & delete temp file
                        doc.Close(SaveChanges: Word.WdSaveOptions.wdDoNotSaveChanges);
                        System.IO.File.Delete(tempFileSavedToScratch);
                        // increment counter
                        i++;
                    }// end for loop to convert each files
                }
                //catch (OperationCanceledException ex) { }
                catch { }
                finally
                {
                    app.ActivePrinter = current_printer;
                    app?.Quit();
                }
                if (exceptionThrownInAwait)
                {
                    // close app
                    app.ActivePrinter = current_printer;
                    app?.Quit();
                    // try to clean folder
                    filesPrintedSuccessfully.ForEach(f =>
                    {
                        if (System.IO.File.Exists(f.PdfFilename))
                        {
                            System.IO.File.Delete(f.PdfFilename);
                        }
                        if (System.IO.File.Exists(f.TempWordFile))
                        {
                            System.IO.File.Delete(f.TempWordFile);
                        }
                    });
                    return(null);
                }

                // block until all files exist
                while (filesPrintedSuccessfully?.Count != filesSelectedForConversion.Count)
                {
                    ;
                }

                #region POINT OF NO RETURN IN CONVERSION
                // convert files to CockleFilePdf
                var cockleFilePdfsPrintedSuccessfully = new List <CockleFilePdf>();
                foreach (var _f in filesPrintedSuccessfully)
                {
                    if (_f.LengthOfCover == null && _f.CockleFile == null)
                    {
                        cockleFilePdfsPrintedSuccessfully.Add(new CockleFilePdf(_f.PdfFilename, _f.Filetype));
                    }
                    else
                    {
                        cockleFilePdfsPrintedSuccessfully.Add(
                            new CockleFilePdf(_f.CockleFile, _f.PdfFilename, _f.LengthOfCover));
                    }
                }

                // test whether all converted files have same ticket
                bool allConvertedFilesSameTicket = cockleFilePdfsPrintedSuccessfully
                                                   .TrueForAll(f => f.TicketNumber ==
                                                               cockleFilePdfsPrintedSuccessfully.First().TicketNumber);

                // move files to unique folder
                if ((allConvertedFilesSameTicket || pdfCreationModel.isSingleTicket) &&
                    cockleFilePdfsPrintedSuccessfully.Count() > 0)    // PROBLEM HERE !!!
                {
                    var firstFile    = cockleFilePdfsPrintedSuccessfully.First();
                    string timeStamp = string.Format("({0} {1}, {2}, {3})", DateTime.Now.ToString("MMM") /*Oct*/,
                                                     DateTime.Now.ToString("dd") /*09*/, DateTime.Now.ToString("yyy") /*2015*/,
                                                     DateTime.Now.ToString("T").ToLower() /*10:58:44 AM*/ /*, len_text*/)
                                       .Replace(':', ' ');
                    var folderName      = $"{firstFile.TicketNumber} {firstFile.Attorney} {timeStamp}";
                    var scratchLocation = @"c:\scratch";

                    var newFolder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(scratchLocation, folderName));

                    foreach (var f in cockleFilePdfsPrintedSuccessfully)
                    {
                        try
                        {
                            var new_filename = System.IO.Path.Combine(newFolder.FullName, f.Filename);
                            System.IO.File.Move(f.FullName, new_filename);

                            // associate new location with CockleFilePdf
                            f.FullName = new_filename;
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex);
                        }
                    }
                }

                // set destination property
                pdfCreationModel.destinationFolderConvertedFiles = System.IO.Path.GetDirectoryName(cockleFilePdfsPrintedSuccessfully.First().FullName);

                // set ranks of pdfs before returning
                pdfCreationModel.setCockleFilePdfRanks(cockleFilePdfsPrintedSuccessfully);

                // combine files into single pdf
                if (convertAll)
                {
                    var createMergedPdfAcrobat = new Models.MergePdf.CreateMergedPDFAcrobat(cockleFilePdfsPrintedSuccessfully);

                    CockleFilePdf mergedCockleFile = null;

                    // add combined file to list of cocklefilepdf files
                    if (System.IO.File.Exists(createMergedPdfAcrobat.CombinedPdfFilename))
                    {
                        mergedCockleFile =
                            new CockleFilePdf(
                                createMergedPdfAcrobat.CombinedPdfFilename,
                                filesSelectedForConversion.First().Attorney,
                                filesSelectedForConversion.First().TicketNumber,
                                SourceFileTypeEnum.Combined_Pdf,
                                "pdf",
                                null);
                        cockleFilePdfsPrintedSuccessfully.Add(mergedCockleFile);
                    }

                    int len_of_cover = -1;
                    if (cockleFilePdfsPrintedSuccessfully.Any(f => f.FileType == SourceFileTypeEnum.Cover))
                    {
                        len_of_cover = cockleFilePdfsPrintedSuccessfully.Where(
                            f => f.FileType == SourceFileTypeEnum.Cover).FirstOrDefault().CoverLength ?? -1;
                    }

                    // remove combined pdf file
                    var cockleFilePdfsPrintedSuccessfullyMinusCombinedFile = cockleFilePdfsPrintedSuccessfully.ToList();
                    cockleFilePdfsPrintedSuccessfullyMinusCombinedFile.Remove(mergedCockleFile);

                    var createImposedPdfiTextSharp =
                        new Models.Imposition.ImposeFullConvertedTicket(
                            pdfCreationModel.destinationFolderConvertedFiles,
                            cockleFilePdfsPrintedSuccessfullyMinusCombinedFile,
                            len_of_cover,
                            TypeOfBindEnum.ProgramDecidesByPageCount);

                    // add imposed files to list of cocklefilepdf files
                    if (createImposedPdfiTextSharp.ImposedFilesCreated.All(f => System.IO.File.Exists(f.FullName)))
                    {
                        createImposedPdfiTextSharp.ImposedFilesCreated.ForEach(f =>
                        {
                            cockleFilePdfsPrintedSuccessfully.Add(
                                new CockleFilePdf(
                                    f.FullName,
                                    filesSelectedForConversion.First().Attorney,
                                    filesSelectedForConversion.First().TicketNumber,
                                    SourceFileTypeEnum.Imposed_Cover_and_Brief,
                                    "pdf",
                                    null));
                        });
                    }
                }
                #endregion


                return(cockleFilePdfsPrintedSuccessfully);
            });

            if (exceptionThrownInAwait)
            {
                throw new OperationCanceledException();
            }
            return(filesToReturnFromTask);
        }
        private void button5_Click(object sender, EventArgs e)
        {
            оплаты uRow = bindingSource1.Current as оплаты;

            клОплата.оплата = uRow.оплата;
            de = new domofon14Entities();

            string[] aMez = de.месяцы
                            .OrderBy(n => n.месяц)
                            .Select(n => n.наимен)
                            .ToArray();

            var услугиQuery = de.оплачено
                              .Where(n => n.оплата == клОплата.оплата)
                              .GroupBy(n => new { n.услуги, n.год, n.сумма })
                              .Select(n => new
            {
                n.Key.услуги,
                n.Key.услуги.наимен,
                n.Key.услуги.порядок,
                цена  = n.Key.сумма,
                сумма = n.Sum(p => p.сумма),
                n.Key.год,
                minMez = n.Min(p => p.месяц),
                maxMez = n.Max(p => p.месяц)
            })
                              .OrderBy(n => n.порядок);



            //dsТабель1.квитанция.Clear();
            квитанцияЛист.Clear();
            foreach (var kRow in услугиQuery)
            {
                //  dsТабель1.за_месяца.Clear();
                //           за_месяцЛист.Clear();

                //                dsТабель.квитанцияRow NewRow = dsТабель1.квитанция.NewквитанцияRow();
                квитанция NewRow = new квитанция();


                NewRow.услуга        = kRow.услуги.услуга;
                NewRow.наимен_услуги = kRow.наимен;
                NewRow.тариф         = kRow.цена;
                NewRow.месяцы        = "";
                NewRow.начало        = aMez[kRow.minMez - 1];
                if (kRow.maxMez > kRow.minMez)
                {
                    NewRow.конец = aMez[kRow.maxMez - 1];
                }
                NewRow.сумма = kRow.сумма;
                NewRow.год   = kRow.год;
                квитанцияЛист.Add(NewRow);

                //dsТабель1.квитанция.Rows.Add(NewRow);
            }


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

            string curDir = System.IO.Directory.GetCurrentDirectory();

            object шаблон = curDir + @"\квитанция.dot";

            if (!System.IO.File.Exists(шаблон.ToString()))
            {
                MessageBox.Show("Нет файла " + шаблон.ToString());
                return;
            }


            клФирма.init();
            клФилиал.init();

            Word.Document o = oWord.Documents.Add(Template: шаблон);
            //  oWord.Application.Visible = true;
            o.Bookmarks["менеджер"].Range.Text  = uRow.сотрудники.фио;
            o.Bookmarks["менеджер2"].Range.Text = uRow.сотрудники.фио;

            o.Bookmarks["дата"].Range.Text  = uRow.дата.ToLongDateString();
            o.Bookmarks["дата2"].Range.Text = uRow.дата.ToLongDateString();

            o.Bookmarks["филиал"].Range.Text          = клФилиал.наимен;
            o.Bookmarks["адрес_филиала"].Range.Text   = клФилиал.адрес.Trim();
            o.Bookmarks["телефон_филиала"].Range.Text = клФилиал.deRow.телефон.Trim();

            o.Bookmarks["филиал2"].Range.Text         = клФилиал.наимен;
            o.Bookmarks["адрес2филиала"].Range.Text   = клФилиал.адрес.Trim();
            o.Bookmarks["телефон2филиала"].Range.Text = клФилиал.deRow.телефон.Trim();


            o.Bookmarks["номер_квитанции"].Range.Text = uRow.номер.ToString();
            o.Bookmarks["номер2квитанции"].Range.Text = uRow.номер.ToString();

            o.Bookmarks["фио"].Range.Text = uRow.клиенты.фио;
            //string адрес_абонента = "ул. " + uRow.наимен_улицы.Trim()
            //    + "   д. " + uRow.номер_дома.Trim() + " "
            //    + uRow.корпус.Trim()
            //    + " кв. " + uRow.квартира.Trim();
            string адрес_абонента = uRow.клиенты.адрес;

            if (uRow.клиенты.ввод > 0)
            {
                адрес_абонента += " ввод " + uRow.клиенты.ввод.ToString();
            }

            o.Bookmarks["адрес"].Range.Text = адрес_абонента;

            o.Bookmarks["фио2"].Range.Text   = uRow.клиенты.фио;
            o.Bookmarks["адрес2"].Range.Text = адрес_абонента;

            o.Bookmarks["наимен_фирмы"].Range.Text   = клФирма.deRow.наимен.Trim();
            o.Bookmarks["наимен2фирмы"].Range.Text   = клФирма.deRow.наимен.Trim();
            o.Bookmarks["инн"].Range.Text            = "ИНН " + клФирма.deRow.инн.Trim();
            o.Bookmarks["инн2"].Range.Text           = "ИНН " + клФирма.deRow.инн.Trim();
            o.Bookmarks["кпп"].Range.Text            = "КПП " + клФирма.deRow.код.Trim();
            o.Bookmarks["кпп2"].Range.Text           = "КПП " + клФирма.deRow.код.Trim();
            o.Bookmarks["расчетный_счет"].Range.Text = "р/с " + клФирма.deRow.р_счет.Trim();
            o.Bookmarks["расчетный2счет"].Range.Text = "р/с " + клФирма.deRow.р_счет.Trim();
            o.Bookmarks["наимен_банка"].Range.Text   = " " + клФирма.deRow.банк.Trim();
            o.Bookmarks["наимен2банка"].Range.Text   = " " + клФирма.deRow.банк.Trim();
            o.Bookmarks["город"].Range.Text          = клФирма.deRow.город.Trim();
            o.Bookmarks["город2"].Range.Text         = клФирма.deRow.город.Trim();
            o.Bookmarks["кор_счет"].Range.Text       = "к/с " + клФирма.deRow.к_счет.Trim();
            o.Bookmarks["кор2счет"].Range.Text       = "к/с " + клФирма.deRow.к_счет.Trim();
            o.Bookmarks["адрес_фирмы"].Range.Text    = клФирма.deRow.адрес.Trim();
            o.Bookmarks["адрес2фирмы"].Range.Text    = клФирма.deRow.адрес.Trim();


            int     j     = 1;
            decimal итого = 0;

            foreach (квитанция kRow in квитанцияЛист)
            {
                string текст1 = kRow.начало + " - " + kRow.конец + " " + kRow.год.ToString();
                j++;
                o.Tables[5].Cell(j, 1).Range.Text = kRow.наимен_услуги;
                o.Tables[5].Cell(j, 2).Range.Text = kRow.тариф.ToString("0.00;#;#");
                o.Tables[5].Cell(j, 3).Range.Text = текст1;
                o.Tables[5].Cell(j, 4).Range.Text = kRow.сумма.ToString("0.00");
                o.Tables[5].Rows.Add();
                итого += kRow.сумма;

                o.Tables[11].Cell(j, 1).Range.Text = kRow.наимен_услуги;
                o.Tables[11].Cell(j, 2).Range.Text = kRow.тариф.ToString("0.00;#;#");
                o.Tables[11].Cell(j, 3).Range.Text = текст1;
                o.Tables[11].Cell(j, 4).Range.Text = kRow.сумма.ToString("0.00");
                o.Tables[11].Rows.Add();
            }
            o.Tables[5].Cell(j + 1, 4).Range.Text  = итого.ToString("0.00");
            o.Tables[11].Cell(j + 1, 4).Range.Text = итого.ToString("0.00");


            клTemp.Caption            = o.ActiveWindow.Caption;
            oWord.Application.Visible = true;
        }
Ejemplo n.º 32
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.Request.QueryString["Id"] != null)
                {
                    Guid   quoteId  = Guid.Parse(this.Request.QueryString["Id"]);
                    string fileName = new ContractCoverHelper().ExecuteContractCover(quoteId, this.Server.MapPath("/"));
                    if (!(fileName != string.Empty))
                    {
                        return;
                    }
                    FileInfo fileInfo = new FileInfo(fileName);
                    if (fileInfo.Exists)
                    {
                        if (ContractCoverHelper.projectNameGlobal == "857 NEF 12 Merter" || ContractCoverHelper.projectNameGlobal == "855 NEF 13 Merter" ||
                            ContractCoverHelper.projectNameGlobal == "845 NEF 98 Points" || ContractCoverHelper.projectNameGlobal == "877 NEF 11 Kağıthane")
                        {
                            this.Response.ClearContent();
                            //this.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                            this.Response.AppendHeader("Content-Disposition", "attachment;filename*=UTF-8''" + Uri.EscapeDataString("Sözleşme Kapağı.docx"));
                            this.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                            this.Response.ContentType = "application/octet-stream";
                            string filename = "/DocumentMerge/Document/" + quoteId.ToString().Replace("{", "").Replace("}", "") + "/" + fileInfo.Name;
                            this.Response.TransmitFile(filename);
                            this.Response.End();
                        }
                        else
                        {
                            if (File.Exists(fileName.Replace("docx", "pdf")))
                            {
                                File.Delete(fileName.Replace("docx", "pdf"));
                            }
                            string wordFilename = @"C:/NEF.Web.Documents/DocumentMerge/Document/" + quoteId.ToString().Replace("{", "").Replace("}", "") + "/" + fileInfo.Name;
                            string pdfPath      = @"C:/NEF.Web.Documents/DocumentMerge/Document/" + quoteId.ToString().Replace("{", "").Replace("}", "") + "/";

                            Microsoft.Office.Interop.Word.Application appWord      = new Microsoft.Office.Interop.Word.Application();
                            Microsoft.Office.Interop.Word.Document    wordDocument = new Microsoft.Office.Interop.Word.Document();

                            wordDocument = appWord.Documents.Open(wordFilename);
                            appWord.Documents.Open(wordFilename);
                            wordDocument.ExportAsFixedFormat(pdfPath + fileInfo.Name.Replace("docx", "pdf"), WdExportFormat.wdExportFormatPDF);
                            fileInfo = new FileInfo(fileName.Replace("docx", "pdf"));
                            if (fileInfo.Exists)
                            {
                                appWord.Documents.Close(Type.Missing, Type.Missing, Type.Missing);
                                appWord.Quit(Type.Missing, Type.Missing, Type.Missing);

                                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(appWord);
                                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wordDocument);

                                Response.ClearHeaders();
                                Response.ContentType = "application/pdf";
                                Response.Clear();
                                Response.AppendHeader("Content-Disposition", "attachment;filename*=UTF-8''" + Uri.EscapeDataString("Sözleşme Kapağı.pdf"));
                                Response.TransmitFile(fileName.Replace("docx", "pdf"));
                                Response.End();
                            }
                        }
                    }
                }
                else
                {
                    this.lblUyari.Text = "Satış Id Eksik.";
                }
            }
            catch (Exception ex)
            {
                this.lblUyari.Text = ex.Message;
            }
        }
Ejemplo n.º 33
0
 private void DocumentClose()
 {
     oDoc = null;
 }
Ejemplo n.º 34
0
        private static bool CrearWord()
        {
            try
            {
                object           ObjMiss = System.Reflection.Missing.Value;
                Word.Application ObjWord = new Word.Application();

                object parametro = "C:\\xampp\\htdocs\\plantilla.docx";
                //nombre de las variables del word
                object rutCliente      = "rutCliente";
                object nombreCliente   = "nombreCliente";
                object telefonoCliente = "telefonoCliente";
                object servicioExtra   = "servicioExtra";
                object fechaCheckIn    = "fechaCheckIn";
                object fechaCheckOut   = "fechaCheckOut";
                object nombreDep       = "nombreDep";
                object direccionDep    = "direccionDep";
                object cantBanios      = "cantBanios";
                object cantHuesped     = "cantHuesped";
                object cantHabitacion  = "cantHabitacion";
                object entregaTv       = "entregaTv";
                object entregaAir      = "entregaAir";
                object entregaLlave    = "entregaLlave";
                object entregaRegalo   = "entregaRegalo";
                object valorTotal      = "valorTotal";

                Word.Document ObjDoc    = ObjWord.Documents.Open(parametro, ObjMiss);
                Word.Range    rutClient = ObjDoc.Bookmarks.get_Item(ref rutCliente).Range;
                rutClient.Text = "23210664-6";
                Word.Range nombreClient = ObjDoc.Bookmarks.get_Item(ref nombreCliente).Range;
                nombreClient.Text = "Juan Colonia";
                Word.Range telefonoClient = ObjDoc.Bookmarks.get_Item(ref telefonoCliente).Range;
                telefonoClient.Text = "965845162";
                Word.Range servicioExtr = ObjDoc.Bookmarks.get_Item(ref servicioExtra).Range;
                servicioExtr.Text = "Si";
                Word.Range fechaCheckI = ObjDoc.Bookmarks.get_Item(ref fechaCheckIn).Range;
                fechaCheckI.Text = "15-11-2020";
                Word.Range fechaCheckOu = ObjDoc.Bookmarks.get_Item(ref fechaCheckOut).Range;
                fechaCheckOu.Text = "19-11-2020";

                Word.Range nombreDe = ObjDoc.Bookmarks.get_Item(ref nombreDep).Range;
                nombreDe.Text = "departamento 1";
                Word.Range direccionDe = ObjDoc.Bookmarks.get_Item(ref direccionDep).Range;
                direccionDe.Text = "av siempre viva 123";
                Word.Range cantBanio = ObjDoc.Bookmarks.get_Item(ref cantBanios).Range;
                cantBanio.Text = "2";
                Word.Range cantHuespe = ObjDoc.Bookmarks.get_Item(ref cantHuesped).Range;
                cantHuespe.Text = "3";
                Word.Range cantHabitacio = ObjDoc.Bookmarks.get_Item(ref cantHabitacion).Range;
                cantHabitacio.Text = "3";

                Word.Range entregaT = ObjDoc.Bookmarks.get_Item(ref entregaTv).Range;
                entregaT.Text = "Si";
                Word.Range entregaAi = ObjDoc.Bookmarks.get_Item(ref entregaAir).Range;
                entregaAi.Text = "Si";
                Word.Range entregaLlav = ObjDoc.Bookmarks.get_Item(ref entregaLlave).Range;
                entregaAi.Text = "Si";
                Word.Range entregaRegal = ObjDoc.Bookmarks.get_Item(ref entregaRegalo).Range;
                entregaRegal.Text = "Si";
                Word.Range valorTota = ObjDoc.Bookmarks.get_Item(ref valorTotal).Range;
                valorTota.Text = "59.990";


                object rangorutCliente      = rutClient;
                object rangonombreCliente   = nombreClient;
                object rangotelefonoCliente = telefonoClient;
                object rangoservicioExtra   = servicioExtr;
                object rangofechaCheckIn    = fechaCheckI;
                object rangofechaCheckOut   = fechaCheckOu;
                object rangonombreDep       = nombreDe;
                object rangodireccionDep    = direccionDe;
                object rangocantBanios      = cantBanio;
                object rangocantHuesped     = cantHuespe;
                object rangocantHabitacion  = cantHabitacio;
                object rangoentregaTv       = entregaT;
                object rangoentregaAir      = entregaAi;
                object rangoentregaLlave    = entregaLlav;
                object rangoentregaRegalo   = entregaRegal;
                object rangovalorTotal      = valorTota;

                ObjDoc.Bookmarks.Add("rutCliente", ref rangorutCliente);
                ObjDoc.Bookmarks.Add("nombreCliente", ref rangonombreCliente);
                ObjDoc.Bookmarks.Add("telefonoCliente", ref rangotelefonoCliente);
                ObjDoc.Bookmarks.Add("servicioExtra", ref rangoservicioExtra);
                ObjDoc.Bookmarks.Add("fechaCheckIn", ref rangofechaCheckIn);
                ObjDoc.Bookmarks.Add("fechaCheckOut", ref rangofechaCheckOut);
                ObjDoc.Bookmarks.Add("nombreDep", ref rangonombreDep);
                ObjDoc.Bookmarks.Add("direccionDep", ref rangodireccionDep);
                ObjDoc.Bookmarks.Add("cantBanios", ref rangocantBanios);
                ObjDoc.Bookmarks.Add("cantHuesped", ref rangocantHuesped);
                ObjDoc.Bookmarks.Add("cantHabitacion", ref rangocantHabitacion);
                ObjDoc.Bookmarks.Add("entregaTv", ref rangoentregaTv);
                ObjDoc.Bookmarks.Add("entregaAir", ref rangoentregaAir);
                ObjDoc.Bookmarks.Add("entregaLlave", ref rangoentregaLlave);
                ObjDoc.Bookmarks.Add("entregaRegalo", ref rangoentregaRegalo);
                ObjDoc.Bookmarks.Add("valorTotal", ref rangovalorTotal);

                string RutaSave = "C:\\Users\\juanc\\projects\\Portafolio\\Escritorio\\S_ArriendoDepartamento\\Arriendo.Test\\plantilla\\";

                object   FileName  = (object)(RutaSave + "WordGenerado");
                Document document2 = ObjDoc;

                document2.SaveAs2(ref FileName);
                ObjWord.Documents.Close();
                ObjWord.Visible = false;
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        //Word转换成pdf
        /// <summary>
        /// 把Word文件转换成为PDF格式文件
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public bool DOCConvertToPDF(string sourcePath, string targetPath)
        {
            bool result = false;

            Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;
            object paramMissing = Type.Missing;

            Word.ApplicationClass wordApplication = new Word.ApplicationClass();
            Word.Document         wordDocument    = null;
            try
            {
                object paramSourceDocPath  = sourcePath;
                string paramExportFilePath = targetPath;

                Word.WdExportFormat paramExportFormat           = exportFormat;
                bool paramOpenAfterExport                       = false;
                Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Word.WdExportRange       paramExportRange       = Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage   = 0;
                Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps         = true;
                bool paramKeepIRM = true;
                Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags   = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1      = false;

                wordDocument = wordApplication.Documents.Open(
                    ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing);

                if (wordDocument != null)
                {
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                     paramExportFormat, paramOpenAfterExport,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                                     ref paramMissing);
                }
                result = true;
            }
            catch (Exception e)
            {
                result = false;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }
Ejemplo n.º 36
0
        public void Export_Data_To_Word(DataGridView DGV, string filename)
        {
            if (DGV.Rows.Count != 0)
            {
                int RowCount    = DGV.Rows.Count;
                int ColumnCount = DGV.Columns.Count;
                Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

                //add rows
                int r = 0;
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    for (r = 0; r <= RowCount - 1; r++)
                    {
                        if (c == 2 || c == 0)
                        {
                            DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
                        }
                    } //end row loop
                }     //end column loop

                Word.Document oDoc = new Word.Document();
                oDoc.Application.Visible = true;

                //page orintation
                oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;


                dynamic oRange = oDoc.Content.Application.Selection.Range;
                string  oTemp  = "";
                for (r = 0; r <= RowCount - 1; r++)
                {
                    string t   = ". ";
                    bool   key = false;
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        try
                        {
                            if (list[c] == Int32.Parse(DataArray[r, c].ToString()))
                            {
                                key = true;
                            }
                        }
                        catch (ArgumentOutOfRangeException ex) { }
                        catch (FormatException ex) { }
                        catch (NullReferenceException ex) { }

                        if (key)
                        {
                            oTemp = oTemp + DataArray[r, c] + t;
                            t     = "\n";
                        }
                    }
                    if (list.Count != 0 && key)
                    {
                        list.RemoveAt(0);
                    }
                }

                //table format
                oRange.Text = oTemp;
                //object oMissing = Missing.Value;
                //object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;
                //object ApplyBorders = true;
                //object AutoFit = true;
                //object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;

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

                // oRange.Select();
                // oDoc.Application.Selection.Text = "324325465";
                //oDoc.Application.Selection.Tables[1].Select();
                //oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                //oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
                //oDoc.Application.Selection.Tables[1].Rows[1].Select();
                //oDoc.Application.Selection.InsertRowsAbove(1);
                //oDoc.Application.Selection.Tables[1].Rows[1].Select();
                //oDoc.Application.Selection.Text = "324325465";
                ////header row style
                //oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
                //oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma";
                //oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

                //add header row manually
                //for (int c = 0; c <= ColumnCount - 1; c++)
                //{
                //    oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
                //}

                //table style
                //oDoc.Application.Selection.Tables[1].Rows[1].Select();
                //oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                //header text
                //foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)
                //{
                //    Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                //    headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
                //    headerRange.Text = "Header";
                //    headerRange.Font.Size = 16;
                //    headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //}

                //save the file

                oDoc.SaveAs(filename);

                //NASSIM LOUCHANI
            }
        }
Ejemplo n.º 37
0
        public static string autoTextColumn;  //Перенос текста


        public void Export_Data_To_Word(DataGridView DGV, string filename, string headerTable)
        {
            try
            {
                if (DGV.Rows.Count != 0)
                {
                    int RowCount    = DGV.Rows.Count;
                    int ColumnCount = DGV.Columns.Count;
                    Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

                    //add rows
                    int r = 0;
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        for (r = 0; r <= RowCount - 1; r++)
                        {
                            DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
                        } //end row loop
                    }     //end column loop

                    Word.Document oDoc = new Word.Document();
                    oDoc.Application.Visible = true;

                    //page orintation
                    oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;


                    dynamic oRange = oDoc.Content.Application.Selection.Range;
                    string  oTemp  = "";
                    for (r = 0; r <= RowCount - 1; r++)
                    {
                        for (int c = 0; c <= ColumnCount - 1; c++)
                        {
                            oTemp = oTemp + DataArray[r, c] + "\t";
                        }
                    }

                    //table format
                    oRange.Text = oTemp;

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

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

                    oRange.Select();

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

                    //header row style
                    oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold      = 1;
                    oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Times New Roman";
                    oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

                    //add header row manually
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
                    }

                    //table style
                    oDoc.Application.Selection.Tables[1].set_Style("Классическая таблица 2");
                    oDoc.Application.Selection.Tables[1].Rows[1].Select();
                    oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                    //header text
                    foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)
                    {
                        Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                        headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
                        headerRange.Text      = headerTable;
                        headerRange.Font.Size = 16;
                        headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }

                    //save the file
                    oDoc.SaveAs2(filename);

                    //NASSIM LOUCHANI
                }
            }
            catch { }
        }
Ejemplo n.º 38
0
        private void Button1_Click(object sender, EventArgs e)
        {
            using (Test11Entities2 db = new Test11Entities2())
            {
                var Doctor       = comboBox2.Text;
                var Pachient     = comboBox1.Text;
                var DatePriema   = dateTimePicker1.Value;
                var Spechialnost = label6.Text;

                List <PriemPacientov> PriemPacientovs = new List <PriemPacientov>();
                PriemPacientovs.Add(new PriemPacientov {
                    Doctor = Doctor, Pacient = Pachient, Date_of_priema = DatePriema, Specialnost = Spechialnost
                });

                db.PriemPacientov.AddRange(PriemPacientovs);
                db.SaveChanges();

                MessageBox.Show("Данные сохранены");


                int IDPriema         = 0;
                var PrienPachientovs = db.PriemPacientov; //Находим айди талона

                foreach (PriemPacientov tl in PrienPachientovs)
                {
                    if (tl.Pacient == Pachient && tl.Doctor == Doctor && tl.Date_of_priema == DatePriema)
                    {
                        IDPriema = tl.id;
                    }
                }

                object missing = Type.Missing;

                Object Pa = "E:\\Durka.docx";                      // Путь к шаблону

                Word.Application wordApp = new Word.Application(); // Создаём объект приложения

                Word.Document wordDoc = new Word.Document();

                wordDoc = wordApp.Documents.Add(ref Pa, ref missing, ref missing, ref missing);


                Word.Bookmarks wBookmarks = wordDoc.Bookmarks;

                wordDoc.Bookmarks["PACHIENT"].Range.Text     = Pachient; // источник текста(может быть элемент массива)
                wordDoc.Bookmarks["DOCTOR"].Range.Text       = Doctor;
                wordDoc.Bookmarks["SPECHIALNOST"].Range.Text = Spechialnost;
                wordDoc.Bookmarks["DATEP"].Range.Text        = Convert.ToString(DatePriema);

                object mi     = "E:\\VisualStudioWorks\\Шаблоны ворд для заполнения дурки\\Талон на прием к доктору " + Doctor + " № " + IDPriema + ".docx"; // путь куда и под каким именем будет сохраняться файл
                string WayDoc = "E:\\VisualStudioWorks\\Шаблоны ворд для заполнения дурки\\Талон на прием к доктору " + Doctor + " № " + IDPriema + ".docx";
                wordDoc.SaveAs(ref mi, 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);


                wordDoc.Close();

                System.Diagnostics.Process myProcess = new Process();
                myProcess.StartInfo.FileName = WayDoc; //имя своего файла(может быть exe файл)

                myProcess.StartInfo.Verb = "Open";

                myProcess.StartInfo.CreateNoWindow = false;

                myProcess.Start();


                this.Hide();
                Form5 m = new Form5();
                m.Show();
            }
        }
Ejemplo n.º 39
0
         private void button1_Click(object sender, EventArgs e)
         {
             Word.Application word = new Word.Application();
             Word.Document document = new Word.Document();
 
             // Define an object to pass to the word API for missing parameters
             object missing = Type.Missing;
 
             try
             {
                 // Everything that word accepts must be an object
                 object fileName = @"R:\Project\Proposals\TestMe.docx";
 
                 object readOnly = true;
                 document = word.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);
 
                 document.Activate();
 
                 String propsalTitle = "Lorem ipsum dolor sit amet";
                 this.FindAndReplace(word, "Enter Proposal Title Here", propsalTitle, true);
 
                 string defaultTechDesc = "ENTER RELEVANT TECHNICAL INFORMATION ABOUT PROJECT HERE.  USE PICTURES WHEN AVAILABLE AND APPLICABLE.";
                 String techDesc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer tempor rutrum libero sed dapibus. Praesent vehicula mollis ultricies. Maecenas vulputate enim vitae nisi gravida euismod. Morbi aliquam lacus enim. Donec suscipit mi at sem mollis id gravida sapien tempor. Donec in sem at quam dignissim placerat et a urna. Maecenas nec tellus vel ipsum volutpat aliquet nec ut tortor. Nulla facilisi. Donec vel quam lectus, ac mattis sapien. Nullam a justo nisl, sit amet congue velit. Ut imperdiet, velit id luctus vulputate, augue libero consectetur eros, quis gravida quam orci ac lacus. Curabitur mollis, mi sit amet interdum feugiat, risus lacus dignissim metus, ut luctus nulla orci a ante. Nunc et turpis vel ipsum faucibus rhoncus eu eu velit. Sed interdum, magna sit amet porta euismod, orci felis tincidunt mauris, et iaculis ligula arcu molestie justo. Duis sollicitudin purus ut purus hendrerit adipiscing. Donec aliquam ultricies eros. ";
                 this.FindAndReplace(word, defaultTechDesc, techDesc, false);
 
                 String deliverables = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
                 this.FindAndReplace(word, "ENTER ALL ITEMS THAT WILL BE DELIVERD OVER PERIOD OF PERFORMANCE FOR THIS PROJECT.", deliverables, false);
 
                 String Contact = "Jenny";
                 this.FindAndReplace(word, "ENTER POINT OF CONTACT HERE", Contact, false);
 
                 String PocTitle = "ipsum";
                 this.FindAndReplace(word, "ENTER POC TITLE HERE", PocTitle, false);
 
                 String PocTeam = "dolor";
                 this.FindAndReplace(word, "ENTER POC TEAM NAME HERE", PocTeam, false);
 
                 String PocPhone = "867-5309";
                 this.FindAndReplace(word, "ENTER POC PHONE NUMBER HERE", PocPhone, false);
 
                 String PocEmail = "*****@*****.**";
                 this.FindAndReplace(word, "ENTER POC EMAIL HERE", PocEmail, false);
 
                 // Tables
                 Word.Table table = document.Tables[1];
 
                 int x = 0;
                 double totalCost = 0;
                 Word.Row row;
                 for (int i = 1; i <= 10; i++)
                 {
                     x = i + 1;
                     row = table.Rows.Add(ref missing);
                     row.Cells[1].Range.Text = "Task New " + i;
                     row.Cells[2].Range.Text = String.Format("{0:C}", i);
                     table.Cell(x, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                     table.Cell(x, 1).Range.Font.Bold = 0;
                     table.Cell(x, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                     table.Cell(x, 2).Range.Font.Bold = 0;
                     totalCost = totalCost + i;
                 }
 
                 x = x + 1;
                 row = table.Rows.Add(ref missing);
                 row.Cells[1].Range.Text = "Total";
                 row.Cells[2].Range.Text = String.Format("{0:C}", totalCost);
                 table.Cell(x, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                 table.Cell(x, 1).Range.Font.Bold = 1;
                 table.Cell(x, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                 table.Cell(x, 2).Range.Font.Bold = 1;
 
                 object newFileName = @"R:\Project\Proposals\TestMe2.docx";
 
                 document.SaveAs(ref newFileName,
                                 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);
             }
 
             catch (Exception ex)
             {
                 // Message here
             }
             finally
             {
                 document.Close(ref missing, 
                                ref missing, 
                                ref missing);
 
                 word.Application.Quit(ref missing, 
                                       ref missing, 
                                       ref missing);
             }
         }
Ejemplo n.º 40
0
        //结束评分
        private void dispose()
        {
            try
            {
                Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
                Object originalFormat = Type.Missing;
                Object routeDocument = Type.Missing;

                stuDoc.Close(ref saveChanges,
                  ref originalFormat, ref routeDocument);
                stuDoc = null;

                ansDoc.Close(ref saveChanges,
                  ref originalFormat, ref routeDocument);
                ansDoc = null;

                word.Quit(ref saveChanges,
                    ref originalFormat, ref routeDocument);
                word = null;
            }
            catch { }
            GC.Collect();

            System.Diagnostics.Process[] pro = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process pro1 in pro)
                if (pro1.ProcessName.ToLower() == "winword")
                    pro1.Kill();
        }
Ejemplo n.º 41
0
        private bool print(Word.Document myDoc, string strPrinterName, int iPageStart, int iPageEnd)
        {
            DocProtectManager.protectSave(myDoc);
            string strOldPrintName = null;

            //当strPrinterName 为空时使用默认打印机
            if (strPrinterName != null)
            {
                strOldPrintName = myDoc.Application.ActivePrinter;
                myDoc.Application.ActivePrinter = strPrinterName;
            }

            /*
             *  PrintOut (
             *      [OptionalAttribute] ref Object Background,
             *      [OptionalAttribute] ref Object Append,
             *      [OptionalAttribute] ref Object Range,
             *      [OptionalAttribute] ref Object OutputFileName,
             *      [OptionalAttribute] ref Object From,
             *      [OptionalAttribute] ref Object To,
             *      [OptionalAttribute] ref Object Item,
             *      [OptionalAttribute] ref Object Copies,
             *      [OptionalAttribute] ref Object Pages,
             *      [OptionalAttribute] ref Object PageType,
             *      [OptionalAttribute] ref Object PrintToFile,
             *      [OptionalAttribute] ref Object Collate,
             *      [OptionalAttribute] ref Object ActivePrinterMacGX,
             *      [OptionalAttribute] ref Object ManualDuplexPrint,
             *      [OptionalAttribute] ref Object PrintZoomColumn,
             *      [OptionalAttribute] ref Object PrintZoomRow,
             *      [OptionalAttribute] ref Object PrintZoomPaperWidth,
             *      [OptionalAttribute] ref Object PrintZoomPaperHeight
             * )
             */
            try
            {
                object missing            = System.Reflection.Missing.Value;
                object Background         = true;
                object Range              = Word.WdPrintOutRange.wdPrintRangeOfPages;
                object Copies             = 1;
                object PageType           = Word.WdPrintOutPages.wdPrintAllPages;
                object PrintToFile        = false;
                object Collate            = false;
                object ActivePrinterMacGX = missing;
                object ManualDuplexPrint  = false;
                object PrintZoomColumn    = 1;
                object PrintZoomRow       = 1;
                object objPage            = iPageStart.ToString() + "-" + iPageEnd.ToString();
                myDoc.PrintOut(ref Background, ref missing, ref Range, ref missing,
                               ref missing, ref missing, ref missing, ref Copies,
                               ref objPage, ref PageType, ref PrintToFile, ref Collate,
                               ref missing, ref ManualDuplexPrint, ref PrintZoomColumn,
                               ref PrintZoomRow, ref missing, ref missing);
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
            finally
            {
                DocProtectManager.unprotectSave(myDoc);
                if (strOldPrintName != null)
                {
                    myDoc.Application.ActivePrinter = strOldPrintName;
                }
            }
        }
Ejemplo n.º 42
0
        public void Export_Data_To_Word(DataGridView DGV, string filename)
        {
            if (DGV.Rows.Count != 0)
            {
                int RowCount    = DGV.Rows.Count;
                int ColumnCount = DGV.Columns.Count;
                Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

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

                Word.Document oDoc = new Word.Document();
                oDoc.Application.Visible = true;

                oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;


                dynamic oRange = oDoc.Content.Application.Selection.Range;
                string  oTemp  = "";
                for (r = 0; r <= RowCount - 1; r++)
                {
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        oTemp = oTemp + DataArray[r, c] + "\t";
                    }
                }

                oRange.Text = oTemp;
                object oMissing        = Missing.Value;
                object Separator       = Word.WdTableFieldSeparator.wdSeparateByTabs;
                object ApplyBorders    = true;
                object AutoFit         = true;
                object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;

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

                oRange.Select();

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

                oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold      = 1;
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma";
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
                }

                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)

                {
                    Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
                    headerRange.Text      = "Подтверждённые записи";
                    headerRange.Font.Size = 16;
                    headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }
                oDoc.SaveAs(filename, ref oMissing, ref oMissing, ref oMissing,
                            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                            ref oMissing, ref oMissing);
            }
        }
Ejemplo n.º 43
0
        ///<summary>
        ///Процедура формирования документа
        ///</summary>
        ///<param name="type">Тип документа</param>
        ///<param name="name">Название документа</param>
        ///<param name="table">результирующая таблица</param>
        public void Document_Create(Document_Type type, string name, DataTable table)
        {
            //Получение данных о документе
            Configuration_class configuration_Class = new Configuration_class();

            configuration_Class.Document_Configuration_Get();
            switch (name != "" || name != null)
            {
            case (true):
                switch (type)
                {
                case (Document_Type.Check):
                    //Открытие приложения и документа в нём
                    word.Application application = new word.Application();
                    word.Document    document    = application.Documents.Add(Visible: true);
                    //Формирование документа
                    try
                    {
                        //Начало
                        word.Range range = document.Range(0, 0);
                        //Поля
                        document.Sections.PageSetup.LeftMargin   = application.CentimetersToPoints((float)Configuration_class.doc_Left_Merge);
                        document.Sections.PageSetup.RightMargin  = application.CentimetersToPoints((float)Configuration_class.doc_Right_Merge);
                        document.Sections.PageSetup.TopMargin    = application.CentimetersToPoints((float)Configuration_class.doc_Top_Merge);
                        document.Sections.PageSetup.BottomMargin = application.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge);
                        //Присвоение текстового значения в абзац
                        range.Text = Configuration_class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интервалы в абзаце
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        //Шрифт
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        //Параграф (один Enter)
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Название документа
                        word.Paragraph Document_Name = document.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;
                        Document_Name.Range.Text       = "Выгрузка чека";
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Создание таблицы
                        word.Paragraph statparg   = document.Paragraphs.Add();
                        word.Table     stat_table = document.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count);
                        //Настройка таблицы
                        stat_table.Borders.InsideLineStyle       = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Borders.OutsideLineStyle      = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Rows.Alignment                = word.WdRowAlignment.wdAlignRowCenter;
                        stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table.Range.Font.Size               = 11;
                        stat_table.Range.Font.Name               = "Times New Roman";
                        //Заполнение таблицы
                        for (int row = 1; row <= table.Rows.Count; row++)
                        {
                            for (int col = 1; col <= table.Columns.Count; col++)
                            {
                                stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString();
                            }
                        }
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Строка даты создания
                        word.Paragraph Footparg = document.Paragraphs.Add();
                        Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString());
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            //Сохранение документа
                            document.SaveAs2(name + "DOC", word.WdSaveFormat.wdFormatDocument);
                            //Закрытие документа
                            document.Close(SaveChanges: false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        application.Quit();
                    }
                    break;

                case (Document_Type.MarkSchemes):
                    //Открытие приложения, создание документа (книги) и листа в нём.
                    excel.Application application_ex = new excel.Application();
                    excel.Workbook    workbook       = application_ex.Workbooks.Add();
                    //excel.Worksheet worksheet = (excel.Worksheet)workbook.ActiveSheet;
                    excel.Worksheet worksheet = workbook.ActiveSheet;
                    try
                    {
                        worksheet.Name        = "MarketerDoc";
                        worksheet.Cells[1][1] = "Отчёт о работе отдела маркетинга";
                        worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count + 1]].Merge();
                        //Заполнение таблицы
                        for (int row = 0; row < table.Rows.Count; row++)
                        {
                            for (int col = 0; col < table.Columns.Count; col++)
                            {
                                worksheet.Cells[row + 3, col + 1] = table.Rows[row][col].ToString();
                            }
                        }
                        //Работа со стилем таблицы
                        excel.Range border1 = worksheet.Range[worksheet.Cells[3, 1], worksheet.Cells[table.Rows.Count + 3][table.Columns.Count]];
                        border1.Borders.LineStyle   = excel.XlLineStyle.xlContinuous;
                        border1.VerticalAlignment   = excel.XlVAlign.xlVAlignCenter;
                        border1.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter;
                        //Дата документа
                        worksheet.Cells[2][table.Rows.Count + 3] = string.Format("Дата создания {0}", DateTime.Now.ToString());
                        //Объединение ячеек
                        worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2], worksheet.Cells[table.Rows.Count + 3, table.Columns.Count + 2]].Merge();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        //Сохранение и выход
                        workbook.SaveAs(name, application_ex.DefaultSaveFormat);
                        workbook.Close();
                        application_ex.Quit();
                    }
                    break;

                case (Document_Type.Order):
                    //Открытие приложения и документа в нём
                    word.Application application_or = new word.Application();
                    word.Document    document_or    = application_or.Documents.Add(Visible: true);
                    //Формирование документа
                    try
                    {
                        //Начало
                        word.Range range = document_or.Range(0, 0);
                        //Поля
                        document_or.Sections.PageSetup.LeftMargin   = application_or.CentimetersToPoints((float)Configuration_class.doc_Left_Merge);
                        document_or.Sections.PageSetup.RightMargin  = application_or.CentimetersToPoints((float)Configuration_class.doc_Right_Merge);
                        document_or.Sections.PageSetup.TopMargin    = application_or.CentimetersToPoints((float)Configuration_class.doc_Top_Merge);
                        document_or.Sections.PageSetup.BottomMargin = application_or.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge);
                        //Присвоение текстового значения в абзац
                        range.Text = Configuration_class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интервалы в абзаце
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        //Шрифт
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        //Параграф (один Enter)
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        //Название документа
                        word.Paragraph Document_Name = document_or.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;
                        Document_Name.Range.Text       = table.Rows[0][0].ToString();
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        //Создание таблицы
                        word.Paragraph statparg      = document_or.Paragraphs.Add();
                        word.Paragraph Document_Text = document_or.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Text.Format.Alignment  = word.WdParagraphAlignment.wdAlignParagraphLeft;
                        Document_Text.Format.LeftIndent = (float)1.25;
                        Document_Text.Range.Font.Name   = "Times New Roman";
                        Document_Text.Range.Font.Size   = 14;
                        Document_Text.Range.Text        = table.Rows[0][1].ToString();
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            //Сохранение документа
                            document_or.SaveAs2(name + "PDF", word.WdSaveFormat.wdFormatPDF);
                            //Закрытие документа
                            document_or.Close(SaveChanges: false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        application_or.Quit();
                    }
                    break;

                case (Document_Type.Storage):
                    //Открытие приложения и документа в нём
                    word.Application application_St = new word.Application();
                    word.Document    document_St    = application_St.Documents.Add(Visible: true);
                    //Формирование документа
                    try
                    {
                        //Начало
                        word.Range range = document_St.Range(0, 0);
                        //Поля
                        document_St.Sections.PageSetup.LeftMargin   = application_St.CentimetersToPoints((float)Configuration_class.doc_Left_Merge);
                        document_St.Sections.PageSetup.RightMargin  = application_St.CentimetersToPoints((float)Configuration_class.doc_Right_Merge);
                        document_St.Sections.PageSetup.TopMargin    = application_St.CentimetersToPoints((float)Configuration_class.doc_Top_Merge);
                        document_St.Sections.PageSetup.BottomMargin = application_St.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge);
                        //Присвоение текстового значения в абзац
                        range.Text = Configuration_class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интервалы в абзаце
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        //Шрифт
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        //Параграф (один Enter)
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        //Название документа
                        word.Paragraph Document_Name = document_St.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;
                        Document_Name.Range.Text       = "Выгрузка чека";
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        //Создание таблицы
                        word.Paragraph statparg   = document_St.Paragraphs.Add();
                        word.Table     stat_table = document_St.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count);
                        //Настройка таблицы
                        stat_table.Borders.InsideLineStyle       = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Borders.OutsideLineStyle      = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Rows.Alignment                = word.WdRowAlignment.wdAlignRowCenter;
                        stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table.Range.Font.Size               = 11;
                        stat_table.Range.Font.Name               = "Times New Roman";
                        //Заполнение таблицы
                        for (int row = 1; row <= table.Rows.Count; row++)
                        {
                            for (int col = 1; col <= table.Columns.Count; col++)
                            {
                                stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString();
                            }
                        }
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        //Строка даты создания
                        word.Paragraph Footparg = document_St.Paragraphs.Add();
                        Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString());
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            //Сохранение документа
                            document_St.SaveAs2(name + "DOC", word.WdSaveFormat.wdFormatDocument);
                            //Закрытие документа
                            document_St.Close(SaveChanges: false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        application_St.Quit();
                    }
                    break;
                }
                break;

            case (false):
                MessageBox.Show("Введите название документа");
                break;
            }
        }
Ejemplo n.º 44
0
        public static bool CreateWordDocParagraph(string qname, string[][] qdata, IVsThreadedWaitDialog2 dlg)
        {
            //InitializeVariables();
            System.Net.WebClient webclient = new System.Net.WebClient();
            webclient.Credentials = System.Net.CredentialCache.DefaultCredentials;

            var           application = new MSWord.Application();
            var           document    = new MSWord.Document();
            object        missing     = System.Reflection.Missing.Value;
            int           pagewidth   = 800;
            bool          bcanceled;
            int           progress = 1;
            StringBuilder strbld   = new StringBuilder();

            MSWord.WdBuiltinStyle[] hstyles = new MSWord.WdBuiltinStyle[8];
            hstyles[0] = MSWord.WdBuiltinStyle.wdStyleHeading1;
            hstyles[1] = MSWord.WdBuiltinStyle.wdStyleHeading2;
            hstyles[2] = MSWord.WdBuiltinStyle.wdStyleHeading3;
            hstyles[3] = MSWord.WdBuiltinStyle.wdStyleHeading4;
            hstyles[4] = MSWord.WdBuiltinStyle.wdStyleHeading5;
            hstyles[5] = MSWord.WdBuiltinStyle.wdStyleHeading6;
            hstyles[6] = MSWord.WdBuiltinStyle.wdStyleHeading7;
            hstyles[7] = MSWord.WdBuiltinStyle.wdStyleHeading8;

            application.Visible       = true;
            application.WindowState   = MSWord.WdWindowState.wdWindowStateMinimize;
            application.DisplayAlerts = MSWord.WdAlertLevel.wdAlertsNone;
            document = application.Documents.Add();
            //document.PageSetup.Orientation = MSWord.WdOrientation.wdOrientLandscape;
            document.PageSetup.LeftMargin   = 20;
            document.PageSetup.RightMargin  = 20;
            document.PageSetup.TopMargin    = 20;
            document.PageSetup.BottomMargin = 20;
            document.PageSetup.PageWidth    = pagewidth + 40;

            MSWord.Paragraph prg = document.Paragraphs.Add();
            prg.Range.Text = "Query results for " + qname + " [" + DateTime.Now + "]";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle);
            //prg.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            prg.SpaceAfter  = 100;
            prg.SpaceBefore = 100;
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "Table of Contents";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTocHeading);
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "TOC";
            prg.Range.InsertParagraphAfter();
            prg.Range.InsertBreak(MSWord.WdBreakType.wdPageBreak);

            prg = document.Paragraphs.Add();
            MSWord.Table qtable = document.Tables.Add(prg.Range, qdata.Length, 1);
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "Appendix";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle);
            prg.Range.InsertParagraphAfter();

            object styleTypeTable = MSWord.WdStyleType.wdStyleTypeTable;

            MSWord.Style styl = document.Styles.Add("New Table Style", ref styleTypeTable);
            styl.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle;
            styl.ParagraphFormat.SpaceAfter      = 0;
            styl.ParagraphFormat.SpaceBefore     = 0;
            styl.Table.TopPadding    = 0;
            styl.Table.BottomPadding = 0;
            styl.Table.LeftPadding   = 0;
            styl.Table.RightPadding  = 0;
            //styl.Table.Borders.Enable = 1;
            qtable.Range.set_Style(styl);

            MSWord.Cell cell = qtable.Cell(1, 1);

            int headerwidth = 85;
            int levelwidth  = 100;

            object rows, cols;

            for (int i = 0; i < qdata.Length; i++)
            {
                int level = int.Parse(qdata[i][1]);
                if (level > 0)
                {
                    rows = 1;
                    cols = 2;
                    cell.Split(ref rows, ref cols);
                    cell.Range.Cells.SetWidth(level * levelwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                    cell = cell.Next;
                }

                rows = 1 + (string.IsNullOrWhiteSpace(qdata[i][0]) ? 0 : 1) + (string.IsNullOrWhiteSpace(qdata[i][6]) ? 0 : 1);
                cols = 2;
                cell.Split(ref rows, ref cols);
                cell.Merge(cell.Next);

                string title = String.Format("{0} {1} ({2})",
                                             qdata[i][2],
                                             (qdata[i][5].Length > 128 ? qdata[i][5].Remove(128) : qdata[i][5]).Replace("\n", "").Replace("\r", "").Replace("\t", ""),
                                             qdata[i][4]);

                cell.Range.Text      = title;
                cell.Range.Font.Bold = 1;
                cell.Range.set_Style(hstyles[level < 8 ? level:7]);
                cell = cell.Next;

                dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Adding to Word document " + qdata[i][3] + " #" + qdata[i][4], "status", progress++, 100, false, out bcanceled);
                if (progress == 100)
                {
                    progress = 0;
                }
                if (bcanceled)
                {
                    application.Visible = true;
                    Marshal.ReleaseComObject(document);
                    Marshal.ReleaseComObject(application);

                    return(true);
                }

                /*cell.Range.Text = "Title";
                 * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                 * cell.Range.Font.Bold = 1;
                 * cell = cell.Next;
                 *
                 * cell.Range.Text = qdata[i][4];
                 * cell = cell.Next;*/

                /*cell.Range.Text = "Description";
                 * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                 * cell.Range.Font.Bold = 1;
                 * cell = cell.Next;*/

                if (!string.IsNullOrWhiteSpace(qdata[i][6]))
                {
                    cell.Merge(cell.Next);
                    cell.Range.Text = qdata[i][6];
                    cell            = cell.Next;
                }

                if (!string.IsNullOrWhiteSpace(qdata[i][0]))
                {
                    cell.Range.Text = "Attachments";
                    cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                    cell.Range.Font.Bold = 1;
                    cell = cell.Next;

                    var query = qdata[i][0]
                                .Split(';')
                                .Where(x => !string.IsNullOrWhiteSpace(x))
                                .Select(x =>
                    {
                        string[] ch = x.Split('~');
                        return(new { name = ch[0], value = ch[1] });
                    }).ToArray();
                    cell.Split(query.Length, 1);

                    foreach (var kvp in query)
                    {
                        string localpath = Path.GetTempFileName() + "." + kvp.name;
                        //try { File.Delete(localpath); }
                        //catch { }

                        try
                        {
                            webclient.DownloadFile(kvp.value, localpath);
                        }
                        catch (Exception ex)
                        {
                            localpath = "";
                            Utilities.OutputCommandString(ex.ToString());
                        }

                        prg            = document.Paragraphs.Add();
                        prg.Range.Text = kvp.name;
                        prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleHeading3);

                        cell.Range.Text = kvp.name;
                        document.Hyperlinks.Add(cell.Range, missing, prg.Range);

                        prg.Range.InsertParagraphAfter();
                        document.InlineShapes.AddHorizontalLineStandard(prg.Range);
                        prg = document.Paragraphs.Add();

                        if (!string.IsNullOrEmpty(localpath))
                        {
                            try
                            {
                                Image img = Image.FromFile(localpath);
                                img.Dispose();
                                document.InlineShapes.AddPicture(localpath, false, true, prg.Range);
                            }
                            catch
                            {
                                if (Path.GetExtension(kvp.name).Equals(".sql", StringComparison.InvariantCultureIgnoreCase) ||
                                    Path.GetExtension(kvp.name).Equals(".txt", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    prg.Range.InsertFile(localpath);//, prg.Range, false, true, false);
                                }
                                else
                                {
                                    MSWord.InlineShape shape = document.InlineShapes.AddOLEObject(missing, localpath, false, false, missing, missing, missing, prg.Range);
                                    if (shape.OLEFormat.ClassType.ToString() != "Package")
                                    {
                                        shape.Width = document.PageSetup.PageWidth - 40;
                                    }
                                }
                            }
                        }
                        cell = cell.Next;
                    }
                    if (query.Length == 0)
                    {
                        cell = cell.Next;
                    }
                }
            }

            object styleTypePara = MSWord.WdStyleType.wdStyleTypeParagraph;

            MSWord.Style styl2 = document.Styles.Add("New Paragraph Style", ref styleTypePara);
            //styl2.ParagraphFormat.set_Style(MSWord.WdBuiltinStyle.wdStyleNormal);
            styl2.ParagraphFormat.LeftIndent      = 100;
            styl2.ParagraphFormat.RightIndent     = 100;
            styl2.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle;
            styl2.ParagraphFormat.SpaceAfter      = 0;
            styl2.ParagraphFormat.SpaceBefore     = 0;

            MSWord.Paragraph       tocpara = document.Paragraphs[3];
            MSWord.TableOfContents tblct   = document.TablesOfContents.Add(tocpara.Range, missing, 1, 1);
            tblct.Update();
            //tblct.Range.set_Style(styl2);

            //application.Visible = true;

            Marshal.ReleaseComObject(document);
            Marshal.ReleaseComObject(application);

            return(false);
        }
Ejemplo n.º 45
0
        //Добавление нового текстового окна при открытии формы
        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            if (openFileDialog1.FileName != "")
            {
                file_path = openFileDialog1.FileName;
                Redactor redactor = new Redactor();
                redactor.Form_Create(openFileDialog1.FileName, this);
                switch (openFileDialog1.FilterIndex)
                {
                case (1):
                    if (File.Exists(openFileDialog1.FileName))
                    {
                        StreamReader reader =
                            new StreamReader(openFileDialog1.FileName);
                        Program.RedactorTextBox.Text = reader.ReadToEnd();
                        reader.Close();
                    }
                    break;

                case (2):
                    word.Application application = new word.Application();
                    word.Document    documents
                        = application.Documents.Open(openFileDialog1.FileName);
                    try
                    {
                        for (int i = 0; i < documents.Paragraphs.Count; ++i)
                        {
                            Program.RedactorTextBox.Font
                                = new Font(documents.Paragraphs[i + 1].Range.Font.Name,
                                           documents.Paragraphs[i + 1].Range.Font.Size);
                            Program.RedactorTextBox.
                            AppendText(documents.Paragraphs[i + 1].Range.Text.ToString());
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        documents.Close();
                        application.Quit();
                    }
                    break;

                case (3):
                    word.Application application1 = new word.Application();
                    word.Document    documents1   = application1.Documents.Open(openFileDialog1.FileName);
                    try
                    {
                        for (int i = 0; i < documents1.Paragraphs.Count; ++i)
                        {
                            Program.RedactorTextBox.Font = new Font(documents1.Paragraphs[i + 1].Range.Font.Name, documents1.Paragraphs[i + 1].Range.Font.Size);
                            Program.RedactorTextBox.AppendText(documents1.Paragraphs[i + 1].Range.Text.ToString());
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        documents1.Close();
                        application1.Quit();
                    }
                    break;
                }
            }
            else
            {
                MessageBox.Show("Выберите файл",
                                "Текстовый реадктор",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Ejemplo n.º 46
0
        private void button5_Click(object sender, EventArgs e)
        {
            List <Shablons> GetTime = dal.GetAllShablons(Convert.ToInt64(dataGridView1.CurrentRow.Cells["Номер карты"].Value.ToString()));

            Word.Application app = new Word.Application();
            Word.Document    doc = app.Documents.Add(Visible: true);
            Word.Range       r   = doc.Range();
            Word.Table       t   = doc.Tables.Add(r, GetTime.Count, 1);
            t.Borders.Enable = 1;
            int ii = -1;

            // int flag = 0, iii = 0;
            foreach (Word.Row row in t.Rows)
            {
                foreach (Word.Cell cell in row.Cells)
                {
                    ii++;

                    /*if (cell.RowIndex == 1)
                     * {
                     *  if (cell.ColumnIndex == 1)
                     *  {
                     *      cell.Range.Text = "ФИО Врача";
                     *      ii = 1;
                     *  }
                     *  if (cell.ColumnIndex == 2)
                     *  {
                     *      cell.Range.Text = "ФИО Пациента";
                     *      ii = 2;
                     *  }
                     *
                     *  if (cell.ColumnIndex == 3)
                     *  {
                     *      cell.Range.Text = "Дата посещения";
                     *      ii = 4;
                     *  }
                     *  if (cell.ColumnIndex == 4)
                     *  {
                     *      cell.Range.Text = "Диагноз";
                     *      ii = 5;
                     *  }
                     *  if (cell.ColumnIndex == 5)
                     *  {
                     *      cell.Range.Text = "Код";
                     *      ii = 6;
                     *  }
                     *
                     *  // cell.Range.Text = "Колонка" + cell.ColumnIndex.ToString();
                     *  cell.Range.Bold = 1;
                     *  cell.Range.Font.Name = "verdana";
                     *  cell.Range.Font.Size = 10;
                     *
                     *  cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                     *  cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                     * }
                     * else
                     * {
                     *  if (flag == 0)
                     *  {
                     *      while (iii < AllPrint.Count)
                     *      {
                     *
                     *          if (Convert.ToInt64(AllPrint[iii].Year) >= Convert.ToInt64(dateTimePicker3.Value.Year) && Convert.ToInt64(AllPrint[iii].Year) <= Convert.ToInt64(dateTimePicker2.Value.Year))
                     *          {
                     *              if (Convert.ToInt64(AllPrint[iii].Month) >= dateTimePicker3.Value.Month && Convert.ToInt64(AllPrint[iii].Month) <= dateTimePicker2.Value.Month)
                     *              {
                     *                  if (Convert.ToInt64(AllPrint[iii].Day) >= dateTimePicker3.Value.Day && Convert.ToInt64(AllPrint[iii].Day) <= dateTimePicker2.Value.Day)
                     *                  {
                     *                      flag++;
                     *                      iii++;
                     *                      break;
                     *                  }
                     *              }
                     *          }
                     *      }
                     *  }*/

                    // if (cell.ColumnIndex == 1)
                    // {
                    cell.Range.Text = "ФИО врача: " + GetTime[ii].DocName + "\n" + "Дата: " + GetTime[ii].Day + "/" + GetTime[ii].Month + "/" + GetTime[ii].Year + "\n" + GetTime[ii].Bolezn + "\n" + GetTime[ii].Shablon;

                    /* }
                     * if (cell.ColumnIndex == 2)
                     * {
                     *   cell.Range.Text = AllPrint[iii].PacName;
                     * }
                     * if (cell.ColumnIndex == 3)
                     * {
                     *   cell.Range.Text = AllPrint[iii].Day.ToString() + "/" + AllPrint[iii].Month.ToString() + "/" + AllPrint[iii].Year.ToString();
                     * }
                     *
                     * if (cell.ColumnIndex == 4)
                     * {
                     *   cell.Range.Text = AllPrint[iii].Diagnoz.ToString();
                     * }
                     * if (cell.ColumnIndex == 5)
                     * {
                     *   cell.Range.Text = AllPrint[iii].Code;
                     *   flag = 0;
                     * }*/

                    //}
                }
            }
            doc.SaveAs(@"C:\Result\" + dataGridView1.CurrentRow.Cells["Фамилия"].Value.ToString() + ".doc");

            app.Documents.Open(@"C:\Template\1.docx");
            try
            {
                app.Documents.Close();
                app.Quit();
            }
            catch
            {
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (listTemp.Count(n => n.отключить) == 0)
            {
                MessageBox.Show("Отметьте клиентов на отключение");
                return;
            }
            Word.Application oWord = new Word.Application();

            string curDir = System.IO.Directory.GetCurrentDirectory();

            object шаблон = curDir + @"\монтажники1вид.dot";

            if (!System.IO.File.Exists(шаблон.ToString()))
            {
                MessageBox.Show("Нет файла " + шаблон.ToString());
                return;
            }

            //domofon10.DataClasses1DataContext dc = new DataClasses1DataContext();

            //string наименФилиала = dc.филиал
            //    .OrderBy(n => n.порядок)
            //    .First().наимен;

            Word.Document o = oWord.Documents.Add(Template: шаблон);
            oWord.Application.Visible      = true;
            o.Bookmarks["дата"].Range.Text = DateTime.Today.ToLongDateString();
            //       o.Bookmarks["филиал"].Range.Text = наименФилиала;

            o.Bookmarks["адрес"].Range.Text = this.Text;
            int j = 1;

            foreach (temp kRow in listTemp
                     .Where(n => n.отключить))
            {
                j++;
                o.Tables[4].Cell(j, 1).Range.Text = kRow.наимен_услуги.Trim();
                o.Tables[4].Cell(j, 2).Range.Text = kRow.адрес.Trim();
                o.Tables[4].Cell(j, 3).Range.Text = kRow.фио;
                o.Tables[4].Cell(j, 4).Range.Text = kRow.долг_мес.ToString("0;#;#");
                o.Tables[4].Cell(j, 5).Range.Text = kRow.прим;
                o.Tables[4].Cell(j, 6).Range.Text = kRow.прим0;
                o.Tables[4].Cell(j, 7).Range.Text = kRow.телефон;
                //o.Tables[4].Cell(j, 8).Range.Text = kRow.месяц.ToString("0;#;#");
                //o.Tables[4].Cell(j, 9).Range.Text = kRow.год.ToString("0;#;#");
                //o.Tables[4].Cell(j, 10).Range.Text =
                //if (kRow.отключен != null)
                //    o.Tables[4].Cell(j, 11).Range.Text = kRow.отключен.Value.ToShortDateString();
                //if (kRow.повтор != null)
                //    o.Tables[4].Cell(j, 12).Range.Text = kRow.повтор.Value.ToShortDateString();

                o.Tables[4].Rows.Add();
            }
            o.Tables[4].Cell(j + 1, 2).Range.Text = "Всего квартир ";
            o.Tables[4].Cell(j + 1, 4).Range.Text = (j - 1).ToString("0;#;#");



            oWord.Application.Visible = true;
        }
Ejemplo n.º 48
0
        private void buttonShowPages_Click(object sender, EventArgs e)
        {
            string msg = "";

            try
            {
                DialogResult ret = this.openFileDialogWord.ShowDialog(this);

                if (ret != DialogResult.OK)
                {
                    return;
                }

                string docFile = this.openFileDialogWord.FileName;

                if (docFile == null || !(docFile.ToLower().EndsWith("doc") || docFile.ToLower().EndsWith("docx")))
                {
                    msg = "非word文件: " + docFile;
                    throw new Exception(msg);
                }

                this.textBox1.Text = msg;

                object wordFile = docFile;

                object oMissing = Missing.Value;

                //自定义object类型的布尔值
                object oTrue  = true;
                object oFalse = false;

                object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;

                //定义WORD Application相关
                Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();

                //WORD程序不可见
                appWord.Visible = false;
                //不弹出警告框
                appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;

                //打开要打印的文件
                Microsoft.Office.Interop.Word.Document doc = appWord.Documents.Open(
                    ref wordFile,
                    ref oMissing,
                    ref oTrue,
                    ref oFalse,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing);


                // 计算Word文档页数 
                WdStatistic stat = WdStatistic.wdStatisticPages;
                int         num  = doc.ComputeStatistics(stat, ref oMissing);//.ComputeStatistics(stat, ref Nothing); 
                //打印完关闭WORD文件
                doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);

                //退出WORD程序
                appWord.Quit(ref oMissing, ref oMissing, ref oMissing);

                doc     = null;
                appWord = null;

                msg = docFile + " : All Pages:" + num;
            }
            catch (System.Exception ex)
            {
                msg = ex.Message;
            }

            this.textBox1.Text = msg;
        }
Ejemplo n.º 49
0
        // Format the header row so with the appropriate widths and titles
        public void FormatColumns(Word.Document doc)
        {
            double widthLeft;
            float  qnumWidth    = 0.51f;
            float  altqnumWidth = 0.86f;
            float  varWidth     = 0.9f;
            float  tcWidth      = 1.2f;
            float  respWidth    = 0.86f;
            float  commentWidth = 1f;
            int    qCol;
            int    otherCols;
            int    numCols;
            String header;

            switch (layoutoptions.PaperSize)
            {
            case 1: widthLeft = 10.5; break;

            case 2: widthLeft = 13.5; break;

            case 3: widthLeft = 16.5; break;

            case 4: widthLeft = 11.7; break;

            default: widthLeft = 10.5; break;
            }
            // Qnum and VarName
            otherCols = 2;

            if (enumeration == 3 && reportType != 2)
            {
                qCol = 4;
                otherCols++; // AltQnum
            }
            else
            {
                qCol = 3;
            }

            numCols = doc.Tables[1].Columns.Count;

            for (int i = 1; i <= numCols; i++)
            {
                // remove underscores
                doc.Tables[1].Rows[1].Cells[i].Range.Text = doc.Tables[1].Rows[1].Cells[i].Range.Text.Replace("_", " ");
                header = doc.Tables[1].Rows[1].Cells[i].Range.Text.TrimEnd('\r', '\a');

                switch (header)
                {
                case "Qnum":
                    doc.Tables[1].Rows[1].Cells[i].Range.Text = "Q#";
                    //doc.Tables[1].Columns[i].Width = qnumWidth * 72;
                    widthLeft -= qnumWidth;
                    break;

                case "AltQnum":
                    doc.Tables[1].Rows[1].Cells[i].Range.Text = "AltQ#";
                    // doc.Tables[1].Columns[i].Width = altqnumWidth * 72;
                    widthLeft -= altqnumWidth;
                    break;

                case "VarName":
                    //doc.Tables[1].Columns[i].Width = varWidth * 72;
                    widthLeft -= varWidth;
                    break;

                case "Response":
                    // doc.Tables[1].Columns[i].Width = respWidth * 72;
                    widthLeft -= respWidth;
                    break;

                case "Info":
                    // doc.Tables[1].Columns[i].Width = tcWidth * 72;
                    widthLeft -= tcWidth;
                    break;

                case "SortBy":
                    //doc.Tables[1].Columns[i].Width = qnumWidth * 72;
                    widthLeft -= qnumWidth;
                    break;

                case "Comments":
                    //doc.Tables[1].Columns[i].Width = commentWidth * 72;
                    widthLeft -= commentWidth;
                    break;

                default:     // question column
                    if (header.Contains(DateTime.Today.ToString("d").Replace("-", "")))
                    {
                        doc.Tables[1].Rows[1].Cells[i].Range.Text = doc.Tables[1].Rows[1].Cells[i].Range.Text.Replace(DateTime.Today.ToString("d"), "");
                    }
                    break;
                }
            }
        }
Ejemplo n.º 50
0
 private void Init()
 {
     wordApp = new Word.Application();
     wordDoc = wordApp.Documents.Open(name);
 }
        private void печать2квитанции_работ()
        {
            //  записать();
            //          DataSet.оплатаRow uRow = (оплатаBindingSource.Current as DataRowView).Row as DataSet.оплатаRow;
            оплаты uRow = bindingSource1.Current as оплаты;

            клОплата.оплата = uRow.оплата;
            de = new domofon14Entities();

            //        domofon10.DataClasses1DataContext db1 = new DataClasses1DataContext();

            //int номерКвитанции = 0;
            //if (db1.опл_работы
            //    .Any(n => n.оплата == клОплата.оплата))
            //{
            //    номерКвитанции = db1.опл_работы
            //    .Where(n => n.оплата == клОплата.оплата)
            //    .Max(n => n.код);
            //}

            //        var yRow = db1.опл_работы
            //.Where(n => n.оплата == клОплата.оплата)
            //.GroupBy(n => n.работа1)
            //.Select(n => new { n.Key, цена = n.Max(z => z.стоимость), сумма = n.Sum(z => z.оплачено) });

            var query = de.опл_работы
                        .Where(n => n.оплата == клОплата.оплата)
                        .OrderBy(n => n.работы.порядок);

            квитанцияЛист.Clear();

            foreach (var kRow in query)
            {
                квитанция NewRow = new квитанция();
                NewRow.услуга        = kRow.работа;
                NewRow.наимен_услуги = kRow.работы.наимен.Trim();
                NewRow.прейскурант   = kRow.работы.прейскурант.Trim();
                //   NewRow.наряд = kRow.задание;
                NewRow.сумма       = kRow.стоимость;
                NewRow.материалы   = (int)kRow.ст_материалов;
                NewRow.зарплата    = (int)NewRow.сумма - NewRow.материалы;
                NewRow.фио_мастера = kRow.сотрудники.фио;
                квитанцияЛист.Add(NewRow);
                //     dsТабель1.квитанция.Rows.Add(NewRow);
            }


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

            string curDir = System.IO.Directory.GetCurrentDirectory();

            object шаблон = curDir + @"\квитанция3работы.dot";

            if (!System.IO.File.Exists(шаблон.ToString()))
            {
                MessageBox.Show("Нет файла " + шаблон.ToString());
                return;
            }

            клФирма.init();
            клФилиал.init();

            Word.Document o = oWord.Documents.Add(Template: шаблон);
            o.Bookmarks["менеджер"].Range.Text  = uRow.сотрудники.фио;
            o.Bookmarks["менеджер2"].Range.Text = uRow.сотрудники.фио;

            o.Bookmarks["дата"].Range.Text  = uRow.дата.ToLongDateString();
            o.Bookmarks["дата2"].Range.Text = uRow.дата.ToLongDateString();

            o.Bookmarks["филиал"].Range.Text          = клФилиал.наимен;
            o.Bookmarks["адрес_филиала"].Range.Text   = клФилиал.адрес.Trim();
            o.Bookmarks["телефон_филиала"].Range.Text = клФилиал.deRow.телефон.Trim();

            o.Bookmarks["филиал2"].Range.Text         = клФилиал.наимен;
            o.Bookmarks["адрес2филиала"].Range.Text   = клФилиал.адрес.Trim();
            o.Bookmarks["телефон2филиала"].Range.Text = клФилиал.deRow.телефон.Trim();


            o.Bookmarks["номер_квитанции"].Range.Text = uRow.номер.ToString();
            o.Bookmarks["номер2квитанции"].Range.Text = uRow.номер.ToString();

            o.Bookmarks["фио"].Range.Text = uRow.клиенты.фио;
            //string адрес_абонента = "ул. " + uRow.наимен_улицы.Trim()
            //    + "   д. " + uRow.номер_дома.Trim() + " "
            //    + uRow.корпус.Trim() + " кв. " + uRow.квартира.Trim();
            //if (uRow.ввод > 0)
            //{
            //    адрес_абонента += " ввод " + uRow.ввод.ToString();
            //}

            o.Bookmarks["адрес"].Range.Text = uRow.клиенты.адрес;

            o.Bookmarks["фио2"].Range.Text   = uRow.клиенты.фио;
            o.Bookmarks["адрес2"].Range.Text = uRow.клиенты.адрес;

            o.Bookmarks["наимен_фирмы"].Range.Text   = клФирма.deRow.наимен.Trim();
            o.Bookmarks["наимен2фирмы"].Range.Text   = клФирма.deRow.наимен.Trim();
            o.Bookmarks["инн"].Range.Text            = "ИНН " + клФирма.deRow.инн.Trim();
            o.Bookmarks["инн2"].Range.Text           = "ИНН " + клФирма.deRow.инн.Trim();
            o.Bookmarks["кпп"].Range.Text            = "КПП " + клФирма.deRow.код.Trim();
            o.Bookmarks["кпп2"].Range.Text           = "КПП " + клФирма.deRow.код.Trim();
            o.Bookmarks["расчетный_счет"].Range.Text = "р/с " + клФирма.deRow.р_счет.Trim();
            o.Bookmarks["расчетный2счет"].Range.Text = "р/с " + клФирма.deRow.р_счет.Trim();
            o.Bookmarks["наимен_банка"].Range.Text   = " " + клФирма.deRow.банк.Trim();
            o.Bookmarks["наимен2банка"].Range.Text   = " " + клФирма.deRow.банк.Trim();
            o.Bookmarks["город"].Range.Text          = клФирма.deRow.город.Trim();
            o.Bookmarks["город2"].Range.Text         = клФирма.deRow.город.Trim();
            o.Bookmarks["кор_счет"].Range.Text       = "к/с " + клФирма.deRow.к_счет.Trim();
            o.Bookmarks["кор2счет"].Range.Text       = "к/с " + клФирма.deRow.к_счет.Trim();
            o.Bookmarks["адрес_фирмы"].Range.Text    = клФирма.deRow.адрес.Trim();
            o.Bookmarks["адрес2фирмы"].Range.Text    = клФирма.deRow.адрес.Trim();


            int     j     = 1;
            decimal итого = 0;

            foreach (квитанция kRow in квитанцияЛист)
            {
                //   string текст1 = kRow.начало + " - " + kRow.конец + " " + kRow.год.ToString();
                j++;
                o.Tables[5].Cell(j, 1).Range.Text = kRow.наряд.ToString("0;#;#");

                o.Tables[5].Cell(j, 2).Range.Text = kRow.прейскурант;
                o.Tables[5].Cell(j, 3).Range.Text = kRow.наимен_услуги.Trim() + "  мастер " + kRow.фио_мастера.Trim();
                //  o.Tables[5].Cell(j, 4).Range.Text = kRow.материалы.ToString("0.00;#;#");
                o.Tables[5].Cell(j, 4).Range.Text = kRow.сумма.ToString("0.00;#;#");
                o.Tables[5].Rows.Add();
                итого += kRow.сумма;

                o.Tables[11].Cell(j, 1).Range.Text = kRow.наряд.ToString("0;#;#");

                o.Tables[11].Cell(j, 2).Range.Text = kRow.прейскурант;
                o.Tables[11].Cell(j, 3).Range.Text = kRow.наимен_услуги.Trim() + "  мастер " + kRow.фио_мастера.Trim();
                o.Tables[11].Cell(j, 4).Range.Text = kRow.материалы.ToString("0.00;#;#");
                o.Tables[11].Cell(j, 5).Range.Text = kRow.сумма.ToString("0.00;#;#");
                o.Tables[11].Rows.Add();
            }
            o.Tables[5].Cell(j + 1, 4).Range.Text  = итого.ToString("0.00");
            o.Tables[11].Cell(j + 1, 5).Range.Text = итого.ToString("0.00");


            клTemp.Caption            = o.ActiveWindow.Caption;
            oWord.Application.Visible = true;
        }
Ejemplo n.º 52
0
    { static void Main(string[] args)
      {
          object path;                                //文件路径变量
          string strContent;                          //文本内容变量

          MSWord.Application wordApp;                 //Word应用程序变量
          MSWord.Document    wordDoc;                 //Word文档变量

          path    = Environment.CurrentDirectory + "\\MyWord_Print.doc";
          wordApp = new MSWord.ApplicationClass(); //初始化

          wordApp.Visible = true;                  //使文档可见

          //如果已存在,则删除
          if (File.Exists((string)path))
          {
              File.Delete((string)path);
          }

          //由于使用的是COM库,因此有许多变量需要用Missing.Value代替
          Object Nothing = Missing.Value;

          wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

          #region 页面设置、页眉图片和文字设置,最后跳出页眉设置

          //页面设置
          wordDoc.PageSetup.PaperSize      = MSWord.WdPaperSize.wdPaperA4;          //设置纸张样式为A4纸
          wordDoc.PageSetup.Orientation    = MSWord.WdOrientation.wdOrientPortrait; //排列方式为垂直方向
          wordDoc.PageSetup.TopMargin      = 57.0f;
          wordDoc.PageSetup.BottomMargin   = 57.0f;
          wordDoc.PageSetup.LeftMargin     = 57.0f;
          wordDoc.PageSetup.RightMargin    = 57.0f;
          wordDoc.PageSetup.HeaderDistance = 30.0f;  //页眉位置

          //设置页眉
          //wordApp.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;//普通视图(即页面视图)样式
          //wordApp.ActiveWindow.View.SeekView = MSWord.WdSeekView.wdSeekPrimaryHeader;//进入页眉设置,其中页眉边距在页面设置中已完成
          //wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;//页眉中的文字右对齐


          //插入页眉图片(测试结果图片未插入成功)
          wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
          string             headerfile = @"D:\project\saiter\logo.jpg";
          MSWord.InlineShape shape1     = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref Nothing, ref Nothing, ref Nothing);
          shape1.Height = 5;                                               //强行设置貌似无效,图片没有按设置的缩放——图片的比例并没有改变。
          shape1.Width  = 20;
          wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("  文档页眉"); //在页眉的图片后面追加几个字

          //去掉页眉的横线
          wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[MSWord.WdBorderType.wdBorderBottom].LineStyle = MSWord.WdLineStyle.wdLineStyleNone;
          wordApp.ActiveWindow.ActivePane.Selection.Borders[MSWord.WdBorderType.wdBorderBottom].Visible = false;
          wordApp.ActiveWindow.ActivePane.View.SeekView = MSWord.WdSeekView.wdSeekMainDocument;  //退出页眉设置
          #endregion

          #region 页码设置并添加页码

          //为当前页添加页码
          MSWord.PageNumbers pns = wordApp.Selection.Sections[1].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers; //获取当前页的号码
          pns.NumberStyle               = MSWord.WdPageNumberStyle.wdPageNumberStyleNumberInDash;                                         //设置页码的风格,是Dash形还是圆形的
          pns.HeadingLevelForChapter    = 0;
          pns.IncludeChapterNumber      = false;
          pns.RestartNumberingAtSection = false;
          pns.StartingNumber            = 0;                                         //开始页页码?
          object pagenmbetal = MSWord.WdPageNumberAlignment.wdAlignPageNumberCenter; //将号码设置在中间
          object first       = true;
          wordApp.Selection.Sections[1].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);

          #endregion

          #region 行间距与缩进、文本字体、字号、加粗、斜体、颜色、下划线、下划线颜色设置

          wordApp.Selection.ParagraphFormat.LineSpacing     = 16f; //设置文档的行间距
          wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;  //首行缩进的长度
          //写入普通文本
          strContent = "我是普通文本\n";
          wordDoc.Paragraphs.Last.Range.Text = strContent;

          wordDoc.Paragraphs.Last.Range.Text = "我再加一行试试,这里不加'\\n'";
          //直接添加段,不是覆盖( += )
          wordDoc.Paragraphs.Last.Range.Text += "不会覆盖的,";

          //添加在此段的文字后面,不是新段落
          wordDoc.Paragraphs.Last.Range.InsertAfter("这是后面的内容\n");

          //将文档的前4个字替换成"哥是替换文字",并将其颜色设为红色
          object       start = 0;
          object       end   = 4;
          MSWord.Range rang  = wordDoc.Range(ref start, ref end);
          rang.Font.Color = MSWord.WdColor.wdColorRed;
          rang.Text       = "哥是替换文字";
          wordDoc.Range(ref start, ref end);

          //写入黑体文本
          object unite = MSWord.WdUnits.wdStory;
          wordApp.Selection.EndKey(ref unite, ref Nothing);      //将光标移到文本末尾
          wordApp.Selection.ParagraphFormat.FirstLineIndent = 0; //取消首行缩进的长度
          strContent = "这是黑体文本\n";
          wordDoc.Paragraphs.Last.Range.Font.Name = "黑体";
          wordDoc.Paragraphs.Last.Range.Text      = strContent;

          //写入加粗文本
          strContent = "这是粗体文本\n";                          //
          wordApp.Selection.EndKey(ref unite, ref Nothing); //这一句不加,有时候好像也不出问题,不过还是加了安全
          wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
          wordDoc.Paragraphs.Last.Range.Text      = strContent;

          //写入15号字体文本
          strContent = "我这个文本的字号是15号,而且是宋体\n";
          wordApp.Selection.EndKey(ref unite, ref Nothing);
          wordDoc.Paragraphs.Last.Range.Font.Size = 15;
          wordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
          wordDoc.Paragraphs.Last.Range.Text      = strContent;

          //写入斜体文本
          strContent = "我是斜体字文本\n";
          wordApp.Selection.EndKey(ref unite, ref Nothing);
          wordDoc.Paragraphs.Last.Range.Font.Italic = 1;
          wordDoc.Paragraphs.Last.Range.Text        = strContent;

          //写入蓝色文本
          strContent = "我是蓝色的文本\n";
          wordApp.Selection.EndKey(ref unite, ref Nothing);
          wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue;
          wordDoc.Paragraphs.Last.Range.Text       = strContent;

          //写入下划线文本
          strContent = "我是下划线文本\n";
          wordApp.Selection.EndKey(ref unite, ref Nothing);
          wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
          wordDoc.Paragraphs.Last.Range.Text           = strContent;

          //写入红色下画线文本
          strContent = "我是点线下划线,并且下划线是红色的\n";
          wordApp.Selection.EndKey(ref unite, ref Nothing);
          wordDoc.Paragraphs.Last.Range.Font.Underline      = MSWord.WdUnderline.wdUnderlineDottedHeavy;
          wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed;
          wordDoc.Paragraphs.Last.Range.Text = strContent;

          //取消下划线,并且将字号调整为12号
          strContent = "我他妈不要下划线了,并且设置字号为12号,黑色不要斜体\n";
          wordApp.Selection.EndKey(ref unite, ref Nothing);
          wordDoc.Paragraphs.Last.Range.Font.Size      = 12;
          wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineNone;
          wordDoc.Paragraphs.Last.Range.Font.Color     = MSWord.WdColor.wdColorBlack;
          wordDoc.Paragraphs.Last.Range.Font.Italic    = 0;
          wordDoc.Paragraphs.Last.Range.Text           = strContent;


          #endregion


          #region 插入图片、居中显示,设置图片的绝对尺寸和缩放尺寸,并给图片添加标题

          wordApp.Selection.EndKey(ref unite, ref Nothing);   //将光标移动到文档末尾
          //图片文件的路径
          string filename = Environment.CurrentDirectory + "\\logo.jpg";
          //要向Word文档中插入图片的位置
          Object range = wordDoc.Paragraphs.Last.Range;
          //定义该插入的图片是否为外部链接
          Object linkToFile = false;                 //默认,这里貌似设置为bool类型更清晰一些
          //定义要插入的图片是否随Word文档一起保存
          Object saveWithDocument = true;            //默认
          //使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入图片
          wordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range);
          wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;  //居中显示图片

          //设置图片宽高的绝对大小

          //wordDoc.InlineShapes[1].Width = 200;
          //wordDoc.InlineShapes[1].Height = 150;
          //按比例缩放大小

          wordDoc.InlineShapes[1].ScaleWidth  = 20; //缩小到20% ?
          wordDoc.InlineShapes[1].ScaleHeight = 20;

          //在图下方居中添加图片标题

          wordDoc.Content.InsertAfter("\n");  //这一句与下一句的顺序不能颠倒,原因还没搞透
          wordApp.Selection.EndKey(ref unite, ref Nothing);
          wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
          wordApp.Selection.Font.Size = 10;  //字体大小
          wordApp.Selection.TypeText("图1 测试图片\n");

          #endregion

          #region 添加表格、填充数据、设置表格行列宽高、合并单元格、添加表头斜线、给单元格添加图片
          wordDoc.Content.InsertAfter("\n");                //这一句与下一句的顺序不能颠倒,原因还没搞透
          wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
          wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
          //object WdLine2 = MSWord.WdUnits.wdLine;//换一行;
          //wordApp.Selection.MoveDown(ref WdLine2, 6, ref Nothing);//向下跨15行输入表格,这样表格就在文字下方了,不过这是非主流的方法

          //设置表格的行数和列数
          int tableRow    = 6;
          int tableColumn = 6;

          //定义一个Word中的表格对象
          MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,
                                                  tableRow, tableColumn, ref Nothing, ref Nothing);

          //默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
          table.Borders.Enable = 1;  //这个值可以设置得很大,例如5、13等等

          //表格的索引是从1开始的。
          wordDoc.Tables[1].Cell(1, 1).Range.Text = "列\n行";
          for (int i = 1; i < tableRow; i++)
          {
              for (int j = 1; j < tableColumn; j++)
              {
                  if (i == 1)
                  {
                      table.Cell(i, j + 1).Range.Text = "Column " + j;  //填充每列的标题
                  }
                  if (j == 1)
                  {
                      table.Cell(i + 1, j).Range.Text = "Row " + i;         //填充每行的标题
                  }
                  table.Cell(i + 1, j + 1).Range.Text = i + "行 " + j + "列"; //填充表格的各个小格子
              }
          }


          //添加行
          table.Rows.Add(ref Nothing);
          table.Rows[tableRow + 1].Height = 35;                                  //设置新增加的这行表格的高度
          //向新添加的行的单元格中添加图片
          string FileName         = Environment.CurrentDirectory + "\\logo.jpg"; //图片所在路径
          object LinkToFile       = false;
          object SaveWithDocument = true;
          object Anchor           = table.Cell(tableRow + 1, tableColumn).Range;//选中要添加图片的单元格
          wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);

          //由于是本文档的第2张图,所以这里是InlineShapes[2]
          wordDoc.Application.ActiveDocument.InlineShapes[2].Width  = 50; //图片宽度
          wordDoc.Application.ActiveDocument.InlineShapes[2].Height = 35; //图片高度

          // 将图片设置为四周环绕型
          MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[2].ConvertToShape();
          s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;


          //设置table样式
          table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;       //高度规则是:行高有最低值下限?
          table.Rows.Height     = wordApp.CentimetersToPoints(float.Parse("0.8")); //

          table.Range.Font.Size = 10.5F;
          table.Range.Font.Bold = 0;

          table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;       //表格文本居中
          table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom; //文本垂直贴到底部
          //设置table边框样式
          table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;                            //表格外框是双线
          table.Borders.InsideLineStyle  = MSWord.WdLineStyle.wdLineStyleSingle;                            //表格内框是单线

          table.Rows[1].Range.Font.Bold    = 1;                                                             //加粗
          table.Rows[1].Range.Font.Size    = 12F;
          table.Cell(1, 1).Range.Font.Size = 10.5F;
          wordApp.Selection.Cells.Height   = 30;//所有单元格的高度

          //除第一行外,其他行的行高都设置为20
          for (int i = 2; i <= tableRow; i++)
          {
              table.Rows[i].Height = 20;
          }

          //将表格左上角的单元格里的文字(“行” 和 “列”)居右
          table.Cell(1, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;
          //将表格左上角的单元格里面下面的“列”字移到左边,相比上一行就是将ParagraphFormat改成了Paragraphs[2].Format
          table.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;

          table.Columns[1].Width = 50;  //将第 1列宽度设置为50

          //将其他列的宽度都设置为75
          for (int i = 2; i <= tableColumn; i++)
          {
              table.Columns[i].Width = 75;
          }


          //添加表头斜线,并设置表头的样式
          table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Visible   = true;
          table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Color     = MSWord.WdColor.wdColorRed;
          table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].LineWidth = MSWord.WdLineWidth.wdLineWidth150pt;

          //合并单元格
          table.Cell(4, 4).Merge(table.Cell(4, 5));  //横向合并

          table.Cell(2, 3).Merge(table.Cell(4, 3));  //纵向合并,合并(2,3),(3,3),(4,3)

          #endregion

          wordApp.Selection.EndKey(ref unite, ref Nothing);   //将光标移动到文档末尾

          wordDoc.Content.InsertAfter("\n");
          wordDoc.Content.InsertAfter("就写这么多,算了吧!2016.09.27");



          //WdSaveFormat为Word 2003文档的保存格式
          object format = MSWord.WdSaveFormat.wdFormatDocument;  // office 2007就是wdFormatDocumentDefault
          //将wordDoc文档对象的内容保存为DOCX文档
          wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
          //关闭wordDoc文档对象

          //看是不是要打印
          //wordDoc.PrintOut();



          wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
          //关闭wordApp组件对象
          wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
          Console.WriteLine(path + " 创建完毕!");
          Console.ReadKey();


          //我还要打开这个文档玩玩
          MSWord.Application app = new MSWord.Application();
          MSWord.Document    doc = null;
          try
          {
              object unknow = Type.Missing;
              app.Visible = true;
              string str  = Environment.CurrentDirectory + "\\MyWord_Print.doc";
              object file = str;
              doc = app.Documents.Open(ref file,
                                       ref unknow, ref unknow, ref unknow, ref unknow,
                                       ref unknow, ref unknow, ref unknow, ref unknow,
                                       ref unknow, ref unknow, ref unknow, ref unknow,
                                       ref unknow, ref unknow, ref unknow);
              string temp = doc.Paragraphs[1].Range.Text.Trim();
              Console.WriteLine("你他妈输出temp干嘛?");
          }
          catch (Exception ex)
          {
              Console.WriteLine(ex.Message);
          }
          wordDoc = doc;
          wordDoc.Paragraphs.Last.Range.Text += "我真的不打算再写了,就写这么多吧";

          Console.ReadKey();
      }
        private void button17_Click(object sender, EventArgs e)
        {
            if (bindingSource1.Count > 0)
            {
                оплаты uRow = bindingSource1.Current as оплаты;
                клОплата.оплата = uRow.оплата;
                string фио = uRow.клиенты.фио;

                de = new domofon14Entities();
                //int СуммаВозврата = de.возврат
                //    .Where(n => n.оплата == клОплата.оплата)
                //    .Sum(n => n.сумма);

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

                string curDir = System.IO.Directory.GetCurrentDirectory();

                object шаблон = curDir + @"\расходник.dot";
                if (!System.IO.File.Exists(шаблон.ToString()))
                {
                    MessageBox.Show("Нет файла " + шаблон.ToString());
                    return;
                }

                клФирма.init();
                клФилиал.init();

                Word.Document o = oWord.Documents.Add(Template: шаблон);
                o.Bookmarks["кассир"].Range.Text = uRow.сотрудники.фио;

                o.Bookmarks["дата"].Range.Text = uRow.дата.ToLongDateString();

                o.Bookmarks["филиал"].Range.Text = клФилиал.наимен;

                if (de.возврат.Any(n => n.оплата == клОплата.оплата) || de.воз_работы.Any(n => n.оплата == клОплата.оплата))
                {
                    int СуммаВозврата = de.возврат
                                        .Where(n => n.оплата == клОплата.оплата)
                                        .Sum(n => n.сумма);

                    int ВозвратРаботы = de.воз_работы
                                        .Where(n => n.оплата == клОплата.оплата)
                                        .Sum(n => n.сумма);

                    СуммаВозврата += ВозвратРаботы;

                    //  MessageBox.Show(прописью.буквами(СуммаВозврата));
                    if (o.Bookmarks.Exists("сумма"))
                    {
                        o.Bookmarks["сумма"].Range.Text = СуммаВозврата.ToString();
                    }
                    if (o.Bookmarks.Exists("выдано_прописью"))
                    {
                        o.Bookmarks["выдано_прописью"].Range.Text = прописью.буквами(СуммаВозврата) + "____";
                    }
                }
                //      o.Bookmarks["сумма"].Range.Text = СуммаВозврата.ToString();


                if (o.Bookmarks.Exists("номер"))
                {
                    o.Bookmarks["номер"].Range.Text = uRow.номер.ToString();
                }
                if (o.Bookmarks.Exists("фио"))
                {
                    o.Bookmarks["фио"].Range.Text = фио;
                }

                oWord.Application.Visible = true;
            }
        }
Ejemplo n.º 54
0
        //button save to word
        private void saveWord_btn_Click(object sender, EventArgs e)
        {
            /* SaveFileDialog savefile = new SaveFileDialog();
             * savefile.DefaultExt = "*.docx";
             * savefile.Filter = "DOCX files(*.docx)|*.docx";
             *
             * if (savefile.ShowDialog() == DialogResult.OK && savefile.FileName.Length > 0)
             * {
             *   Export_Data_To_Word(info_dgv, savefile.FileName);
             *   MessageBox.Show("File saved!", "Message Dialog", MessageBoxButtons.OK, MessageBoxIcon.Information);
             * }*/
            if (info_dgv.Rows.Count > 0)
            {
                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                word.Visible = true;
                Object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Document wordDoc = word.Documents.Add(Type.Missing);

                Microsoft.Office.Interop.Word.Paragraph title = wordDoc.Content.Paragraphs.Add(ref missing);

                title.Range.Text      = "Danh sach hoc sinh";
                title.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
                title.Range.Font.Size = 40;
                title.Range.InsertParagraphAfter();
                title.Range.Font.Reset();

                Microsoft.Office.Interop.Word.Paragraph content = wordDoc.Content.Paragraphs.Add(ref missing);
                content.Range.Text = "Giang Vien: Le Vinh Thinh";
                content.Alignment  = WdParagraphAlignment.wdAlignParagraphLeft;
                content.Range.InsertParagraphAfter();

                Microsoft.Office.Interop.Word.Paragraph content2 = wordDoc.Content.Paragraphs.Add(ref missing);
                content2.Range.Text = "Tong so sinh vien: " + info_dgv.Rows.Count;
                content2.Alignment  = WdParagraphAlignment.wdAlignParagraphLeft;
                content2.Range.InsertParagraphAfter();

                Microsoft.Office.Interop.Word.Paragraph para1 = wordDoc.Content.Paragraphs.Add(ref missing);


                Table Tab1 = wordDoc.Tables.Add(para1.Range, 1, 9, ref missing, ref missing);
                Tab1.Borders.Enable        = 1;
                Tab1.Range.Font.Size       = 12;
                Tab1.Cell(1, 1).Range.Text = "Order number";
                for (int i = 1; i < info_dgv.Columns.Count + 1; i++)
                {
                    Tab1.Cell(1, i + 1).Range.Text = info_dgv.Columns[i - 1].HeaderText + Environment.NewLine;
                }
                for (int i = 0; i < info_dgv.Rows.Count; i++)
                {
                    Tab1.Rows.Add();
                    Tab1.Cell(i + 2, 1).Range.Text = (i + 1).ToString();
                    for (int j = 0; j < info_dgv.Columns.Count; j++)
                    {
                        if (info_dgv.Rows[i].Cells[j].Value.GetType() == typeof(byte[]))
                        {
                            Sdraw.Image image1 = byteArrayToImage((byte[])info_dgv.Rows[i].Cells[j].Value);
                            image1.Save(@"L:\image.img");
                            Tab1.Cell(i + 2, j + 2).Range.InlineShapes.AddPicture(@"L:\image.img");
                            File.Delete(@"L:\image.img");
                        }
                        else
                        {
                            Tab1.Cell(i + 2, j + 2).Range.Text = info_dgv.Rows[i].Cells[j].Value.ToString();
                        }
                    }
                }
                Tab1.Columns.AutoFit();
            }
        }
Ejemplo n.º 55
0
 private void RaportBtn_Click(object sender, RoutedEventArgs e)
 {
     if (DGridConsumable.SelectedItem == null)
     {
         return;
     }
     else
     {
         SaveFileDialog openDlg = new SaveFileDialog();
         openDlg.FileName         = "Отчет №";
         openDlg.Filter           = "Word (.doc)|*.doc |Word (.docx)|*.docx |All files (*.*)|*.*";
         openDlg.FilterIndex      = 2;
         openDlg.RestoreDirectory = true;
         if (openDlg.ShowDialog() == true)
         {
             Word.Application word = new Microsoft.Office.Interop.Word.Application();
             Word.Document    doc  = word.Documents.Open(Environment.CurrentDirectory + @"\Tovarny_otchyot_-_materialy.doc");
             var SelectedInfo      = DGridConsumable.SelectedItems.Cast <ReplenishmentOfMaterials>().FirstOrDefault() as ReplenishmentOfMaterials;
             var info           = AccountingForConsumablesEntities.GetContext().MaterialsInDelivery.Where(w => w.FK_Replenishment == SelectedInfo.id).FirstOrDefault();
             var XHuman1        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 1).Select(s => s.FirstName + " " + s.MiddleName.Substring(0, 1) + " " + s.LastName.Substring(0, 1)).FirstOrDefault();
             var XHuman2        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 5).Select(s => s.FirstName + " " + s.MiddleName.Substring(0, 1) + " " + s.LastName.Substring(0, 1)).FirstOrDefault();
             var XHuman3        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 9).Select(s => s.FirstName + " " + s.MiddleName.Substring(0, 1) + " " + s.LastName.Substring(0, 1)).FirstOrDefault();
             var NameOfMaterial = info.MaterialCard.Materials.MaterialName;
             var Date           = DateTime.Now.ToShortDateString();
             var date2          = DateTime.Now.AddDays(7).ToShortDateString();
             var date3          = info.ReplenishmentOfMaterials.DateOfAcceptanceToTheWarehouse.ToShortDateString();
             var Number         = info.ReplenishmentOfMaterials.ContractNumber;
             var Worker1        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 2).FirstOrDefault();
             var Worker2        = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 34).FirstOrDefault();
             var GetDate        = DateTime.Today.ToShortDateString();
             try
             {
                 ReplaceWordStub("{getdate1}", Date, doc);
                 ReplaceWordStub("{GetDate2}", Date, doc);
                 ReplaceWordStub("{FirstDate}", date2, doc);
                 ReplaceWordStub("{DateOfDelivery}", date3, doc);
                 ReplaceWordStub("{Number}", Number, doc);
                 ReplaceWordStub("{FirstName1}", Worker1.FirstName, doc);
                 ReplaceWordStub("{FirstName2}", Worker1.FirstName, doc);
                 ReplaceWordStub("{FirstName3}", Worker2.FirstName, doc);
                 ReplaceWordStub("{LastName1}", Worker1.LastName, doc);
                 ReplaceWordStub("{LastName2}", Worker1.LastName, doc);
                 ReplaceWordStub("{LastName3}", Worker2.LastName, doc);
                 ReplaceWordStub("{MiddleName1}", Worker1.MiddleName, doc);
                 ReplaceWordStub("{MiddleName2}", Worker1.MiddleName, doc);
                 ReplaceWordStub("{MiddleName3}", Worker2.MiddleName, doc);
                 ReplaceWordStub("{Position1}", Worker2.Position.PositionName, doc);
                 ReplaceWordStub("{Position2}", Worker1.Position.PositionName, doc);
                 ReplaceWordStub("{Position}", Worker1.Position.PositionName, doc);
                 ReplaceWordStub("{N}", info.id.ToString(), doc);
                 ReplaceWordStub("{N1}", info.id + 1000.ToString(), doc);
                 ReplaceWordStub("{NameOfMaterial}", NameOfMaterial, doc);
             }
             catch (Exception ex)
             {
                 MessageBox.Show("" + ex);
             }
             doc.SaveAs2(openDlg.FileName);
             doc.Close();
         }
     }
 }
Ejemplo n.º 56
0
        public Word.Document getWordDocument()
        {
            try
            {
                object missing = System.Reflection.Missing.Value;

                //Create a new document
                Word.Document document = new Word.Document();

                //Add header into the document
                foreach (Word.Section section in document.Sections)
                {
                    //Get the header range and add the header details.
                    Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
                    headerRange.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    headerRange.ParagraphFormat.FirstLineIndent = 0;
                    headerRange.Font.ColorIndex = Word.WdColorIndex.wdBlue;
                    headerRange.Font.Size       = 10;
                }

                //Add the footers into the document
                foreach (Word.Section wordSection in document.Sections)
                {
                    //Get the footer range and add the footer details.
                    Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex           = Word.WdColorIndex.wdDarkRed;
                    footerRange.Font.Size                 = 10;
                    footerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }

                //Create title
                Word.Paragraph title = document.Content.Paragraphs.Add(ref missing);
                title.Range.Text             = this.Title;
                title.Format.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                title.Range.Font.Size        = 26;
                title.Range.Font.Color       = Word.WdColor.wdColorDarkBlue;
                title.Format.FirstLineIndent = 0;
                title.Range.InsertParagraphAfter();

                //Create date report
                Word.Paragraph ReportDate = document.Content.Paragraphs.Add(ref missing);
                ReportDate.Range.Text             = "Export date: " + this.createDate.ToLongDateString();
                ReportDate.Format.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphRight;
                ReportDate.Range.Font.Size        = 14;
                ReportDate.Range.Font.Color       = Word.WdColor.wdColorBlack;
                ReportDate.Format.FirstLineIndent = 0;
                ReportDate.Range.InsertParagraphAfter();

                //Create table and insert datatable
                Word.Table firstTable = document.Tables.Add(title.Range, Table.Rows.Count + 1, Table.Columns.Count + 1, ref missing, ref missing);
                firstTable.Range.Font.Size  = 10;
                firstTable.Range.Font.Color = Word.WdColor.wdColorBlack;
                firstTable.Borders.Enable   = 1;
                firstTable.AllowAutoFit     = true;

                int tableRow = 0; // row index for datatable
                foreach (Word.Row row in firstTable.Rows)
                {
                    int tableColumn = 0; // column index for datatable
                    foreach (Word.Cell cell in row.Cells)
                    {
                        cell.Range.Font.Size   = 8;
                        cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                        //Header row
                        if (cell.RowIndex == 1)
                        {
                            if (cell.ColumnIndex == 1)
                            {
                                cell.Range.Text = "STT";
                            }
                            else
                            {
                                cell.Range.Text = Table.Columns[tableColumn].ColumnName;
                                tableColumn++;
                            }
                            cell.Range.Font.Bold = 1;
                            //other format properties goes here
                            cell.Range.Font.Name = "verdana";
                            //Center alignment for the Header cells
                            cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        }
                        //Data row
                        else
                        {
                            if (cell.ColumnIndex == 1)
                            {
                                cell.Range.Text = (cell.RowIndex - 1).ToString();
                            }
                            else
                            {
                                //check for image cell and print
                                if (Table.Rows[tableRow][tableColumn].GetType() == typeof(byte[]))
                                {
                                    Image image = new Picture().ByteArrToImage((byte[])Table.Rows[tableRow][tableColumn]);

                                    // resize image
                                    Bitmap bitmap = new Bitmap(image, new Size(90, 90));
                                    image = (Image)bitmap;

                                    Clipboard.SetImage(image);
                                    cell.Range.PasteAndFormat(Word.WdRecoveryType.wdSingleCellTable);
                                    Clipboard.Clear();
                                }
                                else if (Table.Rows[tableRow][tableColumn].GetType() == typeof(DateTime))
                                {
                                    cell.Range.Text = ((DateTime)Table.Rows[tableRow][tableColumn]).ToShortDateString();
                                    tableColumn++;
                                }
                                else
                                {
                                    cell.Range.Text = (Table.Rows[tableRow][tableColumn]).ToString().Trim();
                                    tableColumn++;
                                }
                            }
                        }
                    }
                    if (row.Index != 1)
                    {
                        tableRow++;
                    }
                }
                return(document);
            }
            catch (Exception)
            {
                return(null);

                throw;
            }
        }
 private void createTemplate()
 {
     object isTemplate = true;
     object isVisible = false;
     FabDotxAsDocument = Globals.ThisAddIn.Application.Documents.Add(ref missingType, ref isTemplate, ref missingType, ref isVisible);
 }
Ejemplo n.º 58
0
        private void RaportBtn2_Click(object sender, RoutedEventArgs e)
        {
            if (DGridConsumable.SelectedItem == null)
            {
                return;
            }
            else
            {
                SaveFileDialog openDlg = new SaveFileDialog();
                openDlg.FileName         = "Отчет №";
                openDlg.Filter           = "Word (.doc)|*.doc |Word (.docx)|*.docx |All files (*.*)|*.*";
                openDlg.FilterIndex      = 2;
                openDlg.RestoreDirectory = true;
                if (openDlg.ShowDialog() == true)
                {
                    Word.Application word = new Microsoft.Office.Interop.Word.Application();
                    Word.Document    doc  = word.Documents.Open(Environment.CurrentDirectory + @"\Akt_priyoma_peredachi_materialov.docx");
                    var SelectedInfo      = DGridConsumable.SelectedItems.Cast <ReplenishmentOfMaterials>().FirstOrDefault() as ReplenishmentOfMaterials;
                    var info = AccountingForConsumablesEntities.GetContext().MaterialsInDelivery.Where(w => w.FK_Replenishment == SelectedInfo.id).FirstOrDefault();
                    List <ReplenishmentOfMaterials> materialsInDeliverieLst = new List <ReplenishmentOfMaterials>();
                    materialsInDeliverieLst.AddRange(DGridConsumable.SelectedItems.Cast <ReplenishmentOfMaterials>().ToList());



                    var Worker1 = AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 5).FirstOrDefault();
                    var GetDate = DateTime.Today.ToShortDateString();
                    MessageBox.Show("" + materialsInDeliverieLst.Count());
                    try
                    {
                        ReplaceWordStub("{DateOfDelivery}", info.ReplenishmentOfMaterials.DateOfAcceptanceToTheWarehouse.ToShortDateString(), doc);
                        ReplaceWordStub("{DateOfDelivery1}", info.ReplenishmentOfMaterials.DateOfAcceptanceToTheWarehouse.ToShortDateString(), doc);
                        ReplaceWordStub("{ GetDate }", DateTime.Now.ToShortDateString(), doc);
                        ReplaceWordStub("{Position}", AccountingForConsumablesEntities.GetContext().Worker.Where(w => w.id == 5).Select(s => s.Position.PositionName).FirstOrDefault(), doc);
                        ReplaceWordStub("{FirstName}", Worker1.FirstName, doc);
                        ReplaceWordStub("{LastName}", Worker1.LastName, doc);
                        ReplaceWordStub("{MiddleName}", Worker1.MiddleName, doc);
                        ReplaceWordStub("{Manufacturer}", info.MaterialCard.Materials.Manufacturer.ManufacturerName, doc);
                        ReplaceWordStub("{Email}", Worker1.Email, doc);
                        ReplaceWordStub("{ContactPhone}", Worker1.PhoneNumber, doc);
                        int i = 1;
                        foreach (var item in materialsInDeliverieLst)
                        {
                            var newItem = AccountingForConsumablesEntities.GetContext().MaterialsInDelivery.Where(w => w.FK_Replenishment == item.id).FirstOrDefault();

                            ReplaceWordStub("{MaterialGroup" + i + "}", newItem.MaterialCard.Materials.MaterialGroup.NameOfMaterialGroup, doc);
                            ReplaceWordStub("{MaterialName" + i + "}", newItem.MaterialCard.Materials.MaterialName, doc);
                            ReplaceWordStub("{InventNumber" + i + "}", newItem.MaterialCard.InventNumber, doc);
                            ReplaceWordStub("{DeliveryQuantity" + i + "}", newItem.MaterialQuantity.ToString(), doc);
                            i++;
                        }
                        ;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("" + ex);
                    }
                    doc.SaveAs2(openDlg.FileName);
                    doc.Close();
                }
            }
        }
Ejemplo n.º 59
0
 //打开文件,读入xml信息
 private void openFile(string stu, string ans, string xml)
 {
     word = new Word.Application();
     Object confirmConversions = Type.Missing;
     Object readOnly = true;
     Object addToRecentFiles = Type.Missing;
     Object passwordDocument = Type.Missing;
     Object passwordTemplate = Type.Missing;
     Object revert = Type.Missing;
     Object writePasswordDocument = Type.Missing;
     Object writePasswordTemplate = Type.Missing;
     Object format = Type.Missing;
     Object encoding = Type.Missing;
     Object visible = Type.Missing;
     Object openConflictDocument = Type.Missing;
     Object openAndRepair = Type.Missing;
     Object documentDirection = Type.Missing;
     Object noEncodingDialog = Type.Missing;
     Object file_path;
     file_path = stu;
     stuDoc = word.Documents.Open(ref file_path, ref confirmConversions,
         ref readOnly, ref addToRecentFiles, ref passwordDocument,
         ref passwordTemplate, ref revert, ref writePasswordDocument,
         ref writePasswordTemplate, ref format, ref encoding, ref visible,
         ref openConflictDocument, ref openAndRepair, ref documentDirection,
         ref noEncodingDialog);
     file_path = ans;
     ansDoc = word.Documents.Open(ref file_path, ref confirmConversions,
         ref readOnly, ref addToRecentFiles, ref passwordDocument,
         ref passwordTemplate, ref revert, ref writePasswordDocument,
         ref writePasswordTemplate, ref format, ref encoding, ref visible,
         ref openConflictDocument, ref openAndRepair, ref documentDirection,
         ref noEncodingDialog);
     oxml = new OfficeXML(xml);
     getPoint(oxml);
 }
Ejemplo n.º 60
0
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.Out.WriteLine("Неверно введены данные\nИспользование: programName <excelFile1> <wordFile> <excelFile2>");
                Console.Out.WriteLine("<excelFile1> - файл, содержащий список студентов");
                Console.Out.WriteLine("<wordFile> -шаблон для формирования писем");
                Console.Out.WriteLine("<excelFile2> - файл, содержащий описание и время практик\n\n\n");

                return;
            }

            Dictionary <String, HashSet <String> >            contracts = new Dictionary <string, HashSet <string> >();                                         //словарь ключ-пара <город,договоры>
            Dictionary <String, String>                       address   = new Dictionary <string, string>();                                                    //адреса назначения <город,адрес>
            Dictionary <String, Dictionary <String, String> > direct    = new Dictionary <string, Dictionary <string, string> >();                              //словарь ключ-пара <город,<направление,студенты >>
            Dictionary <Tuple <String, int>, HashSet <Tuple <string, int> > > course = new Dictionary <Tuple <string, int>, HashSet <Tuple <string, int> > >(); //<<направление,курс>,<описание,время>>
            Dictionary <String, Dictionary <String, String> > practice = new Dictionary <string, Dictionary <string, string> >();                               // <город,<описание и время,список студентов>>

            excel.Application excelAppDir   = new excel.Application();
            excel.Workbook    workbookDir   = excelAppDir.Workbooks.Open(args[2], ReadOnly: true);
            excel.Worksheet   worksheetDir  = workbookDir.Sheets[1];
            excel.Range       excelRangeDir = worksheetDir.UsedRange;

            int index = 2;

            while (excelRangeDir.Cells[index, 1].Value2 != null) //парсинг excel-файла с практикой
            {
                string courseName = excelRangeDir.Cells[index, 1].Value2.ToString();
                string courseType = excelRangeDir.Cells[index, 3].Value2.ToString();
                int    courseNum;
                int    courseTime;

                if (!int.TryParse(excelRangeDir.Cells[index, 2].Value2.ToString(), out courseNum))
                {
                    Console.WriteLine("Файл " + args[2] + " имеет пустые ячейки в строке " + index);
                }

                if (!int.TryParse(excelRangeDir.Cells[index, 4].Value2.ToString(), out courseTime))
                {
                    Console.WriteLine("Файл " + args[2] + " имеет пустые ячейки в строке " + index);
                }


                if (course.ContainsKey(Tuple.Create(courseName, courseNum)))
                {
                    course[Tuple.Create(courseName, courseNum)].Add(Tuple.Create(courseType, courseTime));
                }
                else
                {
                    course.Add(Tuple.Create(courseName, courseNum), new HashSet <Tuple <string, int> > {
                        Tuple.Create(courseType, courseTime)
                    });
                }


                index++;
            }

            workbookDir.Close(); // закрытие "книги" excel
            excelAppDir.Quit();  // завершение процесса excel


            index = 1;

            excel.Application excelApp   = new excel.Application();
            excel.Workbook    workbook   = excelApp.Workbooks.Open(args[0], ReadOnly: true);
            excel.Worksheet   worksheet  = workbook.Sheets[1];
            excel.Range       excelRange = worksheet.UsedRange;

            int CourseNum = 1;

            while (excelRange.Cells[index, 1].Value2 != null || excelRange.Cells[index + 1, 1].Value2 != null)
            {
                if (excelRange.Cells[index, 1].Value2 != null && excelRange.Cells[index, 1].Value2[0] != '2')
                {
                    string name     = excelRange.Cells[index, 1].Value2.ToString();
                    string faculty  = excelRange.Cells[index, 3].Value2.ToString();
                    string city     = excelRange.Cells[index, 5].Value2.ToString();
                    string contract = excelRange.Cells[index, 6].Value2.ToString();
                    string addr     = excelRange.Cells[index, 7].Value2.ToString();

                    if (course.ContainsKey(Tuple.Create(faculty, CourseNum))) // есть ли у студента практика,проверка по направлению и курсу
                    {
                        if (address.ContainsKey(city))                        //есть ли город в списке
                        {
                            contracts[city].Add(contract);                    //Город есть => добавляем контракт студента

                            if (direct[city].ContainsKey(faculty))            //содержит список
                            {
                                direct[city][faculty] = String.Join(", ", direct[city][faculty].ToString(), ShortName(name));
                            }
                            else
                            {
                                direct[city].Add(faculty, ShortName(name));
                            }


                            foreach (Tuple <String, int> pair in course[Tuple.Create(faculty, CourseNum)])
                            {
                                string[] practiceInfoArr = pair.Item1.Split(' ');

                                string practiceInfo = practiceInfoArr[0] + " " + practiceInfoArr[1] + " в объеме " + pair.Item2.ToString() + " часов";

                                if (practice[city].ContainsKey(practiceInfo))
                                {
                                    practice[city][practiceInfo] = String.Join(", ", practice[city][practiceInfo], ShortName(name));
                                }
                                else
                                {
                                    practice[city].Add(practiceInfo, ShortName(name));
                                }
                            }
                        }
                        else
                        {
                            contracts.Add(city, new HashSet <string>()
                            {
                                contract
                            });
                            address.Add(city, addr);
                            direct.Add(city, new Dictionary <string, string> {
                                { faculty, ShortName(name) }
                            });
                            practice.Add(city, new Dictionary <string, string>());

                            foreach (Tuple <String, int> pair in course[Tuple.Create(faculty, CourseNum)])
                            {
                                string[] practiceInfoArr = pair.Item1.Split(' ');

                                string practiceInfo = practiceInfoArr[0] + " " + practiceInfoArr[1] + " в объеме " + pair.Item2.ToString() + " часов";

                                if (practice[city].ContainsKey(practiceInfo))
                                {
                                    practice[city][practiceInfo] = String.Join(", ", practice[city][practiceInfo], ShortName(name));
                                }
                                else
                                {
                                    practice[city].Add(practiceInfo, ShortName(name));
                                }
                            }
                        }
                    }
                }
                else if (excelRange.Cells[index, 1].Value2 != null)
                {
                    string year      = excelRange.Cells[index, 1].Value2.ToString();
                    int    startYear = int.Parse(year.Substring(0, 4));
                    CourseNum = GetCourse(startYear);
                }

                index++;
            }


            workbook.Close();
            excelApp.Quit();


            int k = 1;

            foreach (KeyValuePair <string, string> pair in address)
            {
                try
                {
                    File.Delete(Path.Combine(args[1], "..", k.ToString() + ".doc"));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }


                try
                {
                    File.Copy(args[1], Path.Combine(args[1], "..", k.ToString() + ".doc"), true);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

                word.Application wordApp = new word.Application();
                word.Document    doc     = wordApp.Documents.Open(Path.Combine(args[1], "..", k.ToString() + ".doc"));

                ReplaceWord("{Where}", ToWhom(pair.Key, GetHead(address[pair.Key])), doc);
                ReplaceWord("{Address}", GetAddress(address[pair.Key]), doc);

                string   head  = GetHead(address[pair.Key]);
                string[] names = head.Split(' ');
                ArraySegment <string> segment = new ArraySegment <string>(names, names.Length - 2, 2);


                string name = string.Join(" ", segment);
                ReplaceWord("{ToWhom}", name, doc);

                Console.WriteLine("Введите имя и отчество: " + name);
                string secondName = Console.ReadLine();
                Console.WriteLine("\n");
                string genre = secondName[secondName.Length - 1].Equals('ч') ? "Уважаемый" : "Уважаемая";

                ReplaceWord("{ToWhom2}", genre + " " + secondName, doc);
                ReplaceWord("{City}", pair.Key, doc);

                string contractsStr = string.Join <string>(", ", contracts[pair.Key].Select(x => "№ " + x));
                ReplaceWord("{Contracts}", contractsStr, doc);

                string students = string.Empty;

                foreach (KeyValuePair <String, String> stud in direct[pair.Key])
                {
                    string editedKey = stud.Key.Insert(stud.Key.IndexOf(" ") + 1, "«");
                    editedKey += "»";
                    students  += stud.Value + " (" + editedKey + "), ";
                }

                students = students.Substring(0, students.Length - 2);


                ReplaceWord("{Students}", students, doc);
                ReplaceWord("{Date}", DateTime.Now.Year.ToString(), doc);

                word.Range range = doc.Content;
                range.Find.Execute(FindText: "{StudentsTable}");

                word.Table table = doc.Tables.Add(range, practice[pair.Key].Count, 2);
                table.Borders.Enable = 1;

                int rowIndex = 1;

                foreach (KeyValuePair <String, String> practicePair in practice[pair.Key])
                {
                    table.Cell(rowIndex, 1).Range.Text      = practicePair.Value;
                    table.Cell(rowIndex, 2).Range.Text      = practicePair.Key;
                    table.Cell(rowIndex, 1).Range.Font.Size = 11;
                    table.Cell(rowIndex, 2).Range.Font.Size = 11;

                    rowIndex++;
                }
                doc.Save();
                doc.Close();
                wordApp.Quit();


                k++;
            }

            Console.In.Read();
        }