private ControllerResult MailMergeExecute()
        {
            try
            {
                string fileName   = @"\datasource.csv";
                string sourcePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + fileName;

                System.IO.File.Create(sourcePath).Close();
                _dataModel.WriteToFile(sourcePath);

                Word.MailMerge mailMerge = ActiveDocument.MailMerge;

                mailMerge.OpenDataSource(sourcePath, Word.WdOpenFormat.wdOpenFormatAuto);
                mailMerge.Execute(true);
                mailMerge.DataSource.Close();
                System.IO.File.Delete(sourcePath);

                return(ControllerResult.Success);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show($"{ex.ToString()}");
                return(ControllerResult.Failure);
            }
        }
        private void GenerateLetter(Word.Selection wrdSelection, Word.MailMerge wrdMailMerge, out Word.MailMergeFields wrdMergeFields)
        {
            // Create a string and insert it into the document.
            wrdSelection.Font.Bold = 1;
            var strToAdd = _mailMergeData.Originator.Company + Environment.NewLine + _mailMergeData.Originator.Department;

            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wrdSelection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            wrdSelection.TypeText(strToAdd);

            InsertLines(4);

            // Insert merge data.
            wrdSelection.Font.Bold = 0;
            wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wrdMergeFields = wrdMailMerge.Fields;
            wrdMergeFields.Add(wrdSelection.Range, "Name");
            wrdSelection.TypeParagraph();
            wrdMergeFields.Add(wrdSelection.Range, "Address");

            InsertLines(2);

            // Right justify the line and insert a date field
            // with the current date.
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphRight;

            Object objDate = "dddd, MMMM dd, yyyy";

            wrdSelection.InsertDateTime(ref objDate, ref _oFalse, ref _oMissing,
                                        ref _oMissing, ref _oMissing);

            InsertLines(2);

            // Justify the rest of the document.
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphJustify;

            wrdSelection.TypeText("Dear ");
            wrdMergeFields.Add(wrdSelection.Range, "Name");
            wrdSelection.TypeText(",");
            InsertLines(2);

            //insert the messagebody
            wrdSelection.TypeText(_mailMergeData.MessageBody);
            InsertLines(2);

            // Go to the end of the document.
            Object oConst1 = Word.WdGoToItem.wdGoToLine;
            Object oConst2 = Word.WdGoToDirection.wdGoToLast;

            _wrdApp.Selection.GoTo(ref oConst1, ref oConst2, ref _oMissing, ref _oMissing);
            InsertLines(2);

            strToAdd = "Thank You," + Environment.NewLine + _mailMergeData.Originator.Name + Environment.NewLine + _mailMergeData.Originator.Designation;
            wrdSelection.TypeText(strToAdd);
        }
        public void ProcessWordMailMerge(bool SaveMailingList)
        {
            //OBJECT OF MISSING "NULL VALUE"
            Object oMissing = System.Reflection.Missing.Value;

            //OBJECTS OF FALSE AND TRUE
            Object oTrue  = true;
            Object oFalse = false;

            //CREATING OBJECTS OF WORD AND DOCUMENT
            Microsoft.Office.Interop.Word.Application oWordApp = new Microsoft.Office.Interop.Word.Application();

            //SETTING THE VISIBILITY TO TRUE
            oWordApp.Visible = true;

            //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
            Object oTemplatePath = _dealerMailingList.TemplateFilePath;

            //ADDING A NEW DOCUMENT FROM A TEMPLATE
            Microsoft.Office.Interop.Word.Document  oWordDoc       = oWordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
            Microsoft.Office.Interop.Word.MailMerge oWordMailMerge = oWordDoc.MailMerge;
            oWordDoc.MailMerge.OpenDataSource(_dealerMailingList.CsvFilePath);

            oWordDoc.MailMerge.Execute();

            oWordMailMerge.Application.ActiveDocument.SaveAs(ConfigurationManager.AppSettings.Get("MailMergeDocFilePath")
                                                             + _dealer.CompanyName.Replace(" ", "_")
                                                             + "_"
                                                             + _dealerMailingList.StartFilterDate.Month
                                                             + _dealerMailingList.StartFilterDate.Day
                                                             + _dealerMailingList.StartFilterDate.Year
                                                             + "_"
                                                             + _dealerMailingList.EndFilterDate.Month
                                                             + _dealerMailingList.EndFilterDate.Day
                                                             + _dealerMailingList.EndFilterDate.Year
                                                             + "_"
                                                             + _dealerMailingList.ID.ToString()
                                                             + "_" + _dealerMailingList.TemplateFileName.Replace(" ", "_").Substring(0, _dealerMailingList.TemplateFileName.Replace(" ", "_").IndexOf("."))
                                                             + ".docx");

            _dealerMailingList.MailMergeFilePath = ConfigurationManager.AppSettings.Get("MailMergeDocFilePath") + _dealer.CompanyName.Replace(" ", "_") + "_" + _dealerMailingList.StartFilterDate.Month + _dealerMailingList.StartFilterDate.Day + _dealerMailingList.StartFilterDate.Year + "_" + _dealerMailingList.EndFilterDate.Month + _dealerMailingList.EndFilterDate.Day + _dealerMailingList.EndFilterDate.Year + "_" + _dealerMailingList.ID.ToString() + "_" + _dealerMailingList.TemplateFileName.Replace(" ", "_").Substring(0, _dealerMailingList.TemplateFileName.Replace(" ", "_").IndexOf(".")) + ".docx";

            if (SaveMailingList)
            {
                DealerMailingListService.Save(_dealerMailingList);
            }
            oWordApp.Quit(oFalse, oMissing, oMissing);
        }
        private void GenerateEnvelope(Word.Selection wrdSelection, Word.MailMerge wrdMailMerge, out Word.MailMergeFields wrdMergeFields)
        {
            // Create a string and insert it into the document.
            wrdSelection.Font.Bold = 1;
            var strToAdd = _mailMergeData.Originator.Name + Environment.NewLine + _mailMergeData.Originator.Designation + Environment.NewLine + _mailMergeData.Originator.Department + ", " + _mailMergeData.Originator.Company;

            wrdSelection.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wrdSelection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            wrdSelection.TypeText(strToAdd);
            InsertLines(2);

            Object oConst1 = Word.WdGoToItem.wdGoToLine;
            Object oConst2 = Word.WdGoToDirection.wdGoToLast;

            _wrdApp.Selection.GoTo(ref oConst1, ref oConst2, ref _oMissing, ref _oMissing);

            wrdSelection.Font.Bold = 0;
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphRight;
            wrdMergeFields = wrdMailMerge.Fields;
            wrdMergeFields.Add(wrdSelection.Range, "Name");
            wrdSelection.TypeParagraph();
            wrdMergeFields.Add(wrdSelection.Range, "Address");
        }
示例#5
0
        private void btnNext_Click(object sender, EventArgs e)
        {
            if (btnNext.Text == "Next")
            {
                LoadMergeData();
                tabControlAdvancedMerge.SelectedTab = tabControlAdvancedMerge.TabPages[1];
                btnNext.Text = "Merge";
            }
            else if (btnNext.Text == "Merge" & btnNext.Enabled)
            {
                Word.Fields wordFields = Globals.ThisAddIn.Application.ActiveDocument.Fields;
                if (wordFields.Count > 0 && dataTableMergeData != null)
                {
                    if (Globals.ThisAddIn.Application.ActiveDocument.Saved)
                    {
                        MessageBox.Show("File is saved");
                    }
                    else
                    {
                        Globals.ThisAddIn.Application.ActiveDocument.Save();
                    }
                    string keyField = ReadDocumentProperty("KeyField");
                    Outlook.Application outlookApp      = new Outlook.Application();
                    Outlook.Accounts    outlookAccounts = outlookApp.Session.Accounts;
                    Outlook.MailItem    mailItem        = outlookApp.CreateItem(Outlook.OlItemType.olMailItem);

                    Word.Document wordDocument = Globals.ThisAddIn.Application.ActiveDocument;

                    var grouped = from table in dataTableMergeData.AsEnumerable()
                                  group table by new { keyCol = table[textBoxKeyField.Text] } into grp
                        select new
                    {
                        Value        = grp.Key,
                        ColumnValues = grp
                    };
                    foreach (var key in grouped)
                    {
                        Word.Application wordApplication = new Word.Application();
                        wordApplication.ShowAnimation = false;
                        wordApplication.Visible       = false;
                        object        missing     = System.Reflection.Missing.Value;
                        Word.Document newDocument = wordApplication.Documents.Open(wordDocument.Path + @"\" + wordDocument.Name, ReadOnly: true);

                        Word.MailMerge mailMerge = newDocument.MailMerge;


                        DataRow[] selectedRows = dataTableMergeData.Select(textBoxKeyField.Text + " ='" + key.Value.keyCol.ToString() + "'");

                        foreach (Word.MailMergeField mailMergeField in mailMerge.Fields)
                        {
                            if (mailMergeField.Code.Text.IndexOf(" MERGEFIELD " + "FirstName" + " ") > -1)
                            {
                                mailMergeField.Select();

                                mailMerge.Application.Selection.TypeText(selectedRows[1][2].ToString());
                            }
                            else if (mailMergeField.Code.Text.IndexOf(" MERGEFIELD " + "Product_name" + " ") > -1)
                            {
                                mailMergeField.Select();
                                mailMerge.Application.Selection.TypeText(selectedRows[1][4].ToString());
                                for (int i = 0; i < selectedRows.Length; i++)
                                {
                                    if (i < selectedRows.Length - 1)


                                    {
                                        for (int tableIndex = 0; tableIndex < newDocument.Tables.Count; tableIndex++)
                                        {
                                        }

/*                                        foreach  (Word.Table table in wordDocument.Tables)
 *                                      {
 *                                          foreach (Word.Row row in table.Rows)
 *                                          {
 *                                              foreach (Word.Cell cell in row.Cells)
 *                                              {
 *
 *                                              }
 *                                          }
 *
 *                                      }*/
                                        mailMerge.Application.Selection.InsertAfter("\r\n" + selectedRows[i + 1][4].ToString());
                                    }
                                }
                            }
                        }

                        mailItem.Subject = "Test";
                        mailItem.To      = "*****@*****.**";
                        mailItem.Body    = newDocument.Content.Text;
                        mailItem.Send();
                        newDocument.Close(false);
                        wordApplication.Quit(false);
                        Marshal.ReleaseComObject(newDocument);
                        Marshal.ReleaseComObject(wordApplication);
                    }
                }
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            List <string> list_id = (List <string>)ViewState["list"];
            List <int>    list    = list_id.Select(c => Convert.ToInt32(c)).ToList();

            if (list.Count == 0)
            {
                return;
            }
            string        attachmentFolder = Server.MapPath("~/Download/附件一/");
            string        customer         = this.ddlCustomer.SelectedItem.Text;
            string        saveFolder       = Path.Combine(attachmentFolder, customer);
            DirectoryInfo dirInfo          = new DirectoryInfo(saveFolder);

            if (!dirInfo.Exists)
            {
                dirInfo.Create();
            }
            string fileExt     = ".doc";
            String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            string savePath    = Path.Combine(saveFolder, newFileName);
            string docPath     = "/Download/附件一/" + customer + "/" + newFileName;

            string filePath = Server.MapPath("~/template_files/附件一权属企业舆情专报.doc");
            //string filePath = Server.MapPath("~/template_files/111.docx");
            object missing = Type.Missing;

            Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
            Word.Document document = null;
            try
            {
                document = wordApplication.Documents.Open(
                    filePath, ref missing, false,
                    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);
                Word.MailMerge wrdMailMerge = document.MailMerge;
                foreach (Word.MailMergeField f in wrdMailMerge.Fields)
                {
                    if (f.Code.Text.IndexOf("Customer") > -1)
                    {
                        f.Select();
                        wordApplication.Selection.TypeText(this.ddlCustomer.SelectedItem.Text.Replace("集团", ""));
                    }
                    else if (f.Code.Text.IndexOf("ReportType") > -1)
                    {
                        f.Select();
                        wordApplication.Selection.TypeText(this.ddlReportType.SelectedItem.Text);
                    }
                    else if (f.Code.Text.IndexOf("Subsidiary") > -1)
                    {
                        f.Select();
                        wordApplication.Selection.TypeText(this.ddlSubsidiary.SelectedItem.Text);
                    }
                    else if (f.Code.Text.IndexOf("Date") > -1)
                    {
                        f.Select();
                        wordApplication.Selection.TypeText(DateTime.Now.ToString("yyyy年MM月dd日"));
                    }
                    else if (f.Code.Text.IndexOf("CurrentNumber") > -1)
                    {
                        f.Select();
                        using (var context = new ReportContext())
                        {
                            int CustomerID    = int.Parse(this.ddlCustomer.SelectedValue);
                            int reportTypeId  = int.Parse(this.ddlReportType.SelectedValue);
                            int currentNumber = 0;
                            var entity        = context.ReportNumbers.FirstOrDefault(a => a.CustomerID == CustomerID && a.ReportTypeId == reportTypeId);
                            if (entity != null)
                            {
                                currentNumber = entity.CurrentNumber.Value;
                            }
                            wordApplication.Selection.TypeText(currentNumber.ToString());
                        }
                    }
                    else if (f.Code.Text.IndexOf("TotalNumber") > -1)
                    {
                        f.Select();
                        using (var context = new ReportContext())
                        {
                            int CustomerID   = int.Parse(this.ddlCustomer.SelectedValue);
                            int reportTypeId = int.Parse(this.ddlReportType.SelectedValue);
                            int totalNumber  = 0;
                            var entity       = context.ReportNumbers.FirstOrDefault(a => a.CustomerID == CustomerID && a.ReportTypeId == reportTypeId);
                            if (entity != null)
                            {
                                totalNumber = entity.TotalNumber.Value;
                            }
                            wordApplication.Selection.TypeText(totalNumber.ToString());
                        }
                    }
                    else if (f.Code.Text.IndexOf("Content") > -1)
                    {
                        f.Select();
                        using (var context = new ReportContext())
                        {
                            var articles = context.Articles.Where(a => list.Contains(a.ID)).OrderByDescending(a => a.Rating);
                            int i        = 0;
                            //wordApplication.Selection.ParagraphFormat.IndentFirstLineCharWidth(1);
                            foreach (var article in articles)
                            {
                                i++;

                                wordApplication.Selection.Font.Bold = (int)Word.WdConstants.wdToggle;
                                wordApplication.Selection.Font.Size = 16;
                                wordApplication.Selection.Font.Name = "楷体_GB2312";
                                string title = String.Format("{0}.{1}", i, article.Title);

                                wordApplication.Selection.TypeText(title);
                                wordApplication.Selection.TypeParagraph();
                                wordApplication.Selection.Font.Bold = (int)Word.WdConstants.wdToggle;

                                //wordApplication.Selection.Font.Size = 16;
                                wordApplication.Selection.Font.Name = "仿宋_GB2312";
                                wordApplication.Selection.TypeText(article.Content);
                                wordApplication.Selection.TypeParagraph();
                                if (!string.IsNullOrEmpty(article.ScreenshotsPath))
                                {
                                    FileInfo fileInfo = new FileInfo(Server.MapPath(article.ScreenshotsPath));
                                    if (fileInfo.Exists)
                                    {
                                        wordApplication.Selection.InlineShapes.AddPicture(Server.MapPath(article.ScreenshotsPath), missing, missing, missing);
                                        wordApplication.Selection.TypeParagraph();
                                    }
                                }


                                wordApplication.Selection.TypeText("网址链接:");

                                wordApplication.Selection.Font.Name = "宋体";
                                Word.Range range = wordApplication.Selection.Range;
                                wordApplication.Selection.Font.Size = 10;
                                wordApplication.Selection.Hyperlinks.Add(range, article.Url, missing, missing, article.Url, missing);
                                wordApplication.Selection.TypeParagraph();



                                wordApplication.Selection.Font.Name = "仿宋_GB2312";
                                wordApplication.Selection.Font.Size = 16;
                                wordApplication.Selection.TypeText("风险分析研判:");
                                wordApplication.Selection.TypeText(article.JudgeContent);
                                wordApplication.Selection.TypeParagraph();
                                wordApplication.Selection.TypeText("舆情星级:");
                                wordApplication.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;
                                wordApplication.Selection.TypeText("★".Repeat(article.Rating.Value));
                                wordApplication.Selection.TypeParagraph();

                                wordApplication.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlack;
                                wordApplication.Selection.TypeText("处置建议:");
                                wordApplication.Selection.TypeText(article.SuggestContent);
                                wordApplication.Selection.TypeParagraph();
                            }
                        }
                    }
                }
                document.SaveAs2(savePath, Word.WdSaveFormat.wdFormatDocument, missing, missing,
                                 missing, missing, false, missing, missing, missing, missing, missing, missing, missing, missing,
                                 missing, missing);
                using (var context = new ReportContext())
                {
                    int customerId   = int.Parse(this.ddlCustomer.SelectedValue);
                    int reportTypeId = int.Parse(this.ddlReportType.SelectedValue);
                    var entity       = context.ReportNumbers.FirstOrDefault(a => a.CustomerID == customerId && a.ReportTypeId == reportTypeId);
                    if (entity != null)
                    {
                        entity.CurrentNumber++;
                        entity.TotalNumber++;
                        context.SaveChanges();
                    }
                }
                System.Data.DataTable table = (System.Data.DataTable)ViewState["Table"];
                System.Data.DataRow   row   = table.NewRow();
                row["FileName"]   = newFileName;
                row["FilePath"]   = savePath;
                row["Customer"]   = this.ddlCustomer.SelectedItem.Text;
                row["Subsidiary"] = this.ddlSubsidiary.SelectedItem.Text;
                row["AddDate"]    = DateTime.Now.ToString();
                row["DocPath"]    = docPath;
                table.Rows.Add(row);
                BindRepeater1(table);
                BindGridView1(int.Parse(this.ddlCustomer.SelectedValue), this.AspNetPager1.CurrentPageIndex);
            }

            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.UpdatePanel4, GetType(), "alert", "alert('" + ex.Message + "')", true);
            }
            finally
            {
                if (document != null)
                {
                    document.Close(Word.WdSaveOptions.wdDoNotSaveChanges, ref missing, ref missing);
                    document = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref missing, ref missing, ref missing);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }