public void ConvertDocxToPdf(string input, string output) { // Create an instance of Word.exe Word._Application oWord = new Word.Application(); // Make this instance of word invisible (Can still see it in the taskmgr). oWord.Visible = false; // Interop requires objects. object oMissing = System.Reflection.Missing.Value; object isVisible = true; object readOnly = false; object oInput = input; object oOutput = output; object oFormat = Word.WdSaveFormat.wdFormatPDF; // Load a document into our instance of word.exe Word._Document oDoc = oWord.Documents.Open(ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Make this document the active document. oDoc.Activate(); // Save this document in Word 2003 format. oDoc.SaveAs(ref oOutput, ref oFormat, 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); // Always close Word.exe. object saveChanges = false; oWord.Quit(ref saveChanges, ref oMissing, ref oMissing); }
/// <summary> /// 化验单 /// </summary> /// <param name="a"></param> private void PrintAssay(Assay a) { Log.Logs += $"正在打印化验单:{a.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintAssayDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", a.Name); if (a.Purchase != null) { WordReplace(wApp, "#CarnoOrStorename#", "车号:" + a.Purchase.CarNo); } if (a.Store != null) { WordReplace(wApp, "#CarnoOrStorename#", "油仓:" + a.Store.Name); } WordReplace(wApp, "#视密#", a.视密.ToString("0.000")); WordReplace(wApp, "#标密#", a.标密.ToString("0.000")); WordReplace(wApp, "#闭口闪点#", a.闭口闪点); WordReplace(wApp, "#Temperature#", a.Temperature.ToString("0.00")); WordReplace(wApp, "#OilTempTime#", a.OilTempTime.ToLongTimeString()); WordReplace(wApp, "#SmellType#", strSmellType(a.SmellType)); WordReplace(wApp, "#混水反应#", a.混水反应); WordReplace(wApp, "#十六烷值#", a.十六烷值); WordReplace(wApp, "#十六烷指数#", a.十六烷指数); WordReplace(wApp, "#初硫#", a.初硫.ToString("0.00")); WordReplace(wApp, "#Percentage10#", a.Percentage10.ToString("0.00")); WordReplace(wApp, "#Percentage50#", a.Percentage50.ToString("0.00")); WordReplace(wApp, "#Percentage90#", a.Percentage90.ToString("0.00")); WordReplace(wApp, "#回流#", a.回流.ToString("0.00")); WordReplace(wApp, "#干点#", a.干点.ToString("0.00")); WordReplace(wApp, "#蚀点#", a.蚀点.ToString("0.00")); WordReplace(wApp, "#凝点#", a.凝点.ToString("0.00")); WordReplace(wApp, "#含硫#", a.含硫.ToString("0.00")); WordReplace(wApp, "#CreatedBy#", a.CreatedBy); WordReplace(wApp, "#CreatedAt#", a.CreatedAt.ToString("yyyy-MM-dd HH:mm")); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + a.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
// Open a new document打开一个新文档 public void Open() { object missing = System.Reflection.Missing.Value; oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing); oDoc.Activate(); }
protected void btnCheck_Click(object sender, EventArgs e) { // Prevent multiple checker windows. if (applicationWord != null) { return; } applicationWord = new Microsoft.Office.Interop.Word.Application(); int errors = 0; if (tbInput.Text.Length > 0) { object template = Missing.Value; object newTemplate = Missing.Value; object documentType = Missing.Value; object visible = true; // Define a MS Word Document, then we use this document to calculate errors number and // invoke document's CheckSpelling method. Microsoft.Office.Interop.Word._Document documentCheck = applicationWord.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible); applicationWord.Visible = false; documentCheck.Words.First.InsertBefore(tbInput.Text); Microsoft.Office.Interop.Word.ProofreadingErrors spellErrorsColl = documentCheck.SpellingErrors; errors = spellErrorsColl.Count; object optional = Missing.Value; documentCheck.Activate(); documentCheck.CheckSpelling(ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional); documentCheck.LanguageDetected = true; // When users close the dialog, the error message will be displayed. if (errors == 0) { lbMessage.Text = "No errors"; } else { lbMessage.Text = "Total errors num:" + errors; } // Replace misspelled words of TextBox. object first = 0; object last = documentCheck.Characters.Count - 1; tbInput.Text = documentCheck.Range(ref first, ref last).Text; } object saveChanges = false; object originalFormat = Missing.Value; object routeDocument = Missing.Value; ((_Application)applicationWord).Quit(ref saveChanges, ref originalFormat, ref routeDocument); applicationWord = null; }
/// <summary> /// 陆上装车单 /// </summary> /// <param name="order">model</param> private void PrintLandLoad(Order order) { Log.Logs += $"正在打印LoadOil:{order.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintLandLoadDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 decimal DiffWeightToLitre = order.DiffWeight / (decimal)order.Density * 1000; decimal OilCountTon = order.OilCountLitre * (decimal)order.Density / 1000; decimal DiffPondLitre = order.OilCountLitre - DiffWeightToLitre; //填充数据 WordReplace(wApp, "#Name#", order.Name); WordReplace(wApp, "#ClientName#", order.Client.CarNo); WordReplace(wApp, "#CompanyName#", order.Client.Company?.Name); WordReplace(wApp, "#StoreName#", order.Store.Name); WordReplace(wApp, "#DiffWeight#", order.DiffWeight.ToString("0.0")); WordReplace(wApp, "#Count#", (order.Count * 1000).ToString("0.0")); WordReplace(wApp, "#DiffOrder#", (order.DiffWeight - order.Count * 1000).ToString("0.0")); WordReplace(wApp, "#Price#", order.IsPrintPrice? order.Price.ToString() : "0.00"); WordReplace(wApp, "#TotalMoney#", order.TotalMoney.ToString()); WordReplace(wApp, "#OilCount#", order.OilCountLitre.ToString()); WordReplace(wApp, "#OilCountTon#", OilCountTon.ToString("0.0")); WordReplace(wApp, "#DiffWeight#", (order.OilCarWeight - order.EmptyCarWeight).ToString("0.0")); WordReplace(wApp, "#DiffWeightTon#", ((order.OilCarWeight - order.EmptyCarWeight) / 1000).ToString("0.0")); WordReplace(wApp, "#DiffWeightToLitre#", DiffWeightToLitre.ToString("0.00")); WordReplace(wApp, "#DiffPondLitre#", DiffPondLitre.ToString("0.0")); WordReplace(wApp, "#DiffPondTon#", (DiffPondLitre * (decimal)order.Density / 1000).ToString("0.0")); WordReplace(wApp, "#Instrument_bf#", (order.Instrument1 - order.OilCountLitre).ToString()); WordReplace(wApp, "#Instrument_af#", order.Instrument1.ToString()); WordReplace(wApp, "#Density#", order.Density.ToString("0.000")); WordReplace(wApp, "#OilTemperature#", order.OilTemperature.ToString()); WordReplace(wApp, "#Worker#", order.Worker); WordReplace(wApp, "#LastUpdatedAt#", order.LastUpdatedAt.ToString()); WordReplace(wApp, "#Salesman#", order.Salesman); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + order.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
private void PrintUnload(Purchase p) { Log.Logs += $"正在打印陆上卸油单:{p.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintUnloadDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", p.Name); WordReplace(wApp, "#CarNo#", p.CarNo); WordReplace(wApp, "#ProductName#", p.Product?.Name); WordReplace(wApp, "#Count#", p.Count.ToString()); WordReplace(wApp, "#OilCount#", p.OilCount.ToString("0.00")); WordReplace(wApp, "#Density#", p.Density.ToString("0.000")); WordReplace(wApp, "#ScaleWithCar#", p.ScaleWithCar.ToString()); WordReplace(wApp, "#Scale#", p.Scale.ToString()); string strToStore = ""; foreach (var st in p.ToStoresList) { strToStore += "\r"; strToStore += "卸入仓:" + st.Name + "\r"; strToStore += "卸油前表数:" + st.InstrumentBf + "\r"; strToStore += "卸油后表数:" + st.InstrumentAf + "\r"; strToStore += "卸油数量:" + st.Count + "升\r"; } WordReplace(wApp, "#ToStores#", strToStore); WordReplace(wApp, "#DiffLitre#", p.DiffLitre.ToString("0.00")); WordReplace(wApp, "#DiffTon#", p.DiffTon.ToString("0.00")); WordReplace(wApp, "#Worker#", p.Worker); WordReplace(wApp, "#StartTime#", p.StartTime.HasValue ? DateTime.Parse(p.StartTime.ToString()).ToString("yyyy-MM-dd HH:mm") : ""); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + p.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
public static void ConvertToPdf(string input, string filename, string output) { WdSaveFormat format = WdSaveFormat.wdFormatPDF; Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word._Document oDoc = null; object oMissing = System.Reflection.Missing.Value; try { oWord.Visible = false; oWord.ScreenUpdating = false; object isVisible = true; object readOnly = true; object confirmConversions = false; object addToRecentFiles = false; object passwordDocument = "12345"; object oInput = input; object oOutput = output; object oFormat = WdOpenFormat.wdOpenFormatAuto; if (filename.EndsWith(".docx") || filename.EndsWith(".doc")) { oFormat = WdOpenFormat.wdOpenFormatAllWord; } oDoc = oWord.Documents.OpenNoRepairDialog(ref oInput, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oFormat, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.Activate(); object oSaveFormat = format; oDoc.SaveAs2(ref oOutput, ref oSaveFormat, 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); } finally { oWord.Quit(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges, ref oMissing, ref oMissing); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oWord); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oDoc); // Release all Interop objects. if (oDoc != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc); } if (oWord != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord); } oDoc = null; oWord = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
/// <summary> /// 调拨单 也是收款单 水上陆上共用 /// </summary> /// <param name="order"></param> private void PrintOrder(Order order) { Log.Logs += $"正在打印Order:{order.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintOrderDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", order.Name); WordReplace(wApp, "#CarNo#", order.CarNo); WordReplace(wApp, "#ProductName#", "石化油"); WordReplace(wApp, "#Count#", order.Count.ToString()); WordReplace(wApp, "#Unit#", order.Unit); WordReplace(wApp, "#Price#", order.IsPrintPrice ? order.Price.ToString("0.00") : ""); WordReplace(wApp, "#TotalMoney#", order.IsPrintPrice? order.TotalMoney.ToString("0.00") : ""); WordReplace(wApp, "#Payments#", strPayments(order.Payments.ToList())); WordReplace(wApp, "#CNMoney#", ConvertToChinese(order.TotalMoney)); WordReplace(wApp, "#Remark#", order.Remark); WordReplace(wApp, "#LastUpdatedBy#", order.Cashier); WordReplace(wApp, "#Salesman#", order.Salesman); WordReplace(wApp, "#CreatedAt#", order.CreatedAt.ToString("yyyy-MM-dd HH:mm")); PrintTime(wApp); string strInvoice = ""; if (order.IsInvoice) { strInvoice += "开票单位:" + order.BillingCompany + "\r"; strInvoice += "开票单价:¥" + order.BillingPrice + "\r"; strInvoice += "开票数量:" + order.BillingCount + order.Unit + "\r"; //strInvoice += "类型:" + strTicketType(order.TicketType); } WordReplace(wApp, "#InvoiceContent#", strInvoice); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + order.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
public void GenerateWordFile() { Word._Application wApp = new Word.Application(); Word.Documents wDocs = wApp.Documents; Word._Document wDoc = wDocs.Open(@"C:\Users\s.stadtler\source\repos\FST01\Sourcecode\FST.TournamentPlanner\FST.TournamentPlanner.Test\Urkunde_v1_edit.docx", ReadOnly: false); wDoc.Activate(); Word.Bookmarks wBookmarks = wDoc.Bookmarks; Word.Bookmark wBookmark = wBookmarks["Tuniername"]; Word.Range wRange = wBookmark.Range; wRange.Text = "Supertunier"; }
public void OpenFromDot(string strFileName) { object fileName = strFileName; object readOnly = false; object isVisible = true; object missing = System.Reflection.Missing.Value; oDoc = oWordApplic.Documents.Add(ref fileName, ref missing, ref missing, ref missing); oDoc.Activate(); }
/// <summary> /// 根据定义的书签 生成 word /// </summary> /// <param name="dc">简单的非重复型数据</param> public bool GenerateWordByBookmarks(Dictionary <string, string> dc) { killWinWordProcess(); if (!File.Exists(tempFile.ToString())) { MessageUtil.ShowError(string.Format("{0}模版文件不存在,请先设置模版文件。", tempFile.ToString())); return(false); } try { wApp = new Word.Application(); wApp.Visible = false; wDoc = wApp.Documents.Add(ref tempFile, ref missing, ref missing, ref missing); wDoc.Activate();// 当前文档置前 //string s = ""; // 替换书签 foreach (Word.Bookmark bm in wDoc.Bookmarks) { //s += "=" + bm.Name + ",\r\n"; foreach (string item in dc.Keys) { if (bm.Name == item) { bm.Select(); bm.Range.Text = dc[item]; } } } //Log.Info("ss", s); wDoc.SaveAs(ref saveFile, 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); DisposeWord(); return(true); } catch { MessageUtil.ShowError("生成失败"); return(false); } }
public void Start() { try { //Make hidden document active to receive selection HiddenDoc.Activate(); //results in a slight application focus loss } catch (System.Runtime.InteropServices.COMException ex) { if (ex.Message == "Object has been deleted.") { //Open Blank document, then attach styles *and update HiddenDoc = Globals.ThisAddIn.Application.Documents.Add(ref missing, ref missing, ref missing, ref FalseObj); HiddenDoc.set_AttachedTemplate(ref templateObj); HiddenDoc.UpdateStyles(); HiddenDoc.Activate(); } else { throw; } } //Remove Continue Bookmark, if exists Word.Bookmarks hiddenDocBookmarks = Globals.ThisAddIn.Application.ActiveDocument.Bookmarks; if (hiddenDocBookmarks.Exists("Continue")) { object deleteMarkObj = "Continue"; Word.Bookmark deleteMark = hiddenDocBookmarks.get_Item(ref deleteMarkObj); deleteMark.Select(); deleteMark.Delete(); } //Tell hidden document it has been saved to remove rare prompt to save document HiddenDoc.Saved = true; //Keep track when started started = true; }
// $名子试试$ // simpleExpPairValue.Add("$名子试试$","23232"); /// <summary> /// 根据定义模板 生成 word /// </summary> /// <param name="simpleExpPairValue">简单的非重复型数据</param> /// <param name="dt">模版包含头部信息和表格,表格重复使用 重复表格的数据</param> /// <param name="expPairColumn">模版包含头部信息和表格,表格重复使用 word中要替换的表达式和表格字段的对应关系</param> public bool GenerateWord(Dictionary <string, string> simpleExpPairValue, DataTable dt = null, Dictionary <string, string> expPairColumn = null) { if (!File.Exists(tempFile.ToString())) { MessageUtil.ShowError(string.Format("{0}模版文件不存在,请先设置模版文件。", tempFile.ToString())); return(false); } try { wApp = new Word.Application(); wApp.Visible = false; wDoc = wApp.Documents.Add(ref tempFile, ref missing, ref missing, ref missing); wDoc.Activate();// 当前文档置前 bool isGenerate = false; if (simpleExpPairValue != null && simpleExpPairValue.Count > 0) { isGenerate = ReplaceAllRang(simpleExpPairValue); } // 表格有重复 if (dt != null && dt.Rows.Count > 0 && expPairColumn != null && expPairColumn.Count > 0) { isGenerate = GenerateTable(dt, expPairColumn); } if (isGenerate) { wDoc.SaveAs(ref saveFile, 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); } DisposeWord(); return(true); } catch { MessageUtil.ShowError("生成失败"); return(false); } }
public bool ReplaceText(string a_TextToReplace, string a_Replacement) { string zReplacement = a_Replacement.Replace('\n', '\r'); // Чтобы обойти ограничение на 255 символов, делаем такой финт ушами // Заменяем 230 символов и добавляем спец метку, которую заменяем на оставшиеся if (zReplacement.Length > 255) { string zNewReplacement = zReplacement.Substring(0, 230) + "{{{continue_continue}}}"; // Если ничего не нашли то дальше можно не мучаться if (!ReplaceText(a_TextToReplace, zNewReplacement)) { return(false); } // Берем следующие 230 символов и дальше по рекурсии return(ReplaceText("{{{continue_continue}}}", zReplacement.Substring(230))); } else { _document.Activate(); _application.Selection.Find.ClearFormatting(); _application.Selection.Find.Replacement.ClearFormatting(); object zFindText = a_TextToReplace; object zReplaceWith = zReplacement; object zMatchCase = false; object zMatchWholeWord = false; object zMatchWildcards = false; object zMatchSoundsLike = false; object zMatchAllWordForms = false; object zForward = true; object zWrap = true; object zMatchKashida = false; object zMatchDiacritics = false; object zMatchAlefHamza = false; object zMatchControl = false; return(_application.Selection.Find.Execute(ref zFindText, ref zMatchCase, ref zMatchWholeWord, ref zMatchWildcards, ref zMatchSoundsLike, ref zMatchAllWordForms, ref zForward, ref zWrap, ref _missingObj, ref zReplaceWith, ref _missingObj, ref zMatchKashida, ref zMatchDiacritics, ref zMatchAlefHamza, ref zMatchControl)); } }
/// <summary> /// 模版包含头部信息和表格,表格重复使用 /// </summary> /// <param name="dt">重复表格的数据</param> /// <param name="expPairColumn">word中要替换的表达式和表格字段的对应关系</param> /// <param name="simpleExpPairValue">简单的非重复型数据</param> public bool GenerateWord(DataTable dt, Dictionary <string, string> expPairColumn, Dictionary <string, string> simpleExpPairValue) { if (!File.Exists(tempFile.ToString())) { HttpContext.Current.Response.Write("<script>alert('" + string.Format("{0}模版文件不存在,请先设置模版文件。", tempFile.ToString()) + "');</script>"); return(false); } try { wApp = new Word.Application(); wApp.Visible = false; wDoc = wApp.Documents.Add(ref tempFile, ref missing, ref missing, ref missing); wDoc.Activate();// 当前文档置前 bool isGenerate = false; //不重复替换 if (simpleExpPairValue != null && simpleExpPairValue.Count > 0) { isGenerate = ReplaceAllRang(simpleExpPairValue); } // 表格有重复 if (dt != null && dt.Rows.Count > 0 && expPairColumn != null && expPairColumn.Count > 0) { isGenerate = GenerateTable(dt, expPairColumn); } if (isGenerate) { wDoc.SaveAs(ref saveFile, 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); } DisposeWord(); return(true); } catch (Exception ex) { HttpContext.Current.Response.Write("<script>alert('" + "生成失败" + ex.Message + "');</script>"); return(false); } }
public static void ConvertMod(string input, string output, Word.WdSaveFormat format) { // Create an instance of Word.exe Word._Application oWord = new Word.Application(); object oMissing = System.Reflection.Missing.Value; object isVisible = true; object readOnly = false; object oInput = input; object oOutput = output; object oFormat = format; try { // Make this instance of word invisible (Can still see it in the taskmgr). oWord.Visible = false; // Load a document into our instance of word.exe Word._Document oDoc = oWord.Documents.Open(ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Make this document the active document. oDoc.Activate(); oDoc.PageSetup.LeftMargin = 15; oDoc.PageSetup.RightMargin = 15; oDoc.PageSetup.TopMargin = 15; oDoc.PageSetup.BottomMargin = 15; // Save this document in Word 2003 format. oDoc.SaveAs(ref oOutput, ref oFormat, 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); // Always close Word.exe. oWord.Quit(ref oMissing, ref oMissing, ref oMissing); } catch (Exception e) { oWord.Quit(ref oMissing, ref oMissing, ref oMissing); throw e; } }
/// PrinPreview the document /// </summary> /// <param name="fileToPrint"></param> private void PrinPriview(string fileToPrint) { object missing = System.Type.Missing; object objFile = fileToPrint; object readOnly = true; object addToRecentOpen = false; // Create a new Word application Microsoft.Office.Interop.Word._Application wordApplication = new Microsoft.Office.Interop.Word.Application(); try { // Create a new file based on our template Microsoft.Office.Interop.Word._Document wordDocument = wordApplication.Documents.Open(ref objFile, ref missing, ref readOnly, ref addToRecentOpen); wordApplication.Options.SaveNormalPrompt = false; if (wordDocument != null) { // Show print preview wordApplication.Visible = true; wordDocument.PrintPreview(); wordDocument.Activate(); //wordDocument.op while (!_IsPringPriview) { wordDocument.ActiveWindow.View.Magnifier = true; Thread.Sleep(500); } wordDocument.Close(ref missing, ref missing, ref missing); wordDocument = null; } } catch { //I didn't include a default error handler so i'm just throwing the error // throw ex; } finally { // Finally, Close our Word application wordApplication.Quit(ref missing, ref missing, ref missing); wordApplication = null; } }
/// <summary> /// 生产转仓单 /// </summary> /// <param name="m"></param> private void PrintMoveStore(MoveStore m) { Log.Logs += $"正在打印生产转仓:{m.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintMoveStoreDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", m.Name); WordReplace(wApp, "#OutStoreName#", m.OutStoreName); WordReplace(wApp, "#OutPlan#", m.OutPlan.ToString("0.00")); WordReplace(wApp, "#OutDensity#", m.OutDensity.ToString("0.000")); WordReplace(wApp, "#OutTemperature#", m.OutTemperature.ToString()); WordReplace(wApp, "#OutFact#", m.OutFact.ToString("0.00")); WordReplace(wApp, "#InStoreName#", m.InStoreName); WordReplace(wApp, "#InDensity#", m.InDensity.ToString("0.000")); WordReplace(wApp, "#InTemperature#", m.InTemperature.ToString()); WordReplace(wApp, "#InFact#", m.InFact.ToString("0.00")); WordReplace(wApp, "#Manufacturer#", m.Worker); WordReplace(wApp, "#LastUpdatedAt#", m.LastUpdatedAt.ToString("yyyy-MM-dd HH:mm")); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + m.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
/// <summary> /// 初始化 Common.Office.WordInfo /// </summary> private void Init() { try { this.wApp = new Word.Application() { Visible = true }; if (this.strWordFilePath == null) { this.wDoc = this.wApp.Documents.Add(); } else { if (this.strWordTemplatesFilePath == null) { this.wDoc = this.wApp.Documents.Open(this.strWordFilePath); } else { this.wDoc = this.wApp.Documents.Add(this.strWordTemplatesFilePath, ref missing, ref missing, ref missing); } } if (this.wDoc == null) { throw new Exception("Failed to open the Word file"); } wDoc.Activate();// 当前文档置前 wDoc.SaveAs2(this.strWordFilePath, 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) { Log.WriteLog(null, strBaseInfo, ex); } }
/// <summary> /// 出库石化过磅单 /// </summary> /// <param name="p"></param> private void PrintPonderation(Order o) { Log.Logs += $"正在打印出库石化过磅单:{o.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintPonderationDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", o.Name); WordReplace(wApp, "#CarNo#", o.CarNo); WordReplace(wApp, "#OilCarWeight#", o.OilCarWeight.ToString("0.00")); WordReplace(wApp, "#EmptyCarWeight#", o.EmptyCarWeight.ToString("0.00")); WordReplace(wApp, "#DiffWeight#", o.DiffWeight.ToString("0.00")); WordReplace(wApp, "#Worker#", o.Worker); WordReplace(wApp, "#LastUpdatedAt#", o.LastUpdatedAt.ToString()); WordReplace(wApp, "#EndOilDateTime#", o.EndOilDateTime.ToString()); WordReplace(wApp, "#StartOilDateTime#", o.StartOilDateTime.ToString()); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + o.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
private void PrintUnloadPond(Purchase p) { Log.Logs += $"正在打印卸车石化过磅单:{p.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintUnloadPondDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", p.Name); WordReplace(wApp, "#CarNo#", p.CarNo); WordReplace(wApp, "#ScaleWithCar#", p.ScaleWithCar.ToString()); WordReplace(wApp, "#Scale#", p.Scale.ToString()); WordReplace(wApp, "#DiffWeight#", p.DiffWeight.ToString()); WordReplace(wApp, "#Worker#", p.Worker); WordReplace(wApp, "#StartTime#", p.StartTime.HasValue ? DateTime.Parse(p.StartTime.ToString()).ToString("yyyy-MM-dd HH:mm"): ""); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + p.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
/// <summary> /// 船舶清污完工证 /// </summary> /// <param name="m"></param> private void PrintBoatClean(BoatClean m) { Log.Logs += $"正在打印BoatClean:{m.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintBoatCleanDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#Name#", m.Name); WordReplace(wApp, "#CarNo#", m.CarNo); WordReplace(wApp, "#Company#", m.Company); WordReplace(wApp, "#Voyage#", m.Voyage.ToString()); WordReplace(wApp, "#Tonnage#", m.Tonnage.ToString()); WordReplace(wApp, "#ResponseId#", m.ResponseId); WordReplace(wApp, "#Address#", m.Address); WordReplace(wApp, "#CreatedAt#", m.CreatedAt.ToString("yyyy-MM-dd HH:mm")); WordReplace(wApp, "#EndTime#", m.EndTime.ToString()); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + m.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
private void btnWord_Click(object sender, EventArgs e) { //Задаём переменную для отсутствующего параметра object ObjMissing = Missing.Value; if (cmbSemestr.SelectedIndex > 0) { try { //Создаём новое Word приложение Word._Application ObjWord = new Word.Application(); //Добавляем новый чистый документ Word Word._Document ObjDoc = ObjWord.Application.Documents.Add(); ObjDoc.Activate(); cfgPage(ObjDoc); textHeader(ObjMissing, ObjDoc); tableMain(ObjMissing, ObjDoc); textSignature(ObjMissing, ObjDoc); ObjWord.Visible = true; ObjDoc.SaveAs(Application.StartupPath + @"\" + "График замен на " + cmbSemestr.SelectedItem.ToString() + " " + DateTime.Now.Date.ToString("yyyyMMdd") + " " + DateTime.Now.TimeOfDay.ToString("hhmmss") + ".docx"); ObjDoc.Close(); ObjWord.Quit(); } catch { MessageBox.Show("Возможно на этом компьютере присутствует проблема совместимости с MS Word." + " Попробуйте установить версию 2007 и выше."); } } }
/// <summary> /// 公司预收款确认单 /// </summary> /// <param name="order"></param> private void PrintCompanyPrepayment(ChargeLog cl) { Log.Logs += $"正在打印ClientPrepayment:{cl.Company.Name}\r"; Word.Application thisApplication = new Word.ApplicationClass(); wApp = thisApplication; string tmpDocFile = AppDomain.CurrentDomain.BaseDirectory + folder + Properties.Settings.Default.PrintCompanyPrepaymentDocx; object templatefile = tmpDocFile; wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档 wDoc.Activate(); //当前文档置前 //填充数据 WordReplace(wApp, "#CompanyName#", cl.Company.Name); WordReplace(wApp, "#Money#", cl.Money.ToString("0.00")); WordReplace(wApp, "#CNMoney#", ConvertToChinese(cl.Money)); WordReplace(wApp, "#CreatedBy#", cl.CreatedBy); WordReplace(wApp, "#CreatedAt#", cl.CreatedAt.ToString("yyyy-MM-dd HH:mm")); WordReplace(wApp, "#PayType#", strPayType(cl.PayType)); WordReplace(wApp, "#Balances#", cl.Company.Balances.ToString()); PrintTime(wApp); object background = false; //这个很重要,否则关闭的时候会提示请等待Word打印完毕后再退出,加上这个后可以使Word所有 object filename = AppDomain.CurrentDomain.BaseDirectory + createdfolder + cl.Company.Name + ".docx"; wDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wDoc.PrintOut(ref background, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close(ref saveOption, ref missing, ref missing); //关闭当前文档,如果有多个模版文件进行操作,则执行完这一步后接着执行打开Word文档的方法即可 saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程 }
/// <summary> /// parse a word document and build a kinesis document model /// </summary> /// <param name="path">full path of the word document</param> /// <returns>equivalent kinesis document model</returns> public KineSis.ContentManagement.Model.Document ParseNewDocumentCharts(String path, ProcessingProgress pp, KineSis.ContentManagement.Model.Document document) { //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.OverallOperationName = "All Document Charts"; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// //directory where all the data will be saved String folderName = document.Location; String documentPath = System.IO.Path.Combine(DocumentService.TEMP_DIRECTORY, folderName); // Make this instance of word invisible (Can still see it in the taskmgr). wordApplication.Visible = false; // Interop requires objects. object oMissing = System.Reflection.Missing.Value; object isVisible = false; object readOnly = false; object oInput = path; object oOutput = documentPath + DD + DOC_FILES + DD + "document.xps"; object oFormat = WdSaveFormat.wdFormatXPS; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationName = "Opening MS Office"; pp.CurrentOperationTotalElements = 1; pp.CurrentOperationElement = 0; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// // Load a document into our instance of word.exe Microsoft.Office.Interop.Word._Document wdoc = wordApplication.Documents.Open(ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Make this document the active document. wdoc.Activate(); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationElement = 1; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// //KineSis.ContentManagement.Model.Document document = new KineSis.ContentManagement.Model.Document(); document.Name = wdoc.Name; document.Location = folderName; //create a new page KineSis.ContentManagement.Model.Page page = document.Pages[0]; //check if chart generation is wanted if (DocumentService.CHART_HORIZONTAL_FACES > 0) { //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationName = "Transforming"; pp.CurrentOperationTotalElements = 4; pp.CurrentOperationElement = 0; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// Thread thread = new Thread(new ThreadStart(ClearClipboard)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); //handle the charts wdoc.Shapes.SelectAll(); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationElement = 1; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// wdoc.ActiveWindow.Selection.Copy(); //copy all shapes //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationElement = 2; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// //open a new powerpoint application Presentation presentation = powerPointApplication.Presentations.Add(); //paste all copied shapes presentation.SlideMaster.Shapes.Paste(); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationElement = 3; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// //clear the clipboard //Clipboard.Clear(); Thread thread1 = new Thread(new ThreadStart(ClearClipboard)); thread1.SetApartmentState(ApartmentState.STA); thread1.Start(); thread1.Join(); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationElement = 4; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// List <Microsoft.Office.Interop.PowerPoint.Shape> charts = new List <Microsoft.Office.Interop.PowerPoint.Shape>(); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.OverallOperationTotalElements = EvaluatePresentation(presentation, pp); pp.OverallOperationElement = 0; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// //get all charts for (int j = 1; j <= presentation.SlideMaster.Shapes.Count; j++) { Microsoft.Office.Interop.PowerPoint.Shape shape = presentation.SlideMaster.Shapes[j]; if (shape.HasChart == Microsoft.Office.Core.MsoTriState.msoTrue) { charts.Add(shape); } } //create directory for charts String chartPath = System.IO.Path.Combine(documentPath, "charts"); System.IO.Directory.CreateDirectory(chartPath); //for every chart for (int j = 0; j < charts.Count; j++) { //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationName = "Chart " + (j + 1) + " of " + charts.Count; pp.CurrentOperationTotalElements = EvaluateChart(charts.ElementAt(j).Chart); pp.CurrentOperationElement = 0; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// KineSis.ContentManagement.Model.Chart mChart = new KineSis.ContentManagement.Model.Chart(); Microsoft.Office.Interop.PowerPoint.Shape chart = charts.ElementAt(j); mChart.SetThumbnailUrl(GenerateThumbnail(chart, chartPath + DD + j + "_thumb")); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.OverallOperationElement++; pp.CurrentOperationElement++; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// //set preferred width and height chart.Height = ((float)DocumentService.CHART_WIDTH * chart.Height) / chart.Width; chart.Width = DocumentService.CHART_WIDTH; //get chart type int chartType = GetChartType(chart.Chart); //reset rotation chart.Chart.Rotation = 0; int horizontalAngle = 0; //depending on how many horizontal faces are required, calculate the angle between them if (DocumentService.CHART_HORIZONTAL_FACES > 0) { horizontalAngle = 360 / DocumentService.CHART_HORIZONTAL_FACES; } int verticalAngle = 0; //depending on how many vertical faces are required for a horizontal face, celaculate the angle between them, excluding the vertical face at 90 degrees if (DocumentService.CHART_VERTICAL_FACES > 0) { verticalAngle = 90 / (DocumentService.CHART_VERTICAL_FACES + 1); } if (chart.Chart.HasTitle) { mChart.Title = chart.Chart.ChartTitle.Caption; } else { mChart.Title = chart.Name; } //does not support rotation (it's plain) if (chartType == 0) { //if horizontal faces number is 0, then no chart will be outputed if (DocumentService.CHART_HORIZONTAL_FACES > 0) { ChartHorizontalView hView = new ChartHorizontalView(); //draw chart face as image chart.Export(chartPath + DD + j + DocumentService.IMAGE_EXTENSION, DocumentService.IMAGE_FORMAT); //add to hView hView.ImageUrl = chartPath + DD + j + DocumentService.IMAGE_EXTENSION; //add to views mChart.Views.Add(hView); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.OverallOperationElement++; pp.CurrentOperationElement++; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// } } else { //for every horizontal face for (int k = 0; k < DocumentService.CHART_HORIZONTAL_FACES; k++) { ChartHorizontalView hView = new ChartHorizontalView(); //reset elevation chart.Chart.Elevation = 0; //export face as image chart.Export(chartPath + DD + j + _ + chart.Chart.Rotation + _ + chart.Chart.Elevation + DocumentService.IMAGE_EXTENSION, DocumentService.IMAGE_FORMAT); //set bitmap to view hView.ImageUrl = chartPath + DD + j + _ + chart.Chart.Rotation + _ + chart.Chart.Elevation + DocumentService.IMAGE_EXTENSION; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.OverallOperationElement++; pp.CurrentOperationElement++; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// //for every vertical face for (int l = 0; l < DocumentService.CHART_VERTICAL_FACES; l++) { ChartVerticalView vView = new ChartVerticalView(); //increse elevation chart.Chart.Elevation += verticalAngle; //export face as image chart.Export(chartPath + DD + j + _ + chart.Chart.Rotation + _ + chart.Chart.Elevation + DocumentService.IMAGE_EXTENSION, DocumentService.IMAGE_FORMAT); //set bitmap to view vView.ImageUrl = chartPath + DD + j + _ + chart.Chart.Rotation + _ + chart.Chart.Elevation + DocumentService.IMAGE_EXTENSION; //add vertical view to horizontal UP list hView.Up.Add(vView); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.OverallOperationElement++; pp.CurrentOperationElement++; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// } //some chart types, like 3D pie, does not support elevation less than 0 if (SupportsNegativeElevation(chart.Chart)) { //reset elevation chart.Chart.Elevation = 0; //for every vertical face for (int m = 0; m < DocumentService.CHART_VERTICAL_FACES; m++) { ChartVerticalView vView = new ChartVerticalView(); //decrease elevation chart.Chart.Elevation -= verticalAngle; //export face as image chart.Export(chartPath + DD + j + _ + chart.Chart.Rotation + _ + chart.Chart.Elevation + DocumentService.IMAGE_EXTENSION, DocumentService.IMAGE_FORMAT); //set bitmap to vertical view vView.ImageUrl = chartPath + DD + j + _ + chart.Chart.Rotation + _ + chart.Chart.Elevation + DocumentService.IMAGE_EXTENSION; //add vertical view to horizontal view DOWN list hView.Down.Add(vView); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.OverallOperationElement++; pp.CurrentOperationElement++; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// } } //increase horizontal angle in order to get the next horizontal view chart.Chart.Rotation += horizontalAngle; //add horizontal view to the chat's views list mChart.Views.Add(hView); } } //add chart to page page.Charts.Add(mChart); } //close presentation presentation.Close(); } wdoc.Close(SaveChanges: false); CloseOfficeApplication(); //return built document return(document); }
/// <summary> /// parse a word document and build a kinesis document model /// </summary> /// <param name="path">full path of the word document</param> /// <returns>equivalent kinesis document model</returns> KineSis.ContentManagement.Model.Document DocumentHelper.ParseNewDocument(String path, ProcessingProgress pp) { //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.OverallOperationName = "All Document Pages"; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// OpenOfficeApplication(); //directory where all the data will be saved String folderName = DocumentUtil.GenerateDirectoryName(); String documentPath = System.IO.Path.Combine(DocumentService.TEMP_DIRECTORY, folderName); System.IO.Directory.CreateDirectory(documentPath); // Make this instance of word invisible (Can still see it in the taskmgr). wordApplication.Visible = false; // Interop requires objects. object oMissing = System.Reflection.Missing.Value; object isVisible = false; object readOnly = false; object oInput = path; object oOutput = documentPath + DD + DOC_FILES + DD + "document.xps"; object oFormat = WdSaveFormat.wdFormatXPS; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationName = "Opening MS Office"; pp.CurrentOperationTotalElements = 1; pp.CurrentOperationElement = 0; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// // Load a document into our instance of word.exe Microsoft.Office.Interop.Word._Document wdoc = wordApplication.Documents.Open(ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Make this document the active document. wdoc.Activate(); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationElement = 1; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// KineSis.ContentManagement.Model.Document document = new KineSis.ContentManagement.Model.Document(); document.Name = wdoc.Name; document.Location = folderName; //write directory for pages String pagesPath = documentPath + DD + DOC_FILES; System.IO.Directory.CreateDirectory(pagesPath); //create a new page KineSis.ContentManagement.Model.Page page = new KineSis.ContentManagement.Model.Page(); page.Name = wdoc.Name; page.Location = documentPath + DD + DOC_FILES + DD + "document.html"; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationName = "Saving document"; pp.CurrentOperationTotalElements = 2; pp.CurrentOperationElement = 0; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// // Save this document in XPS format. wdoc.SaveAs(ref oOutput, ref oFormat, 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); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationElement = 1; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// wdoc.Close(SaveChanges: false); //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// pp.CurrentOperationElement = 2; //~~~~~~~~~~~~~progress~~~~~~~~~~~~~// try { wdoc.Close(SaveChanges: false); } catch (Exception) { } //CloseOfficeApplication(); //wordApplication.Quit(ref oMissing, ref oMissing, ref oMissing); BuildDocumentHTMLArgs args = new BuildDocumentHTMLArgs(documentPath + DD + DOC_FILES, pp); Thread thread = new Thread(new ParameterizedThreadStart(BuildDocumentHTML)); thread.SetApartmentState(ApartmentState.STA); thread.Start(args); thread.Join(); //build a html page from saved xps //BuildDocumentHTML(documentPath + DD + DOC_FILES, pp); //add page to document model document.Pages.Add(page); //delete the generated xps file FileInfo fi = new FileInfo(documentPath + DD + DOC_FILES + DD + "document.xps"); fi.Delete(); //return built document return(document); }
public ActionResult CreateDocumentsFromTemplate(ContractDetails details) { //Get data from db for current user DSGVOEntities1 db = new DSGVOEntities1(); kunden CurrentUser = db.kundens.Where(t => t.plz == details.UserZip.ToString().Trim() && t.seriennr.Substring(15).Trim() == details.SerialNo.ToString().Trim()).First(); ////Update contractuser in db //CurrentUser.contractuser = details.ContractUser.ToString().Trim(); ////Change email if it is changed //if (CurrentUser.email.ToString().Trim() != details.Email.ToString().Trim()) //{ // CurrentUser.email = details.Email.ToString().Trim(); //} //db.SaveChanges(); //Check if changes in data exist and send it in email StringBuilder dataChanges = new StringBuilder(); bool ChangesExist = false; dataChanges.Append("<table>"); dataChanges.Append(" <tr><th>Previous data</th><th>Changed data from user</th></tr>"); if (CurrentUser.name1.ToString().Trim() != details.Name1.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.name1.ToString().Trim() + " </td><td>" + details.Name1.ToString().Trim() + "</td></tr>"); CurrentUser.name1 = details.Name1.ToString().Trim(); } if (CurrentUser.name2.ToString().Trim() != details.Name2.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.name2.ToString().Trim() + " </td><td>" + details.Name2.ToString().Trim() + "</td></tr>"); CurrentUser.name2 = details.Name2.ToString().Trim(); } if (CurrentUser.strasse.ToString().Trim() != details.Street.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.strasse.ToString().Trim() + " </td><td>" + details.Street.ToString().Trim() + "</td></tr>"); CurrentUser.strasse = details.Street.ToString().Trim(); } if (CurrentUser.plz.ToString().Trim() != details.Zip.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.plz.ToString().Trim() + " </td><td>" + details.Zip.ToString().Trim() + "</td></tr>"); CurrentUser.plz = details.Zip.ToString().Trim(); } if (CurrentUser.ort.ToString().Trim() != details.City.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.ort.ToString().Trim() + " </td><td>" + details.City.ToString().Trim() + "</td></tr>"); CurrentUser.ort = details.City.ToString().Trim(); } //if (CurrentUser.land.ToString().Trim() != details.Country.ToString().Trim()) //{ // ChangesExist = true; // dataChanges.Append(" <tr><td>" + CurrentUser.land.ToString().Trim() + " </td><td>" + details.Country.ToString().Trim() + "</td></tr>"); //} if (CurrentUser.email.ToString().Trim() != details.Email.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.email.ToString().Trim() + " </td><td>" + details.Email.ToString().Trim() + "</td></tr>"); CurrentUser.email = details.Email.ToString().Trim(); } //if (CurrentUser.contractuser == null) //{ // ChangesExist = true; // dataChanges.Append(" <tr><td>Empty</td><td>" + details.ContractUser.ToString().Trim() + "</td></tr>"); //} ////Adding user data to viewbag //if (CurrentUser.name1 != null) //{ // details.Name1 = CurrentUser.name1.ToString().Trim(); //} //if (CurrentUser.name2 != null) //{ // details.Name2 = CurrentUser.name2.ToString().Trim(); //} //if (CurrentUser.strasse != null) //{ // details.Street= CurrentUser.strasse.ToString().Trim() + " " ; //} //if (CurrentUser.ort != null) //{ // details.City= CurrentUser.ort.ToString().Trim(); //} //if (CurrentUser.land != null) //{ // //Set country // switch (CurrentUser.land.ToString().Trim()) // { // case "D": // CurrentUser.land = "Deutschland"; // break; // case "A": // CurrentUser.land = "Österreich"; // break; // case "CH": // CurrentUser.land = "Schweiz"; // break; // default: // break; // } // details.Country = CurrentUser.land.ToString().Trim(); //} //if (CurrentUser.email != null) //{ // details.Contact = CurrentUser.email.ToString().Trim(); //} // Set country switch (details.Country.ToString().Trim()) { case "D": details.Country = "Deutschland"; break; case "A": details.Country = "Österreich"; break; case "CH": details.Country = "Schweiz"; break; default: break; } string Result, Name; //Generating strong name as word and pdf name string HashName = UserInfo.CalculateMD5Hash(details.SerialNo + "-" + details.UserZip); try { Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadFromFile(Server.MapPath("~/Template/template.docx").ToString()); if (details.Name1 != null && details.Name1.ToString().Trim() != "") { document.Replace("##AGName1##", details.Name1, false, true); } else { document.Replace("##AGName1##", "", false, true); } if (details.Name2 != null && details.Name2.ToString().Trim() != "") { document.Replace("##AGName2##", details.Name2, false, true); } else { document.Replace("##AGName2##", "", false, true); } if (details.Street != null && details.Street.ToString().Trim() != "") { document.Replace("##AGStreet##", details.Street, false, true); } else { document.Replace("##AGStreet##", "", false, true); } if (details.Zip != null && details.Zip.ToString().Trim() != "") { document.Replace("##AGZIP##", details.Zip, false, true); } else { document.Replace("##AGZIP##", "", false, true); } if (details.City != null && details.City.ToString().Trim() != "") { document.Replace("##AGCITY##", details.City, false, true); document.Replace("##City##", details.City, false, true); } else { document.Replace("##AGCITY##", "", false, true); document.Replace("##City##", "", false, true); } if (details.Country != null && details.Country.ToString().Trim() != "") { document.Replace("##AGCountry##", details.Country, false, true); } else { document.Replace("##AGCountry##", "", false, true); } if (details.ContractUser != null && details.ContractUser.ToString().Trim() != "") { document.Replace("##ContractUser##", details.ContractUser, false, true); } if (details.Email != null && details.Email.ToString().Trim() != "") { document.Replace("##AGCONTACT##", details.Email, false, true); } else { document.Replace("##AGCONTACT##", "", false, true); } document.Replace("##DayDate##", DateTime.Now.ToString("dd.MM.yyyy"), false, true); document.SaveToFile(Server.MapPath("~/Word/").ToString() + HashName + ".docx", Spire.Doc.FileFormat.Docx); //Code for making connection with existing word template Microsoft.Office.Interop.Word._Application wApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Documents wDocs = wApp.Documents; Microsoft.Office.Interop.Word._Document wDoc = wDocs.Open(Server.MapPath("~/Word/").ToString() + HashName + ".docx", ReadOnly: false, Visible: false); wDoc.Activate(); string pdfName = @Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf"; //wDoc.ExportAsFixedFormat(OutputFileName: pdfName, ExportFormat: WdExportFormat.wdExportFormatPDF, UseISO19005_1: true); wDoc.ExportAsFixedFormat( pdfName, WdExportFormat.wdExportFormatPDF, OptimizeFor: WdExportOptimizeFor.wdExportOptimizeForPrint, BitmapMissingFonts: true, DocStructureTags: false, UseISO19005_1: true); wDoc.Close(); //Update fields into db CurrentUser.contractuser = details.ContractUser; CurrentUser.contactperson = details.ContractUser; CurrentUser.contractsigned = true; CurrentUser.signeddate = DateTime.Now; CurrentUser.contractname = HashName + ".pdf"; //Send email with pdf as attachment to office SmtpClient smtpClient = new SmtpClient(); NetworkCredential basicCredential = new NetworkCredential("*****@*****.**", "hopeDSGVO"); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); MailAddress fromAddress = new MailAddress("*****@*****.**"); smtpClient.Host = "smtp.1und1.de"; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = basicCredential; smtpClient.Port = 587; smtpClient.EnableSsl = true; message.From = fromAddress; message.Subject = "hope-DSGVO - AV-Vertrag, Kunde: " + details.UserZip + " - hotel: " + details.Name1; message.Attachments.Add(new System.Net.Mail.Attachment(Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf")); //[email protected] message.To.Add(new MailAddress("*****@*****.**")); smtpClient.Send(message); //Send email to customer SmtpClient smtpCustomer = new SmtpClient(); NetworkCredential basicCredentialCustomer = new NetworkCredential("*****@*****.**", "hopeDSGVO"); System.Net.Mail.MailMessage messageCustomer = new System.Net.Mail.MailMessage(); MailAddress fromAddressCompany = new MailAddress("*****@*****.**"); smtpCustomer.Host = "smtp.1und1.de"; smtpCustomer.UseDefaultCredentials = false; smtpCustomer.Credentials = basicCredential; smtpCustomer.Port = 587; smtpCustomer.EnableSsl = true; messageCustomer.From = fromAddressCompany; messageCustomer.Subject = "hope-DSGVO - AV-Vertrag, Kunde: " + details.UserZip + " - hotel: " + details.Name1; messageCustomer.Attachments.Add(new System.Net.Mail.Attachment(Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf")); //[email protected] messageCustomer.To.Add(new MailAddress(CurrentUser.email.ToString().Trim())); smtpCustomer.Send(messageCustomer); //Send email if user changed data on html form [email protected] if (ChangesExist) { //Send email with pdf as attachemnt SmtpClient smtpClientSecond = new SmtpClient(); NetworkCredential basicCredentialSecond = new NetworkCredential("*****@*****.**", "hopeDSGVO"); System.Net.Mail.MailMessage messageSecond = new System.Net.Mail.MailMessage(); MailAddress fromAddressSecond = new MailAddress("*****@*****.**"); smtpClientSecond.Host = "smtp.1und1.de"; smtpClientSecond.UseDefaultCredentials = false; smtpClientSecond.Credentials = basicCredential; smtpClientSecond.Port = 587; smtpClientSecond.EnableSsl = true; messageSecond.From = fromAddress; messageSecond.Subject = "hope-DSGVO - Kundendaten geändert: " + details.UserZip + " - hotel: " + details.Name1; messageSecond.IsBodyHtml = true; messageSecond.Body = dataChanges.ToString(); //[email protected] messageSecond.To.Add(new MailAddress("*****@*****.**")); smtpClientSecond.Send(message); //Update field in database CurrentUser.datachanged = true; } //Update field in database db.SaveChanges(); return(Json(new { Result = "true", Name = HashName })); } catch (Exception ex) { Console.WriteLine("Error occured:", ex.ToString()); return(Json(Result = ex.ToString())); } finally { Dispose(); } }
private void btnExportModelThreats_Click(object sender, EventArgs e) { mf.wsm.Visible = true; mf.wsm.Update(); Microsoft.Office.Interop.Word._Application oWord = null; try { oWord = new Microsoft.Office.Interop.Word.Application(); } catch { mf.wsm.Visible = false; MessageBox.Show("На ПК не установлен пакет Microsoft Office Word 2007 или позднее. Экспорт невозможен.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Microsoft.Office.Interop.Word._Document oDoc = null; try { oDoc = oWord.Documents.Add(Environment.CurrentDirectory + "\\template.docx"); } catch { mf.wsm.Visible = false; MessageBox.Show("Отсутствует файл шаблона тех. проекта \"template.docx\". Экспорт невозможен.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Table wordTable; //oWord.Visible = true; #region асчет уровня проектной защищенности wordTable = oDoc.Tables[1]; int rowN = 4; Console.WriteLine(IS.listOfSFHs.Count + ""); foreach (SFHType sfhtype in listSFHTypes) { foreach (SFH sfh in listSFHs.Where(sfh => sfh.SFHType == sfhtype).ToList()) { if (IS.listOfSFHs.Where(l => l.SFHNumber == sfh.SFHNumber).ToList().Count > 0) { wordTable.Cell(rowN, 4 - sfh.ProjectSecurity).Range.Text = "+"; } rowN++; } rowN++; } rowN++; wordTable.Cell(rowN++, 2).Range.Text = mf.dgvProjectSecurityResult.Rows[0].Cells[1].Value.ToString(); wordTable.Cell(rowN++, 3).Range.Text = mf.dgvProjectSecurityResult.Rows[1].Cells[1].Value.ToString(); wordTable.Cell(rowN, 4).Range.Text = mf.dgvProjectSecurityResult.Rows[2].Cells[1].Value.ToString(); #endregion #region Виды, типы и потенциал нарушителя Range bm = oDoc.Bookmarks["Intruder_Table"].Range; int rowsNumber = 1; foreach (System.Windows.Forms.CheckBox i in mf.clbIntruderTypes.Controls) { if (i.CheckState == CheckState.Checked) { rowsNumber++; } } bm.Tables.Add(bm, rowsNumber, 3, Type.Missing, Type.Missing); wordTable = bm.Tables[1]; wordTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Columns.PreferredWidthType = Microsoft.Office.Interop.Word.WdPreferredWidthType.wdPreferredWidthPercent; wordTable.Columns[1].PreferredWidth = 50f; wordTable.Columns[2].PreferredWidth = 25f; wordTable.Columns[3].PreferredWidth = 25f; wordTable.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowLeft; wordTable.Rows[1].Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter; wordTable.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; wordTable.Range.Select(); wordTable.Cell(1, 1).Range.Text = "Вид нарушителя"; wordTable.Cell(1, 2).Range.Text = "Тип нарушителя"; wordTable.Cell(1, 3).Range.Text = "Потенциал нарушителя"; int row = 2; foreach (System.Windows.Forms.CheckBox i in mf.clbIntruderTypes.Controls) { if (i.CheckState == CheckState.Checked) { wordTable.Cell(row, 1).Range.Text = i.Text; wordTable.Cell(row, 2).Range.Text = ((StageIntruder)mf.stages["tnIntruder"]).getIntruderType(i.Text); wordTable.Cell(row++, 3).Range.Text = ((StageIntruder)mf.stages["tnIntruder"]).getIntruderPotencial(i.Text); } } #endregion #region Фильтрация по нарушителю (1) bm = oDoc.Bookmarks["NSD_Filter_1_Intruder"].Range; mf.clbThreatFilter.SetItemChecked(0, true); mf.clbThreatFilter.SetItemChecked(1, false); mf.clbThreatFilter.SetItemChecked(2, false); mf.clbThreatFilter.SetItemChecked(3, false); filterThreatList(); bm.Tables.Add(bm, listFilteredThreats.Count + 1, 3, Type.Missing, Type.Missing); wordTable = bm.Tables[1]; wordTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Columns.PreferredWidthType = Microsoft.Office.Interop.Word.WdPreferredWidthType.wdPreferredWidthPercent; wordTable.Columns[1].PreferredWidth = 7.7f; wordTable.Columns[2].PreferredWidth = 55f; wordTable.Columns[3].PreferredWidth = 37.3f; wordTable.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowLeft; wordTable.Rows[1].Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter; wordTable.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; wordTable.Range.Select(); wordTable.Cell(1, 1).Range.Text = "№ п/п"; wordTable.Cell(1, 2).Range.Text = "Идентификатор и название УБИ"; wordTable.Cell(1, 3).Range.Text = "Источник УБИ (нарушитель)"; row = 2; foreach (Threat t in listFilteredThreats) { wordTable.Cell(row, 1).Range.Text = (row - 1).ToString(); wordTable.Cell(row, 2).Range.Text = "УБИ." + t.ThreatNumber + " " + t.Name.ToString(); wordTable.Cell(row++, 3).Range.Text = t.stringSources; } #endregion #region Фильтрация по уязвимостям (2) bm = oDoc.Bookmarks["NSD_Filter_2_Vuls"].Range; mf.clbThreatFilter.SetItemChecked(0, true); mf.clbThreatFilter.SetItemChecked(1, false); mf.clbThreatFilter.SetItemChecked(2, true); mf.clbThreatFilter.SetItemChecked(3, false); filterThreatList(); bm.Tables.Add(bm, listFilteredThreats.Count + 1, 3, Type.Missing, Type.Missing); wordTable = bm.Tables[1]; wordTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Columns.PreferredWidthType = Microsoft.Office.Interop.Word.WdPreferredWidthType.wdPreferredWidthPercent; wordTable.Columns[1].PreferredWidth = 8f; wordTable.Columns[2].PreferredWidth = 42f; wordTable.Columns[3].PreferredWidth = 50f; wordTable.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowLeft; wordTable.Rows[1].Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter; wordTable.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; wordTable.Range.Select(); wordTable.Cell(1, 1).Range.Text = "№ п/п"; wordTable.Cell(1, 2).Range.Text = "Идентификатор и название УБИ"; wordTable.Cell(1, 3).Range.Text = "Уязвимости, способствующие реализации УБИ"; row = 2; foreach (Threat t in listFilteredThreats) { wordTable.Cell(row, 1).Range.Text = (row - 1).ToString(); wordTable.Cell(row, 2).Range.Text = "УБИ." + t.ThreatNumber + " " + t.Name.ToString(); wordTable.Cell(row++, 3).Range.Text = t.stringVuls; } #endregion #region Фильтрация по способам реализации (3) bm = oDoc.Bookmarks["NSD_Filter_3_Implement"].Range; mf.clbThreatFilter.SetItemChecked(0, true); mf.clbThreatFilter.SetItemChecked(1, true); mf.clbThreatFilter.SetItemChecked(2, true); mf.clbThreatFilter.SetItemChecked(3, false); filterThreatList(); bm.Tables.Add(bm, listFilteredThreats.Count + 1, 3, Type.Missing, Type.Missing); wordTable = bm.Tables[1]; wordTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Columns.PreferredWidthType = Microsoft.Office.Interop.Word.WdPreferredWidthType.wdPreferredWidthPercent; wordTable.Columns[1].PreferredWidth = 8f; wordTable.Columns[2].PreferredWidth = 27f; wordTable.Columns[3].PreferredWidth = 65f; wordTable.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowLeft; wordTable.Rows[1].Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter; wordTable.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; wordTable.Range.Select(); wordTable.Cell(1, 1).Range.Text = "№ п/п"; wordTable.Cell(1, 2).Range.Text = "Идентификатор и название УБИ"; wordTable.Cell(1, 3).Range.Text = "Возможные способы реализации УБИ"; row = 2; foreach (Threat t in listFilteredThreats) { wordTable.Cell(row, 1).Range.Text = (row - 1).ToString(); wordTable.Cell(row, 2).Range.Text = "УБИ." + t.ThreatNumber + " " + t.Name.ToString(); wordTable.Cell(row++, 3).Range.Text = t.stringWays; } #endregion #region Фильтрация по СФХ (4) bm = oDoc.Bookmarks["NSD_Filter_4_SFH"].Range; mf.clbThreatFilter.SetItemChecked(0, true); mf.clbThreatFilter.SetItemChecked(1, true); mf.clbThreatFilter.SetItemChecked(2, true); mf.clbThreatFilter.SetItemChecked(3, true); filterThreatList(); bm.Tables.Add(bm, listFilteredThreats.Count + 1, 3, Type.Missing, Type.Missing); wordTable = bm.Tables[1]; wordTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Columns.PreferredWidthType = Microsoft.Office.Interop.Word.WdPreferredWidthType.wdPreferredWidthPercent; wordTable.Columns[1].PreferredWidth = 8f; wordTable.Columns[2].PreferredWidth = 27f; wordTable.Columns[3].PreferredWidth = 65f; wordTable.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowLeft; wordTable.Rows[1].Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter; wordTable.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; wordTable.Range.Select(); wordTable.Cell(1, 1).Range.Text = "№ п/п"; wordTable.Cell(1, 2).Range.Text = "Идентификатор и название УБИ"; wordTable.Cell(1, 3).Range.Text = "Описание УБИ"; row = 2; foreach (Threat t in listFilteredThreats) { wordTable.Cell(row, 1).Range.Text = (row - 1).ToString(); wordTable.Cell(row, 2).Range.Text = "УБИ." + t.ThreatNumber + " " + t.Name.ToString(); wordTable.Cell(row++, 3).Range.Text = t.Description; } #endregion #region Уровень проектной защищенности (слово) bm = oDoc.Bookmarks["Project_Security"].Range; string PSLtext = ""; switch (IS.ProjectSecutiryLvl) { case 0: PSLtext = "низкий"; break; case 1: PSLtext = "средний"; break; case 2: PSLtext = "высокий"; break; } bm.Text = PSLtext; #endregion #region Возможность реализации УБИ bm = oDoc.Bookmarks["Feasibility"].Range; bm.Tables.Add(bm, mf.dgvActualThreatsNSD.Rows.Count + 1, 5, Type.Missing, Type.Missing); wordTable = bm.Tables[1]; wordTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Columns.PreferredWidthType = Microsoft.Office.Interop.Word.WdPreferredWidthType.wdPreferredWidthPercent; wordTable.Columns[1].PreferredWidth = 8f; wordTable.Columns[2].PreferredWidth = 29.8f; wordTable.Columns[3].PreferredWidth = 24.6f; wordTable.Columns[4].PreferredWidth = 20.2f; wordTable.Columns[5].PreferredWidth = 17.4f; wordTable.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowLeft; wordTable.Rows[1].Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter; wordTable.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; wordTable.Range.Select(); wordTable.Cell(1, 1).Range.Text = "№ п/п"; wordTable.Cell(1, 2).Range.Text = "Идентификатор и название УБИ"; wordTable.Cell(1, 3).Range.Text = "Источник угрозы (нарушитель)"; wordTable.Cell(1, 4).Range.Text = "Уровень проектной защищенности ИС"; wordTable.Cell(1, 5).Range.Text = "Возможность реализации угрозы"; wordTable.Cell(2, 4).Range.Text = PSLtext; row = 2; foreach (Threat t in listFilteredThreats) { wordTable.Cell(row, 1).Range.Text = (row - 1).ToString(); wordTable.Cell(row, 2).Range.Text = "УБИ." + t.ThreatNumber + " " + t.Name.ToString(); wordTable.Cell(row++, 3).Range.Text = t.stringSources; } row = 2; foreach (DataGridViewRow dgvrow in mf.dgvActualThreatsNSD.Rows) { wordTable.Cell(row++, 5).Range.Text = dgvrow.Cells[2].Value.ToString(); } wordTable.Rows[2].Cells[4].Merge(wordTable.Rows[mf.dgvActualThreatsNSD.Rows.Count + 1].Cells[4]); #endregion #region Степени ущерба bm = oDoc.Bookmarks["Damage_Degree"].Range; //bm.Tables.Add(bm, mf.dgvActualThreatsNSD.Rows.Count + 2, 3 + IS.listOfInfoTypes.Count, Type.Missing, Type.Missing); wordTable = bm.Tables[1]; //wordTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; //wordTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; //wordTable.Columns.PreferredWidthType = Microsoft.Office.Interop.Word.WdPreferredWidthType.wdPreferredWidthPercent; //wordTable.Columns[1].PreferredWidth = 7f; //wordTable.Columns[2].PreferredWidth = 33.1f; //wordTable.Columns[3].PreferredWidth = 45.1f; //wordTable.Columns[5].PreferredWidth = 13.8f; //wordTable.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowLeft; //wordTable.Rows[1].Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter; //wordTable.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; wordTable.Range.Select(); //wordTable.Cell(1, 1).Range.Text = "№ п/п"; //wordTable.Cell(1, 2).Range.Text = "Идентификатор и название УБИ"; //wordTable.Cell(1, 3).Range.Text = "Степень ущерба в результате наруше-ния каждого свойства безопасности относительно всех видов ущерба"; //wordTable.Cell(1, 3 + IS.listOfInfoTypes.Count).Range.Text = "Итоговая степень ущерба"; //wordTable.Rows[1].Cells[1].Merge(wordTable.Rows[2].Cells[1]); //wordTable.Rows[1].Cells[2].Merge(wordTable.Rows[2].Cells[2]); //wordTable.Rows[1].Cells[3 + IS.listOfInfoTypes.Count].Merge(wordTable.Rows[2].Cells[3 + IS.listOfInfoTypes.Count]); //if (IS.listOfInfoTypes.Count >= 2) // wordTable.Rows[1].Cells[3].Merge(wordTable.Rows[1].Cells[2 + IS.listOfInfoTypes.Count]); int infoN = 0; wordTable.Cell(2, 3).Split(1, IS.listOfInfoTypes.Count); foreach (InfoType info in IS.listOfInfoTypes) { wordTable.Cell(2, 3 + infoN).Range.Text = info.TypeName; infoN++; } row = 3; foreach (DataGridViewRow dgvrow in mf.dgvActualThreatsNSD.Rows) { wordTable.Rows.Add(); wordTable.Cell(row, 1).Range.Text = (row - 1).ToString(); wordTable.Cell(row, 2).Range.Text = "УБИ." + dgvrow.Cells[0].Value.ToString() + " " + dgvrow.Cells[1].Value.ToString(); infoN = 0; foreach (InfoType info in IS.listOfInfoTypes) { switch (calcMaxDDInfo(Convert.ToInt32(dgvrow.Cells[0].Value.ToString()), info)) { case 3: wordTable.Cell(row, 3 + infoN).Range.Text = "Высокая"; break; case 2: wordTable.Cell(row, 3 + infoN).Range.Text = "Средняя"; break; case 1: wordTable.Cell(row, 3 + infoN).Range.Text = "Низкая"; break; case 0: wordTable.Cell(row, 3 + infoN).Range.Text = "Не определена"; break; } infoN++; } wordTable.Cell(row++, 3 + IS.listOfInfoTypes.Count).Range.Text = dgvrow.Cells[3].Value.ToString(); } //damageDegreeInput[currentThreatNumber][itype, iCIA, iDT] = 3; #endregion #region Актуальные УБИ НСД bm = oDoc.Bookmarks["ACT_NSD"].Range; bm.Tables.Add(bm, mf.dgvActualThreatsNSD.Rows.Count + 1, 5, Type.Missing, Type.Missing); wordTable = bm.Tables[1]; wordTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; wordTable.Columns.PreferredWidthType = Microsoft.Office.Interop.Word.WdPreferredWidthType.wdPreferredWidthPercent; wordTable.Columns[1].PreferredWidth = 7f; wordTable.Columns[2].PreferredWidth = 35.3f; wordTable.Columns[3].PreferredWidth = 18.2f; wordTable.Columns[4].PreferredWidth = 21.2f; wordTable.Columns[5].PreferredWidth = 18.1f; wordTable.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowLeft; wordTable.Rows[1].Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter; wordTable.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; wordTable.Range.Select(); wordTable.Cell(1, 1).Range.Text = "№ п/п"; wordTable.Cell(1, 2).Range.Text = "Идентификатор и название УБИ"; wordTable.Cell(1, 3).Range.Text = "Возможность реализации УБИ"; wordTable.Cell(1, 4).Range.Text = "Степень возможного ущерба в результате реализации УБИ"; wordTable.Cell(1, 5).Range.Text = "Актуальность"; row = 2; foreach (DataGridViewRow dgvrow in mf.dgvActualThreatsNSD.Rows) { wordTable.Cell(row, 1).Range.Text = (row - 1).ToString(); wordTable.Cell(row, 2).Range.Text = "УБИ." + dgvrow.Cells[0].Value.ToString() + " " + dgvrow.Cells[1].Value.ToString(); wordTable.Cell(row, 3).Range.Text = dgvrow.Cells[2].Value.ToString(); wordTable.Cell(row, 4).Range.Text = dgvrow.Cells[3].Value.ToString(); wordTable.Cell(row++, 5).Range.Text = dgvrow.Cells[4].Value.ToString(); } #endregion //bm.Text = "hello"; oDoc.Activate(); mf.FindAndReplace(oWord, "{Название ИС}", "ГИС \"" + IS.ISName + "\""); //oDoc.SaveAs(FileName: Environment.CurrentDirectory + "\\2.docx"); //oDoc.Close(); mf.wsm.Visible = false; oWord.Visible = true; }
/// <summary> /// 打开待打印WORD模板文件,以开始打印处理 /// </summary> /// <returns>打开成功则返回TRUE,否则返回FALSE</returns> public override bool Open() { object template = this.Template; object ReadOnly = false; object revert = true; object SavePath = this.SavePath; if (this.Available(this.Template)) { if (!ChkExtOfDocx()) return false; int TryCount = 0; while (true) { if (TryCopy(this.Template, this.SavePath)) { break; } else { Thread.Sleep(500); TryCount++; if (TryCount > _TRY_COUNT_) { return false; } } } //Monitor.Enter(template); //try { // File.Copy(this.Template, this.SavePath, true); //} //catch { // Thread.Sleep(200); // try // { // File.Copy(this.Template, this.SavePath, true); // } // catch { return false; } //} //Monitor.Exit(template); if (!File.Exists(this.SavePath)) return false; m_doc = m_WordApp.Documents.Open(ref SavePath, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref revert, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); m_doc.Activate(); //m_doc.ActiveWindow.Document.Activate(); if (m_doc.Revisions.Count > 0) { m_doc.ShowRevisions = true; m_doc.TrackRevisions = true; m_doc.Revisions.AcceptAll(); } m_arKeyPosition = new ArrayList[m_doc.Tables.Count]; for (int iCount = 0; iCount < m_doc.Tables.Count; iCount++) { ArrayList alkp = TraverTable(iCount + 1); m_arKeyPosition.SetValue(alkp, iCount); } return true; } return false; }
public bool ConvertToWord(LeaveEntity leave, UserEntity user, UserEntity checkLeader, UserEntity approvalLeader, OrganizeEntity organ, RoleEntity role, string printName) { object missing = System.Reflection.Missing.Value; //创建一个Word应用程序实例 Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application(); oWord.ActivePrinter = printName; //设置为不可见 oWord.Visible = false; //模板文件地址,这里假设在X盘根目录 object oTemplate = "E:\\Temp\\template.doc"; object filename = "E:\\Temp\\" + new Guid().ToString() + ".doc"; //以模板为基础生成文档 Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref missing, ref missing, ref missing); oDoc.Activate(); //当前文档置前 try { //声明书签数组 object[] oBookMark = new object[12]; //赋值书签名 oBookMark[0] = "F_CreateTime"; oBookMark[1] = "F_Account"; oBookMark[2] = "F_Department"; oBookMark[3] = "F_ApprovalLeader"; oBookMark[4] = "F_CheckLeader"; oBookMark[5] = "F_Group"; oBookMark[6] = "F_Position"; oBookMark[7] = "F_StartTime"; oBookMark[8] = "F_LeaveReason"; oBookMark[9] = "F_UserName"; oBookMark[10] = "F_BeginEndTime"; oBookMark[11] = "F_Name"; //赋值任意数据到书签的位置 oDoc.Bookmarks.get_Item(ref oBookMark[0]).Range.Text = leave.F_CreateTime.ToString(); oDoc.Bookmarks.get_Item(ref oBookMark[1]).Range.Text = user.F_Account; oDoc.Bookmarks.get_Item(ref oBookMark[2]).Range.Text = organ.F_FullName; oDoc.Bookmarks.get_Item(ref oBookMark[3]).Range.Text = approvalLeader.F_RealName; oDoc.Bookmarks.get_Item(ref oBookMark[4]).Range.Text = checkLeader.F_RealName; oDoc.Bookmarks.get_Item(ref oBookMark[5]).Range.Text = ""; oDoc.Bookmarks.get_Item(ref oBookMark[6]).Range.Text = role.F_FullName; oDoc.Bookmarks.get_Item(ref oBookMark[7]).Range.Text = user.F_CreatorTime.ToString(); oDoc.Bookmarks.get_Item(ref oBookMark[8]).Range.Text = leave.F_LeaveReason; oDoc.Bookmarks.get_Item(ref oBookMark[9]).Range.Text = user.F_RealName; oDoc.Bookmarks.get_Item(ref oBookMark[10]).Range.Text = leave.F_BeginTime.ToString() + "至" + leave.F_EndTime.ToString(); oDoc.Bookmarks.get_Item(ref oBookMark[11]).Range.Text = user.F_RealName; //oDoc.SaveAs(ref filename, ref missing, ref missing, ref missing, //ref missing, ref missing, ref missing, ref missing, ref missing, //ref missing, ref missing, ref missing, ref missing, ref missing, //ref missing, ref missing); // return filename.ToString(); //打印 oDoc.PrintOut(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); return(true); } catch (Exception ex) { return(false); } finally { object saveChange = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; if (oDoc != null) { oDoc.Close(ref saveChange, ref missing, ref missing); } if (oDoc != null) { oWord.Quit(ref missing, ref missing, ref missing); } } }
public static void CreateBallots(Tournament tournament, DataContext context, Guid roundId) { SqlHelper helper = new SqlHelper(tournament.Database); Round round = helper.GetRound(roundId).Result; string motion = round.Motion; List <Debate> debates = helper.GetDebates(roundId).Result; string directory = Path.Combine(Path.GetDirectoryName(tournament.Location), tournament.Name, string.Format("Round {0}", round.RoundNumber)); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } string ballotsDirectory = Path.Combine(directory, "ballots"); if (!Directory.Exists(ballotsDirectory)) { Directory.CreateDirectory(ballotsDirectory); } foreach (Debate debate in debates) { List <SpeakerDraw> speakerDraws = helper.GetSpeakerDrawsByDebate(debate.DebateId).Result; List <JudgeDraw> judgeDraws = helper.GetJudgeDrawsByDebate(debate.DebateId).Result; Venue venue = context.Venues.First(v => v.VenueId.Equals(debate.VenueId)); Word._Application wordApplication = new Word.Application() { Visible = false }; wordApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; object filename = Path.Combine(Path.GetDirectoryName(tournament.Location), tournament.Name, "lib", "ballot.docx"); Word._Document wordDocument = wordApplication.Documents.Open(ref filename); wordDocument.Activate(); Word.Range content = wordDocument.Range(); Dictionary <string, string> findReplaces = new Dictionary <string, string>(); findReplaces.Add("#t", tournament.Name); findReplaces.Add("#v", venue.Name); string chairJudge = judgeDraws.OrderBy(j => j.Number).Select(jd => context.Judges.First(j => j.JudgeId.Equals(jd.JudgeId))).First().Name; findReplaces.Add("#chair", chairJudge); findReplaces.Add("#j", string.Join(", ", judgeDraws.OrderBy(j => j.Number).Select(a => context.Judges.First(j => j.JudgeId.Equals(a.JudgeId)).Name))); findReplaces.Add("#r", round.RoundNumber.ToString()); findReplaces.Add("#m", motion); SpeakerDraw og = speakerDraws.First(sd => sd.Position.Equals(Position.OpeningGovernment)); Speaker ogSpeaker = context.Speakers.First(sd => og.SpeakerId.Equals(sd.SpeakerId)); findReplaces.Add("#og", context.Speakers.First(s => s.SpeakerId.Equals(og.SpeakerId)).Name); findReplaces.Add("#iog", context.Institutions.First(i => i.InstitutionId.Equals(ogSpeaker.InstitutionId)).Name); SpeakerDraw oo = speakerDraws.First(sd => sd.Position.Equals(Position.OpeningOpposition)); Speaker ooSpeaker = context.Speakers.First(sd => oo.SpeakerId.Equals(sd.SpeakerId)); findReplaces.Add("#oo", context.Speakers.First(s => s.SpeakerId.Equals(oo.SpeakerId)).Name); findReplaces.Add("#ioo", context.Institutions.First(i => i.InstitutionId.Equals(ooSpeaker.InstitutionId)).Name); SpeakerDraw sg = speakerDraws.First(sd => sd.Position.Equals(Position.SecondGovernment)); Speaker sgSpeaker = context.Speakers.First(sd => sg.SpeakerId.Equals(sg.SpeakerId)); findReplaces.Add("#sg", context.Speakers.First(s => s.SpeakerId.Equals(sg.SpeakerId)).Name); findReplaces.Add("#isg", context.Institutions.First(i => i.InstitutionId.Equals(sgSpeaker.InstitutionId)).Name); SpeakerDraw so = speakerDraws.First(sd => sd.Position.Equals(Position.SecondOpposition)); Speaker soSpeaker = context.Speakers.First(sd => so.SpeakerId.Equals(sd.SpeakerId)); findReplaces.Add("#so", context.Speakers.First(s => s.SpeakerId.Equals(so.SpeakerId)).Name); findReplaces.Add("#iso", context.Institutions.First(i => i.InstitutionId.Equals(soSpeaker.InstitutionId)).Name); SpeakerDraw cg = speakerDraws.First(sd => sd.Position.Equals(Position.ClosingGovernment)); Speaker cgSpeaker = context.Speakers.First(sd => cg.SpeakerId.Equals(sd.SpeakerId)); findReplaces.Add("#cg", context.Speakers.First(s => s.SpeakerId.Equals(cg.SpeakerId)).Name); findReplaces.Add("#icg", context.Institutions.First(i => i.InstitutionId.Equals(cgSpeaker.InstitutionId)).Name); SpeakerDraw co = speakerDraws.First(sd => sd.Position.Equals(Position.ClosingOpposition)); Speaker coSpeaker = context.Speakers.First(sd => co.SpeakerId.Equals(sd.SpeakerId)); findReplaces.Add("#co", context.Speakers.First(s => s.SpeakerId.Equals(co.SpeakerId)).Name); findReplaces.Add("#ico", context.Institutions.First(i => i.InstitutionId.Equals(coSpeaker.InstitutionId)).Name); foreach (KeyValuePair <string, string> keyValuePair in findReplaces) { content.Find.Execute(FindText: keyValuePair.Key, Replace: Word.WdReplace.wdReplaceAll, ReplaceWith: keyValuePair.Value); } object ballotFilename = Path.Combine(ballotsDirectory, string.Format("{0}.doc", venue.Name)); wordDocument.SaveAs(ref ballotFilename); object save = Word.WdSaveOptions.wdDoNotSaveChanges; wordDocument.Close(ref save); wordApplication.Quit(); } }