public async Task GenerateContract(Dictionary <string, string> valuePairs, IEnumerable <Equipment> equipments, string filePath) { await Task.Factory.StartNew(() => { string docText = ""; using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(templateFile, true)) { using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())) { docText = sr.ReadToEnd(); } docText = ReplaceMarkersByValues(valuePairs, docText); var savedDoc = wordDoc.SaveAs(filePath); savedDoc.Close(); } using (WordprocessingDocument generatedDocument = WordprocessingDocument.Open(filePath, true)) { using (StreamWriter sw = new StreamWriter(generatedDocument.MainDocumentPart.GetStream(FileMode.Create))) { sw.Write(docText); } FillTable(equipments, generatedDocument); generatedDocument.Save(); } }); }
private static void CreateInnerMethod(DocXDocumentObjectModel model) { //Преподготовка шаблона (удаление не нужных разделений внутри документа) ProcessTemplate(model); //Удаление основного файла CheckAndDeleteDestinationFile(model.DocumentSaveFileName); using var memStream = new MemoryStream(); var bytes = File.ReadAllBytes(model.DocumentTemplateFileName); memStream.Write(bytes, 0, bytes.Length); memStream.Seek(0, SeekOrigin.Begin); using WordprocessingDocument doc = WordprocessingDocument.Open(memStream, true); ProcessTextReplacing(doc, model); foreach (var tableModel in model.Tables) { DocTableInserter.AddTable(doc, tableModel); } foreach (var image in model.ToReplaceImages) { DocImageInserter.InsertAPicture(doc, image); } var t = doc.SaveAs(model.DocumentSaveFileName); t.Dispose(); }
public void ReplaceBookmarks(string sourceDocPath, string targetDocPath, Dictionary <string, string> bookmarks) { bool isEditable = true; // Don't use open unless you want to change that document too, use CreateFromTemplate instead using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(sourceDocPath, isEditable)) { var body = doc.MainDocumentPart.Document.Body; var bookmarkStarts = body.Descendants <BookmarkStart>(); foreach (var header in doc.MainDocumentPart.HeaderParts) { var headerBookmarkStarts = header.Header.Descendants <BookmarkStart>(); bookmarkStarts = bookmarkStarts.Concat(headerBookmarkStarts); } foreach (var bookmarkStart in bookmarkStarts) { Debug.WriteLine($"bookmarkName={bookmarkStart.Name}"); Debug.WriteLine($"bookmarkValue={bookmarkStart.InnerText}"); var bookmarkName = bookmarkStart.Name.InnerText; if (bookmarks.ContainsKey(bookmarkName)) { replaceBookmarkText(bookmarkStart, bookmarks.GetValueOrDefault(bookmarkName)); } } doc.SaveAs(targetDocPath); } }
private void button4_Click(object sender, EventArgs e) { string filepath = @"..\..\template\template2.docx"; string filepath2 = @"..\..\export\export4.docx"; using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath)) { Body body = doc.MainDocumentPart.Document.Body; Table table = body.Elements <Table>().ElementAt(1); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("column1"), new DataColumn("column2"), new DataColumn("column3"), new DataColumn("column4") }); DataRow dr = dt.NewRow(); dr["column1"] = "google"; dr["column2"] = "facebook"; dr["column3"] = "yahoo"; dr["column4"] = "apple"; dt.Rows.Add(dr); DocProcessor.TableRowInsert(table, dt); table = body.Elements <Table>().ElementAt(2); dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("column1"), new DataColumn("column2"), new DataColumn("column3"), new DataColumn("column4") }); dr = dt.NewRow(); dr["column1"] = "google"; dr["column2"] = "facebook"; dr["column3"] = "yahoo"; dr["column4"] = "apple"; dt.Rows.Add(dr); DocProcessor.TableColumnInsert(table, dt); doc.SaveAs(filepath2).Close(); } }
public void SaveZipFile(string openPath, string fileName) { // saves a document into a zip collection that exposes its XML using (WordprocessingDocument doc = WordprocessingDocument.Open(openPath, true)) { string savePath = $"{_basePath}/{fileName}.zip"; doc.SaveAs(savePath); } }
public void AddImage() { WordprocessingDocument word = WordProcessingExtensions.WordDocument(); using (FileStream fs = File.OpenRead($@"{AppDomain.CurrentDomain.BaseDirectory}\Extensions\Word\Templates\Example.JPG")) { Assert.True(word.AddImage(fs)); word.SaveAs($@"{AppDomain.CurrentDomain.BaseDirectory}\TestResults\Extensions\Word\ImageDocument.docx"); } }
public static void SearchAndReplace(string document, Parent parent) { using (WordprocessingDocument wordDoc = WordprocessingDocument.CreateFromTemplate(document)) { string docText = null; using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())) { docText = sr.ReadToEnd(); } docText = docText.Replace("{order.orderId}", "1111222222222222222") .Replace("{order.customerName}", "盛安德盛安德盛安德盛安德盛安德") .Replace("{order.customerAddress}", "盛安德盛安德盛安德盛安德盛安德Address") .Replace("{order.customerContact}", "小张张") .Replace("{order.customerFaxNumber}", "34565675644545") .Replace("{order.selfName}", "盛安德盛安德盛安德盛安德盛安德") .Replace("{order.signDate}", "1990-10-12") .Replace("{order.endWharf}", "曹妃甸") .Replace("{order.startWharf}", "天津港"); using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))) { sw.Write(docText); } Body bod = wordDoc.MainDocumentPart.Document.Body; Table table = bod.Descendants <Table>().First(t => t.InnerText.Contains("船名/航次")); var rows = table.Descendants <TableRow>(); var templateRow = table.Descendants <TableRow>().ElementAt(1); int len = 1; while (len <= 10) { var newRow = templateRow.CloneNode(true) as TableRow; var cells = newRow.Descendants <TableCell>(); ReplaceTableCellText(cells, "{item.voyage}", "WAN MU CHUN 10/1801"); ReplaceTableCellText(cells, "{item.cargo}", "角钢"); ReplaceTableCellText(cells, "{item.value}", "300000.00"); ReplaceTableCellText(cells, "{item.amount}", "40.00"); ReplaceTableCellText(cells, "{item.weight}", "200000.00"); ReplaceTableCellText(cells, "{item.bgfUnit}", "100000.00 元/吨"); ReplaceTableCellText(cells, "{item.receivable}", "-1474836480.00 元"); templateRow.InsertAfterSelf(newRow); len++; } templateRow.Remove(); ReplaceBookmarksWithImage(wordDoc, "seal", "minjie-seal.png"); wordDoc.SaveAs("demo.docx"); } }
private static void LoadContent(byte[] content, string fullPath) { Stream documentStream = new MemoryStream(); documentStream.Write(content, 0, content.Length); using (WordprocessingDocument document = WordprocessingDocument.Open(documentStream, true)) { MainDocumentPart mainPart = document.MainDocumentPart; mainPart.Document.Save(); document.SaveAs(fullPath); } }
public string[] CreateNewWordFile(string fileName, string newFilePath) { var newFileName = DateTime.Now.ToString("HH\\mm\\ss") + ".docx"; newFilePath = newFilePath + newFileName; using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, false)) { var openXml = wordDoc.SaveAs(newFilePath); openXml.Close(); } var FileTab = new string[] { newFilePath, newFileName };; return(FileTab); }
private void button1_Click(object sender, EventArgs e) { string filepath = @"C:\word_test\template.docx"; string filepath2 = @"C:\word_test\1234.docx"; DataTable dt_f06 = new DataTable(); DataTable dt_f06s = new DataTable(); DataTable dt_f06d = new DataTable(); using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath)) { Table table6 = doc.MainDocumentPart.Document.Body.Elements <Table>().ElementAt <Table>(3); foreach (DataRow dr_f06 in dt_f06.Rows) { string groupID = dr_f06.Field <object>("GroupID").ToString(); DataRow[] a = dt_f06s.Select(string.Format(("GroupID = '{0}'"), groupID)); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("major"), new DataColumn("countType"), new DataColumn("firstGrade1") , new DataColumn("firstGrade2"), new DataColumn("secondGrade1"), new DataColumn("secondGrade2"), new DataColumn("thirdGrade1"), new DataColumn("thirdGrade2"), new DataColumn("sum") }); //mock up dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("major"), new DataColumn("countType") }); DataRow dr = dt.NewRow(); dr["major"] = "普通科"; dr["countType"] = "班級數"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["major"] = "普通科"; dr["countType"] = "班級數"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["major"] = "普通科"; dr["countType"] = "班級數"; dt.Rows.Add(dr); //DocProcessor.TableColumnInsert(table6, dt); //DocProcessor.TableRowInsert(table6, dt); //DocProcessor.DeleteTableColumn(table6, 1); //DocProcessor.DeleteTableRow(table6, 5); DocProcessor.DuplicateElement(table6, new Paragraph(new Run(new Break() { Type = BreakValues.Page }))); doc.SaveAs(filepath2).Close(); } } }
public void BuildTemplate(string fileName, string newFilePath) { var bytes = File.ReadAllBytes(fileName); var ms = new MemoryStream(); ms.Write(bytes, 0, bytes.Length); ms.Position = 0; using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(ms, true)) { var body = wordDoc.MainDocumentPart.Document.Body; ReplaceTable(body); ReplaceTemplate(body); wordDoc.SaveAs(newFilePath); }; ms.Dispose(); }
private void button2_Click(object sender, EventArgs e) { string filepath = @"..\..\template\template1.docx"; string filepath2 = @"..\..\export\export2.docx"; using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath)) { Body body = doc.MainDocumentPart.Document.Body; Table table = body.Elements <Table>().ElementAt(0); DocProcessor.TableCellMerge(table, 0, 0, 3, 0); DocProcessor.TableCellMerge(table, 0, 1, 0, 3); DocProcessor.TableCellMerge(table, 4, 4, 6, 6); doc.SaveAs(filepath2).Close(); } }
private void button3_Click(object sender, EventArgs e) { string filepath = @"..\..\template\template2.docx"; string filepath2 = @"..\..\export\export3.docx"; using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath)) { Body body = doc.MainDocumentPart.Document.Body; Table table = body.Elements <Table>().ElementAt(1); DocProcessor.DeleteTableColumn(table, 3); table = body.Elements <Table>().ElementAt(2); DocProcessor.DeleteTableRow(table, 3); doc.SaveAs(filepath2).Close(); } }
private void button1_Click(object sender, EventArgs e) { string filepath = @"..\..\template\template1.docx"; string filepath2 = @"..\..\export\export1.docx"; using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath)) { Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("aaa", "apple"); dic.Add("bbb", "Banana"); dic.Add("ccc", "California"); dic.Add("ddd", "dog"); DocProcessor.ReplaceTags(doc.MainDocumentPart.Document.Body, dic); doc.SaveAs(filepath2).Close(); } }
private void button5_Click(object sender, EventArgs e) { string filepath = @"..\..\template\template2.docx"; string filepath2 = @"..\..\export\export5.docx"; using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath)) { Body body = doc.MainDocumentPart.Document.Body; Table table = body.Elements <Table>().ElementAt(1); DocProcessor.DuplicateElement(table); table = body.Elements <Table>().ElementAt(3); DocProcessor.DuplicateElement(table, new Paragraph(new Run(new Break() { Type = BreakValues.Page }))); doc.SaveAs(filepath2).Close(); } }
static void Main(string[] args) { const string templatePath = @"C:\Users\Gaurav Koli\source\repos\openXmlDemo\openXmlDemo\target\SampleDocOriginal.docx"; const string resultPath = @"C:\Users\Gaurav Koli\source\repos\openXmlDemo\openXmlDemo\Result\result.docx"; try { using (WordprocessingDocument wordDocument = WordprocessingDocument.CreateFromTemplate(templatePath, true)) { ReplaceParagraphParts(wordDocument.MainDocumentPart.Document, wordDocument); wordDocument.SaveAs(resultPath); } } catch (IOException ioe) { Console.WriteLine(ioe.Message); Console.ReadKey(); } }
/// <summary> /// УБрать из шаблона документа тексты, которые являются разбитыми по нескольким элементам /// </summary> /// <param name="model"></param> public static void ProcessTemplate(DocXDocumentObjectModel model) { using (var memStream = new MemoryStream()) { var bytes = File.ReadAllBytes(model.DocumentTemplateFileName); memStream.Write(bytes, 0, bytes.Length); memStream.Seek(0, SeekOrigin.Begin); using (WordprocessingDocument doc = WordprocessingDocument.Open(memStream, true)) { var body = doc.MainDocumentPart.Document.Body; var paras = FindElemsInElement <Paragraph>(body); foreach (var para in paras) { foreach (var toReplace in model.Replaces) { if (para.InnerText.Contains(toReplace.Key)) { var pRun = para.GetFirstChild <Run>(); var fRunProp = pRun.GetFirstChild <RunProperties>().CloneNode(true); var text = para.InnerText; para.RemoveAllChildren <Run>(); para.AppendChild(new Run(fRunProp, new Text(text))); } } } var t = doc.SaveAs(model.DocumentTemplateFileName); t.Dispose(); } } }
private static string EditOpenXmlDocument(string inputFile) { LogMessages("Editando o Docx"); string newFileName = inputFile.Replace(".docx", "-new.docx").Replace(".doc", "-new.docx"); Stream stream = File.Open(inputFile, FileMode.Open); using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true)) { string docText = null; using (StreamReader sr = new StreamReader(wordDocument.MainDocumentPart.GetStream())) { docText = sr.ReadToEnd(); } Regex regexText = new Regex("«nome_proponente»"); docText = regexText.Replace(docText, "Joao Schmidt"); regexText = new Regex("«cidade»"); docText = regexText.Replace(docText, "Porto alegre"); regexText = new Regex("CIDADE"); docText = regexText.Replace(docText, "Porto alegre"); regexText = new Regex("«SEGURADO»"); docText = regexText.Replace(docText, "Joao Schmidt"); using (StreamWriter sw = new StreamWriter(wordDocument.MainDocumentPart.GetStream(FileMode.Create))) { sw.Write(docText); } LogMessages("Docx editado"); LogMessages("Salvando novo Docx"); var newFile = wordDocument.SaveAs(newFileName); newFile.Close(); LogMessages("Novo Docx Salvo"); } return(newFileName); }
public string FillTemplate(string template, Empleado empleado) { string dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string name = string.Format("{1}_{0}.docx", empleado.RFC, Path.GetFileNameWithoutExtension(template)); string end_path = Path.Combine(dir, name); // clone the template using (WordprocessingDocument TemplateDoc = WordprocessingDocument.Open(template, false)) { TemplateDoc.SaveAs(end_path).Close(); } // do the swappening using (WordprocessingDocument OutDoc = WordprocessingDocument.Open(end_path, true)) { string docText = null; using (StreamReader sr = new StreamReader(OutDoc.MainDocumentPart.GetStream())) { docText = sr.ReadToEnd(); } Regex regexText = new Regex(@"\$RFC"); docText = regexText.Replace(docText, empleado.RFC); regexText = new Regex(@"\$NOMBRE"); docText = regexText.Replace(docText, empleado.Nombre); regexText = new Regex(@"\$SEXO"); docText = regexText.Replace(docText, empleado.Sexo); regexText = new Regex(@"\$ESTADO_CIVIL"); docText = regexText.Replace(docText, empleado.EstadoCivil); using (StreamWriter sw = new StreamWriter(OutDoc.MainDocumentPart.GetStream(FileMode.Create))) { sw.Write(docText); } } return(end_path); }
public void ReplaceProperties(string sourceDocPath, string targetDocPath, Dictionary <string, string> bookmarks) { //using (WordprocessingDocument doc = WordprocessingDocument.Open(sourceDocPath, true)) var isEditable = true; using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(sourceDocPath, isEditable)) { var body = doc.MainDocumentPart.Document.Body; foreach (var paragraph in body.Descendants <Paragraph>()) { Debug.WriteLine(paragraph); /*if (paragraph.Text.Contains("##sagsid##")) * { * text.Text = text.Text.Replace("##sagsid##", "Sagsid: 199"); * }*/ } foreach (var text in body.Descendants <Text>()) { if (text.Text.Contains("##sagsid##")) { text.Text = text.Text.Replace("##sagsid##", "Sagsid: 199"); } } foreach (var customProp in doc.CustomFilePropertiesPart.Properties.Descendants <CustomDocumentProperty>()) { Debug.WriteLine($"Name={customProp.Name} Value={customProp.InnerText}"); //customProp.SetAttribute(customProp); //customProp = 173; } //doc.Save(); doc.SaveAs(targetDocPath); } }
/// <summary> /// Saves the document to the specified path /// </summary> /// <param name="path"></param> public void SaveAs(string path) { Save(); document.SaveAs(path); }
/// <summary> /// Save the current document in other file, consider that previously to save to other document the current document is saved. /// </summary> /// <param name="fileName"></param> public void SaveAs(string fileName) { m_Document.SaveAs(fileName); }
public void BuildDocument(string[] AutoTextName) { /* Here's where I look in the Glossary Document Part to determine it there IS AutoText * If there isn't, then there's no use in creating the List of AutoText objects! */ gdp = mdp.GlossaryDocumentPart; if (gdp != null) { foreach (string atxname in AutoTextName) { atxt = new CBAutoText { GDP = gdp, Name = atxname }; Console.WriteLine("AutoText Name ==> {0}", atxt.Name); // Create a new relationship in the NEW document with the AutoText FOUND in the template // Think about changing how this code is called. atxt.CheckForRelationship(); // Retrieve RELATIONSHIP IDs from the document/document.xml in Main document/Document being created Console.WriteLine("Count of Content Controls in this document is {0}\n", doc.Body.Descendants <SdtElement>().Count()); Console.ReadLine(); var cctrl = (from sdtCtrl in doc.Body.Descendants <SdtElement>() where sdtCtrl.SdtProperties.GetFirstChild <SdtAlias>().Val == atxt.CCName || sdtCtrl.SdtProperties.GetFirstChild <SdtAlias>().Val == atxt.Name select sdtCtrl).SingleOrDefault(); XElement cc = XElement.Parse(atxt.CCContent); IEnumerable <XAttribute> ccAttrs = cc.Descendants().Attributes(); var ccRelIDs = (from attrib in ccAttrs where attrib.Value.Contains("rId") select attrib).ToArray(); Console.WriteLine("List of IdPartPairs {0}", mdp.Parts.Count()); foreach (var item in mdp.Parts) { Console.WriteLine("RelIDs ==> {0}", item.RelationshipId); } Console.WriteLine("Found rIds {0}", ccRelIDs.Count()); foreach (var item in ccRelIDs) { Console.WriteLine("RelIDs ==> {0}", item); } Console.WriteLine(); if (ccRelIDs.Count() > 0) { foreach (var RelIDs in ccRelIDs) { oldid = RelIDs.Value; Console.WriteLine("RelIDs = {0} and oldid = {1}", RelIDs.Value, oldid); } } if (atxt.HasARelationship) { int i = 0; foreach (var RelPart in atxt.RelationshipParts) { //Establish new relationship atxt.NewRelID = mdp.CreateRelationshipToPart(RelPart); newsignature = atxt.Content.Replace(oldid, atxt.NewRelID); i++; } } if (newsignature.Length != 0) { cctrl.InnerXml = newsignature; } else { cctrl.InnerXml = atxt.Content; } } wrddoc.SaveAs(DOC_PATH_NAME); wrddoc.Close(); } }
private static void AddDocumentTask(string filePath) { Console.WriteLine("Processing presentation: {0}", filePath); using WordprocessingDocument docPackage = WordprocessingDocument.Open(filePath, true); string newFn = filePath.Replace(".docx", "_new.docx"); using WordprocessingDocument newDocumentPackage = (WordprocessingDocument)docPackage.SaveAs(newFn.ToString()); newDocumentPackage.AddParagraphIdFeature(); MainDocumentPart mdp = newDocumentPackage.MainDocumentPart; string strCommentId = "3"; string comment = " Here's another sentence that is just too long. Shorten it please."; string run = "The introduction to this article."; // userids, providers and names will have to be programmatically accessed via directory services and must be valid. These are just for example User tony = new("S::[email protected]::3063813b-f01d-4030-9808-501a178e7963", "John Doe", "AD", "@John Doe", "*****@*****.**"); User bruce = new("S::[email protected]::ec6240b1-52a3-46dd-9697-ef7bcc7a29e8", "Jane Doe", "AD", "@Jane Doe", "*****@*****.**"); AddNewParagraphRunWithComment(mdp, strCommentId, run); AddMentionComment(mdp, strCommentId, bruce.Mention, comment, tony, bruce); string taskStr = string.Concat(bruce.Mention, " ", comment); AddNewTask(mdp, taskStr, bruce, tony); }
public void SaveDocument(string fileName) => package.SaveAs(fileName);
public void Save(string saveLoc) { curDoc.SaveAs(saveLoc); }