public object Tagify(DocX word, string model) { // Patterns string inlinePattern = this.ModelPattern.Replace("<model>", model); string blockPattern = this.PointerPattern.Replace("<model>", model); // Get inline templates List <string> inlineTemplates = word.FindUniqueByPattern(inlinePattern, this.REGEX); // Get block templates List <Novacode.Table> blockTemplates; try { Novacode.Table blockTemplatesWrapper = word .Tables .Where(e => e.Paragraphs[0].Text.Contains(blockPattern)) .ToList()[0]; blockTemplates = this.CascadeBlock(blockTemplatesWrapper, new List <Novacode.Table>()); } catch (Exception e) { blockTemplates = new List <Novacode.Table>(); } return(new { name = model, inlines = inlineTemplates, blocks = blockTemplates }); }
/// <summary> /// Remplacer le texte qui se trouve entre <> dans un document. /// </summary> /// <param name="document"></param> /// <param name="valeur"></param> public static void ReplaceText(DocX document, IDictionary <string, string> valeur) { // Vérifiez si certains des modèles de remplacement sont utilisés dans le document chargé. if (document.FindUniqueByPattern(@"<[\w \=]{4,}>", RegexOptions.IgnoreCase).Count > 0) { _replacePatterns = (Dictionary <string, string>)valeur; // Effectue le remplacement de tous les tag trouvé. document.ReplaceText("<(.*?)>", DocumentWord.ReplaceFunc, false, RegexOptions.IgnoreCase); } }
public Boolean CreateDocxMassive(string sNameFileDocx, string sNameFileXls, out string errTags) { Boolean bResult = false; try { ResourceFileManager resourceFileManager = ResourceFileManager.Instance; errTags = ""; resourceFileManager.SetResources(); string sPathWork = resourceFileManager._resourceManager.GetString("ExcelWorkFolder"); ExcelDocumentReader excelDocumentReader = new ExcelDocumentReader(sNameFileXls); var columnNames = excelDocumentReader.GetColumnNames(); //var getData = excelDocumentReader.getData<LinqToExcel.Row>(); // Ciclo i singoli record estrapolati dal file excel Int16 iIndiceFile = 1; foreach (var a in excelDocumentReader.getData) { //Apro il FileStyleUriParser template DocX da valorizzare using (DocX document = DocX.Load(@sPathWork + sNameFileDocx)) { // Ciclo tra i nomi delle colonne foreach (var columnName in columnNames) { // sostituisco il valore dei nomi colonne formattandole come TAG che sia suppone sia presente nel template DOCX document.ReplaceText("«" + columnName + "»", a[columnName].ToString()); } // Verifico che tutti i TAG presenti all'interno del file docx siano stati valorizzati var lineBreaks = document.FindUniqueByPattern("«*\\b[^»]*»", System.Text.RegularExpressions.RegexOptions.None); // Qualora siano presenti restituisco i tag non ripristinati come segnalazione di una anomalia if (lineBreaks.Count > 0) { foreach (var tagErr in lineBreaks) { errTags += tagErr + " "; } break; } else { document.SaveAs(excelDocumentReader.sTransactionPath + iIndiceFile + ".docx"); } } iIndiceFile += 1; } bResult = true; } catch (Exception ex) { throw ex; } finally { } return(bResult); }
static void Main(string[] args) { DocX document = DocX.Load("document.docx"); List <string> jetons = document.FindUniqueByPattern("{{(.*?)}}", RegexOptions.IgnoreCase); for (int j = 0; j < jetons.Count; j++) { Console.WriteLine("Le jeton " + jetons[j] + " a été trouvé"); } for (int i = 0; i < valeurs.Count; i++) { document.ReplaceText("{{(.*?)}}", ChercheValeur, false, RegexOptions.IgnoreCase, null, new Formatting()); } document.SaveAs("documentGénéré.docx"); }
public void HyperLinkReplaceSet(DocX document, DataGridView ReplaceLinkGridView) { foreach (DataGridViewRow row in ReplaceLinkGridView.Rows) { string source = row.Cells[0].Value == null ? "" : row.Cells[0].Value.ToString(); Uri target = row.Cells[1].Value == null ? null : GetUri(row.Cells[1].Value.ToString().Trim()); if (string.IsNullOrWhiteSpace(source) || target == null) { continue; } if (document.FindUniqueByPattern(@source, RegexOptions.None).Count > 0) { var linkBlock = document.AddHyperlink(@source, target); document.ReplaceTextWithObject(@source, linkBlock); } } }
public void TextReplaceSet(DocX document, Dictionary <string, string> lists) { if (lists.Count > 0) { string source = "("; foreach (string key in lists.Keys) { source += key + "|"; } source = source.Substring(0, source.Length - 1); source += ")"; this._replaceTextPatterns = lists; if (document.FindUniqueByPattern(@source, RegexOptions.None).Count > 0) { document.ReplaceText(source, ReplaceTextHandler); } } }
public static void ReplaceText(ITemplate template, DocX document, IDictionary <string, string> values) { List <string> fields = document.FindUniqueByPattern(@"\#{var\.([^}]+)}", System.Text.RegularExpressions.RegexOptions.Singleline); if (fields != null && fields.Any()) { foreach (string field in fields) { string key = field.Substring(6, field.Length - 7); if (values.ContainsKey(key)) { document.ReplaceText(field, getStringValue(template, key, values[key])); } else { document.ReplaceText(field, getStringValue(template, key, "")); } } } }
private void ReplaceVar(DocX document, Dictionary <string, string> dicVarMap) { if (dicVarMap.Count == 0) { return; } string regEx = "\\$\\{[^\\$\\{\\}]*\\}"; List <string> parms = document.FindUniqueByPattern(regEx, RegexOptions.IgnoreCase); foreach (var v in parms) { if (dicVarMap.ContainsKey(v)) { document.ReplaceText(v, dicVarMap[v]); } else { document.ReplaceText(v, " "); } } }
/// <summary> /// Load a document and replace texts following a replace pattern. /// </summary> public static void ReplaceText() { Console.WriteLine("\tReplaceText()"); // Load a document. using (DocX document = DocX.Load(DocumentSample.DocumentSampleResourcesDirectory + @"ReplaceText.docx")) { // Check if all the replace patterns are used in the loaded document. if (document.FindUniqueByPattern(@"<[\w \=]{4,}>", RegexOptions.IgnoreCase).Count == _replacePatterns.Count) { // Do the replacement for (int i = 0; i < _replacePatterns.Count; ++i) { document.ReplaceText("<(.*?)>", DocumentSample.ReplaceFunc, false, RegexOptions.IgnoreCase, null, new Formatting()); } // Save this document to disk. document.SaveAs(DocumentSample.DocumentSampleOutputDirectory + @"ReplacedText.docx"); Console.WriteLine("\tCreated: ReplacedText.docx\n"); } } }
public string CreateDocx(NameValueCollection collectionForReplace, string sPathTemplateDocx, LOLIB oLogger, string LogId, out string errTags) { string sPath = ""; try { errTags = ""; string cfSelected = string.Empty; using (DocX document = DocX.Load(sPathTemplateDocx)) { for (int i = 0; i < collectionForReplace.Count; i++) { oLogger.WriteOnLog(LogId, "REPLACE Nome campo: " + "«" + collectionForReplace.GetKey(i) + "»" + " -> " + collectionForReplace.GetValues(i)[0], 3); document.ReplaceText("«" + collectionForReplace.GetKey(i) + "»", collectionForReplace.GetValues(i)[0]); } // Verifico che tutti i TAG presenti all'interno del file docx siano stati valorizzati var lineBreaks = document.FindUniqueByPattern("«*\\b[^»]*»", System.Text.RegularExpressions.RegexOptions.None); // Qualora siano presenti restituisco i tag non ripristinati come segnalazione di una anomalia if (lineBreaks.Count > 0) { foreach (var tagErr in lineBreaks) { errTags += tagErr + " "; } throw new ArgumentException("Sono stati trovati i seguenti tag non sostituiti: " + errTags); //break; } else { sPath = sPathTemplateDocx.ToLower().Replace(".docx", "_Completed.docx"); document.SaveAs(sPath); } } } catch (Exception ex) { throw new ArgumentException(ex.Message); } finally { } return(sPath); }
private void GetAndSaveTmpVars() { long tmpId = this.InfoTmp.Tmp_Id; List <string> parms = null; DocBuilder docBuilder = new DocBuilder(this.InfoTmp); using (DocX document = DocX.Load(docBuilder.ToStream())) { string regEx = "\\$\\{[^\\$\\{\\}]*\\}"; parms = document.FindUniqueByPattern(regEx, RegexOptions.IgnoreCase); //string filename = System.IO.Path.Combine("Report", "tmp.docx"); //Doc.DocBuilder1.SetPageMargin(document); //document.SaveAs(filename); } if (!manager.SaveTmpVars(tmpId, parms)) { MessageBox.Show("模板提取变量失败"); } }
/// <summary> /// @description: hàm kết xuất excel cho sản phẩm /// @author: duynn /// @since: 23/03/2018 /// </summary> /// <param name="objectToExport"></param> /// <returns></returns> public ExportWordResult Export(T objectToExport) { ExportWordResult exportResult = new ExportWordResult(); //kiểm tra file biểu mẫu tồn tại if (string.IsNullOrEmpty(templateFilePath) || File.Exists(templateFilePath) == false) { exportResult.exportResultMessage = "File biểu mẫu không tồn tại!"; return(exportResult); } //kiểm tra thư mục xuất tồn tại if (string.IsNullOrEmpty(outputFolderPath) || Directory.Exists(outputFolderPath) == false) { exportResult.exportResultMessage = "Thư mục kết xuất không tồn tại!"; return(exportResult); } //kiểm tra thư mục tạm tồn tại if (string.IsNullOrEmpty(tempFolderPath) || Directory.Exists(tempFolderPath) == false) { exportResult.exportResultMessage = "Thư mục lưu trữ không tồn tại!"; return(exportResult); } if (string.IsNullOrEmpty(fileName)) { exportResult.exportResultMessage = "Tên file không được để trống"; return(exportResult); } //lấy tên file biểu mẫu string templateFileName = Path.GetFileName(templateFilePath); //tạo tên cho file tạm (phòng khi bị trùng) string tempFileName = SetNewFileName(templateFileName); //tạo đường dẫn cho file tạm string tempFilePath = Path.Combine(tempFolderPath, tempFileName); FileInfo fileTemplate = new FileInfo(templateFilePath); fileTemplate.CopyTo(tempFilePath); app = new MSWordApp(); doc = app.Documents.Open(templateFilePath); try { app.Visible = false; doc.Activate(); DocX docX = DocX.Load(tempFilePath); List <string> wordsToReplace = docX.FindUniqueByPattern(@"\[\[\w*\]\]", RegexOptions.IgnoreCase); if (wordsToReplace != null && wordsToReplace.Count() > 0) { Type objectType = typeof(T); foreach (string wordToReplace in wordsToReplace) { object replaceValue = string.Empty; string propertyName = wordToReplace.Replace("[[", string.Empty).Replace("]]", string.Empty).Trim(); if (string.IsNullOrEmpty(propertyName) == false) { PropertyInfo property = objectType.GetProperty(propertyName); if (property != null) { replaceValue = property.GetValue(objectToExport); } } Replace(app, wordToReplace, replaceValue); } } //save file string outputFilePath = Path.Combine(outputFolderPath, fileName); if (File.Exists(outputFilePath)) { fileName = SetNewFileName(fileName); outputFilePath = Path.Combine(outputFolderPath, fileName); } app.ActiveDocument.SaveAs2(outputFilePath); exportResult.exportSuccess = true; exportResult.exportResultUrl = outputFilePath; exportResult.exportResultFileName = fileName; return(exportResult); } catch (Exception ex) { exportResult.exportResultMessage = ex.Message; return(exportResult); } finally { if (doc != null) { doc.Close(); } app.Quit(); } }
public static DocX CreateDocA(DocX template, ECEViewModel model, string source, bool cprvalue) { bool addcor = false; string Fadcorr = ""; bool special = false; string Fsnum = "[NUMBER]"; string sym = getSym(model); if (!String.IsNullOrEmpty(model.Prep)) { sym = sym.Replace("#", model.Prep.ToString()); } if (cprvalue == true) { sym = sym + "/CRP." + model.cprnum.ToString(); } if (!String.IsNullOrEmpty(model.Add) && model.cAdd == true && model.cCor == false) { sym = sym + "/Add." + model.Add.ToString(); Fadcorr = "Addendum"; addcor = true; } if (!String.IsNullOrEmpty(model.Cor) && model.cCor == true && model.cAdd == false) { sym = sym + "/Corr." + model.Cor.ToString(); Fadcorr = "Corrigendum"; addcor = true; } if (!String.IsNullOrEmpty(model.Cor) && !String.IsNullOrEmpty(model.Add) && model.cCor == true && model.cAdd == true) { sym = sym + "/Add." + model.Add.ToString() + "/Corr." + model.Cor.ToString(); Fadcorr = "Addendum Corrigendum"; addcor = true; } if (String.IsNullOrEmpty(model.Cor) && String.IsNullOrEmpty(model.Add)) { addcor = false; } if (String.IsNullOrEmpty(model.CaseYear)) { sym = sym.Replace("&", DateTime.Now.Year.ToString()); } if (!String.IsNullOrEmpty(model.CaseYear)) { sym = sym.Replace("&", model.CaseYear.ToString()); } model.tsym = sym; string[] SymStr = sym.Split('/'); string[] sym1 = SymStr.Skip(1).ToArray(); string Fsym = String.Join("/", sym1); if (Fsym.Contains("/S/")) { special = true; Fsnum = "special"; } //Create Date for Header string Fdate = model.date.ToString(); string[] d = Fdate.Split(' '); Fdate = d[0]; Fdate = formatdate(Fdate, model); //Create Distribution for Header string Fdist = getDist(model); //Create Virsions for Header string Fvirs = ""; //if (model.version1 != null) //{ // int deleteStart = 0; // int deleteEnd = 0; // //Get the array of the paragraphs containing the start and end catches // for (int i = 0; i < template.Paragraphs.Count; i++) // { // if (template.Paragraphs[i].Text.Contains("Original")) // deleteStart = i; // if (template.Paragraphs[i].Text.Contains("olang")) // deleteEnd = i; // } // if (deleteStart > 0 && deleteEnd > 0) // { // //delete from the paraIndex as the arrays will shift when a paragraph is deleted // int paraIndex = deleteStart; // for (int i = deleteStart; i <= deleteEnd; i++) // { // template.RemoveParagraphAt(paraIndex); // } // } //} //Fvirs = getVerisons(model); string Folang = ""; Folang = Olanguage(model.lang_ID); string Fatitle = "[Title]"; if (!String.IsNullOrEmpty(model.AgendaItem)) { Fatitle = model.AgendaItem.ToString(); } string Fsdate = "[Start-End Dates ]"; if (model.Sdate != null & model.Edate != null) { string sdate = model.Sdate.ToString(); string[] sd = sdate.Split(' '); sdate = sd[0]; sdate = formatdate(sdate, model); string edate = model.Edate.ToString(); string[] ed = edate.Split(' '); edate = ed[0]; edate = formatdate(edate, model); Fsdate = SessionDate(sdate, edate, model); } string Fldate = "[Start Date]"; if (model.Sdate != null & model.Edate != null) { string ldate = model.Sdate.ToString(); string[] ld = ldate.Split(' '); ldate = ld[0]; string dldate = System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(DateTime.Parse(ldate).DayOfWeek); ldate = formatdate(ldate, model); //Regex rx = new Regex(@"^\d+\p{Zs}", RegexOptions.Compiled); //ldate = rx.Replace(ldate, dldate+" "); ldate = dldate + " " + ldate; Fldate = ldate; } string Fanum = "[NUMBER]"; if (!String.IsNullOrEmpty(model.AgendaNum)) { Fanum = model.AgendaNum.ToString(); } if (special == false) { if (!String.IsNullOrEmpty(model.SNum)) { Fsnum = Sessionnum(model); } } if (model.qrcode == true) { string lang = language(model.lang_ID); lang = lang.Substring(0, 1); string url = "http://undocs.org/m2/QRCode.ashx?DS=" + Fsym + "&Size=2&Lang=" + lang; using (var client = new WebClient()) { //var content = client.DownloadData("https://api.qrserver.com/v1/create-qr-code/?size=66x66&data=http://undocs.org/fr/A/HRC/70"); //var content = client.DownloadData("http://undocs.org/m2/QRCode.ashx?DS=A/HRC/70&Size=2&Lang=F"); var content = client.DownloadData(url); using (var str = new MemoryStream(content)) { if (lang == "A") { Image image = template.AddImage(str); NVPicture p = image.CreatePicture(); NVFooter f = template.Footers.first; NVTable t = f.Tables[0]; //t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(pR); t.Rows[0].Cells[0].Paragraphs.First().AppendPicture(p); } else { NVImage image = template.AddImage(str); NVPicture p = image.CreatePicture(); NVFooter f = template.Footers.first; NVTable t = f.Tables[0]; //t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(pR); t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(p); } } } } string Fcategory = ""; Fcategory = getCat(model.Cat); string FSubcategory = ""; if (model.SCat != "Not Applicable" || model.SCat != "Special Session") { FSubcategory = model.SCat.ToString(); } if (model.SCat == "Not Applicable" || model.SCat == "Special Session") { int deleteStart = 0; int deleteEnd = 0; //Get the array of the paragraphs containing the start and end catches for (int i = 0; i < template.Paragraphs.Count; i++) { if (template.Paragraphs[i].Text.Contains("subcategory")) { deleteStart = i; } if (template.Paragraphs[i].Text.Contains("subcategory")) { deleteEnd = i; } } if (deleteStart > 0 && deleteEnd > 0) { //delete from the paraIndex as the arrays will shift when a paragraph is deleted int paraIndex = deleteStart; for (int i = deleteStart; i <= deleteEnd; i++) { template.RemoveParagraphAt(paraIndex); } } } if (addcor == false) { int deleteStart = 0; int deleteEnd = 0; //Get the array of the paragraphs containing the start and end catches for (int i = 0; i < template.Paragraphs.Count; i++) { if (template.Paragraphs[i].Text.Contains("adcorr")) { deleteStart = i; } if (template.Paragraphs[i].Text.Contains("adcorr")) { deleteEnd = i; } } if (deleteStart > 0 && deleteEnd > 0) { //delete from the paraIndex as the arrays will shift when a paragraph is deleted int paraIndex = deleteStart; for (int i = deleteStart; i <= deleteEnd; i++) { template.RemoveParagraphAt(paraIndex); } } } string Fsplace = "[Session City]"; if (!String.IsNullOrEmpty(model.splace)) { Fsplace = model.splace.ToString(); } string Floca = "[Session Location]"; if (!String.IsNullOrEmpty(model.loca)) { Floca = model.loca.ToString() + ", " + Fsplace; } DateTime x = DateTime.Now; string[] info1 = info(model); template.AddCustomProperty(new CustomProperty("sym1", Fsym)); template.AddCustomProperty(new CustomProperty("symh", sym)); template.AddCustomProperty(new CustomProperty("dist", Fdist)); template.AddCustomProperty(new CustomProperty("date", Fdate)); template.AddCustomProperty(new CustomProperty("sdate", Fsdate)); template.AddCustomProperty(new CustomProperty("virs", Fvirs)); template.AddCustomProperty(new CustomProperty("snum", Fsnum)); template.AddCustomProperty(new CustomProperty("anum", Fanum)); template.AddCustomProperty(new CustomProperty("adcorr", Fadcorr)); template.AddCustomProperty(new CustomProperty("gdoc", "")); template.AddCustomProperty(new CustomProperty("gdocf", "")); template.AddCustomProperty(new CustomProperty("tlang", "")); template.AddCustomProperty(new CustomProperty("atitle", Fatitle)); template.AddCustomProperty(new CustomProperty("ldate", Fldate)); template.AddCustomProperty(new CustomProperty("loca", Floca)); template.AddCustomProperty(new CustomProperty("categ", Fcategory)); template.AddCustomProperty(new CustomProperty("subcategory", FSubcategory)); template.AddCustomProperty(new CustomProperty("splace", Fsplace)); template.AddCustomProperty(new CustomProperty("olang", Folang)); template.AddCustomProperty(new CustomProperty("Date-Generated", x)); template.AddCustomProperty(new CustomProperty("Org", "ECE")); template.AddCustomProperty(new CustomProperty("Entity", info1[0])); template.AddCustomProperty(new CustomProperty("doctype", info1[1])); template.AddCustomProperty(new CustomProperty("category", info1[2])); template.AddCustomProperty(new CustomProperty("bar", "")); for (int i = 0; i < template.Paragraphs.Count; i++) { if (template.Paragraphs[i].Text.Contains(Fsnum)) { string Fsnum1 = char.ToUpper(Fsnum[0]) + Fsnum.Substring(1); template.Paragraphs[i].ReplaceText(Fsnum, Fsnum1); break; } } if (addcor == true && cprvalue == false) { int deleteStart = 0; int deleteEnd = 0; //Get the array of the paragraphs containing the start and end catches for (int i = 0; i < template.Paragraphs.Count; i++) { if (template.Paragraphs[i].Text.Contains("*")) { deleteStart = i; } if (template.Paragraphs[i].Text.Contains(Fadcorr)) { deleteEnd = i; } } if (deleteStart > 0 && deleteEnd > 0) { //delete from the paraIndex as the arrays will shift when a paragraph is deleted int paraIndex = deleteEnd - deleteStart; paraIndex = deleteStart + paraIndex - 1; template.RemoveParagraphAt(paraIndex); } //List <string> replace = template.FindUniqueByPattern("*", RegexOptions.None); //foreach (string s in replace) //{ // if (!s.Equals("")) template.ReplaceText((s, ""); //} template.ReplaceText("*", ""); List <string> repl = template.FindUniqueByPattern(",\\s", RegexOptions.None); foreach (string rep in repl) { if (!String.IsNullOrEmpty(rep)) { template.ReplaceText(rep, ""); } } //bool flag = false; //List<List<string>> list1 = new List<List<string>>(); //List<string> list2 = new List<string>(); //foreach (Novacode.Paragraph item in template.Paragraphs) //{ // //use this if you need whole text of a paragraph // string paraText = item.Text; // var result = paraText.Split(' '); // int count = 0; // list2 = new List<string>(); // //use this if you need word by word // foreach (var data in result) // { // string word = data.ToString(); // if (word.Contains(Fsnum)) flag = true; // if (word.Contains("session")) // { // flag = false; // // list2.Add(word); // } // if (flag) // list2.Add(word); // count++; // } // // list2.RemoveAt(0); // list1.Add(list2); //} //// list1[0].Replace(list1[0], "*"); //for (int i = 0; i < list1.Count(); i++) //{ // string temp = ""; // for (int y = 0; y < list1[i].Count(); y++) // { // if (y == 0) // { // temp = list1[i][y]; // continue; // } // temp += " " + list1[i][y]; // // temp = temp.Remove(temp.IndexOf(',')-1, temp.Length); // } // int ind = temp.IndexOf("*"); // // temp = temp.Substring(ind, temp.Length - ind); // if (!temp.Equals("")) template.ReplaceText("Done", ""); //} } //using (WordprocessingDocument // document = WordprocessingDocument.Open(source, true)) //{ // var bookMarks = FindBookmarks(document.MainDocumentPart.Document); //} // Return the template now that it has been modified to hold all of our custom data. return(template); }
public void Parse(Stream input, Object data, ParseOptions options = null) { if (options == null) { options = new ParseOptions(); } using (DocX document = DocX.Load(input)) { //do loop replace first to avoid variable confusion //get a list of all loop variables var loopsToReplace = document.FindUniqueByPattern(options.LoopVariable.Regex, System.Text.RegularExpressions.RegexOptions.Multiline); foreach (var loop in loopsToReplace) { var loopListName = loop.Replace(options.LoopVariable.Start, string.Empty).Replace(options.LoopVariable.End, string.Empty); var loopData = GetPropValue(data, loopListName) as IEnumerable <Object>; if (loopData != null) { var table = document.Tables.Where(z => z.Rows.Any(r => r.Cells.Any(c => c.Xml.Value.Contains(loop)))).FirstOrDefault(); if (table != null) { var row = table.Rows.FirstOrDefault(r => r.Cells.Any(c => c.Xml.Value.Contains(loop))); var index = table.Rows.FindIndex((r => r.Cells.Any(c => c.Xml.Value.Contains(loop)))); row.ReplaceText(loop, ""); if (table.Rows.Count == 1) { table.InsertRow(); // insert row doesn't work when table has zero rows. We add 1 row and remove the original template row if there is only 1 row in total } table.RemoveRow(index); int rowNumber = 1; foreach (var rowData in loopData) { var newRow = table.InsertRow(row, index); foreach (var cell in newRow.Cells) { var cellValue = cell.Xml.Value; var variables = Regex.Matches(cellValue, options.Variable.Regex, RegexOptions.Multiline); foreach (var variable in variables) { var variableName = variable.ToString().Replace(options.Variable.Start, string.Empty).Replace(options.Variable.End, string.Empty); var cellData = variableName == options.RowNumberVariable ? rowNumber : rowData.GetPropValue(variableName); cell.ReplaceText(variable.ToString(), cellData?.ToString() ?? ""); } } rowNumber++; index++; } } } } //replace variables var variablesToReplace = document.FindUniqueByPattern(options.Variable.Regex, System.Text.RegularExpressions.RegexOptions.Multiline); foreach (var variable in variablesToReplace) { var variableName = variable.Replace(options.Variable.Start, string.Empty).Replace(options.Variable.End, string.Empty); var cellData = GetPropValue(data, variableName); document.ReplaceText(variable.ToString(), cellData?.ToString() ?? ""); } //end of variable replace document.Save(); document.Dispose(); } }