OpenXML Create Word Document always corrupt C# - c#

I am working on an old webforms application and I am trying to create a word document via the OpenXml in C# within one of the pages. I am trying to read in data from SQL to populate a table I will create in the word document by following the examples found at http://www.ludovicperrichon.com/create-a-word-document-with-openxml-and-c/
However, every time I run the code it produces a document that Word reports is corrupt and presents the following message:
I cannot see what the issue is and I have been trying to find similar issues for a solution but I can only find mentions of a problem with the stream but this seems to be only when when reading an existing document to edit not creating a new one.
My example code is below (excluding the DataTable dt where the data is loaded, since that element works fine).
var header = "";
using (var stream = new MemoryStream())
{
using (var wordDoc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
{
// Add a main document part.
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body docBody = new Body();
mainPart.Document.Body = docBody;
// Load study plan and build word table to hold data
// Create an empty table.
var table = new DocumentFormat.OpenXml.Drawing.Table();
// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new BottomBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new LeftBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new RightBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideHorizontalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideVerticalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
}
)
);
// Append the TableProperties object to the empty table.
table.AppendChild<TableProperties>(tblProp);
// Add header row
// Create a row.
var hr = new DocumentFormat.OpenXml.Drawing.TableRow();
// Create a cell.
var hc1 = new DocumentFormat.OpenXml.Drawing.TableCell();
// Specify the width property of the table cell.
hc1.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
// Specify the table cell content.
hc1.Append(new Paragraph(new Run(new Text("Start Date"))));
// Append the table cell to the table row.
hr.Append(hc1);
// Create a cell
var hc2 = new DocumentFormat.OpenXml.Drawing.TableCell();
hc2.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
hc2.Append(new Paragraph(new Run(new Text("End Date"))));
// Append the table cell to the table row.
hr.Append(hc2);
// Create a cell
var hc3 = new DocumentFormat.OpenXml.Drawing.TableCell();
hc3.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
hc3.Append(new Paragraph(new Run(new Text("Type"))));
// Append the table cell to the table row.
hr.Append(hc3);
// Create a cell
var hc4 = new DocumentFormat.OpenXml.Drawing.TableCell();
hc4.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
hc4.Append(new Paragraph(new Run(new Text("Status"))));
// Append the table cell to the table row.
hr.Append(hc4);
// Create a cell
var hc5 = new DocumentFormat.OpenXml.Drawing.TableCell();
hc5.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
hc5.Append(new Paragraph(new Run(new Text("Description"))));
// Append the table cell to the table row.
hr.Append(hc5);
// Append the table row to the table.
table.Append(hr);
// Add data rows
for (var i = 0; i < dt.Rows.Count; i++)
{
// Create a row.
var tr = new DocumentFormat.OpenXml.Drawing.TableRow();
// Create a cell.
var tc1 = new DocumentFormat.OpenXml.Drawing.TableCell();
// Specify the width property of the table cell.
tc1.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
// Specify the table cell content.
tc1.Append(new Paragraph(new Run(new Text(dt.Rows[i]["start"].ToString()))));
// Append the table cell to the table row.
tr.Append(tc1);
//Create a cell
var tc2 = new DocumentFormat.OpenXml.Drawing.TableCell();
tc2.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
tc2.Append(new Paragraph(new Run(new Text(dt.Rows[i]["end"].ToString()))));
//Append the table cell to the table row.
tr.Append(tc2);
///Create a cell
var tc3 = new DocumentFormat.OpenXml.Drawing.TableCell();
tc3.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
tc3.Append(new Paragraph(new Run(new Text(dt.Rows[i]["type"].ToString()))));
//Append the table cell to the table row.
tr.Append(tc3);
// Create a cell
var tc4 = new DocumentFormat.OpenXml.Drawing.TableCell();
tc4.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
tc4.Append(new Paragraph(new Run(new Text(dt.Rows[i]["status"].ToString()))));
//Append the table cell to the table row.
tr.Append(tc4);
//Create a cell
var tc5 = new DocumentFormat.OpenXml.Drawing.TableCell();
tc5.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
tc5.Append(new Paragraph(new Run(new Text(dt.Rows[i]["description"].ToString()))));
//Append the table cell to the table row.
tr.Append(tc5);
//Append the table row to the table.
table.Append(tr);
}
//Append the table to the document.
wordDoc.MainDocumentPart.Document.Body.Append(table);
header = "attachment;filename=" + DateTime.Today.ToString("dd/MM/yyyy") + student.Replace(" ", "_") + "_study_plan.docx";
}
Context.Response.AppendHeader("Content-Disposition", header);
stream.Position = 0;
stream.CopyTo(Context.Response.OutputStream);
Context.Response.Flush();
Context.Response.End();
}

You are using the tableelements from the wrong namespace. Instead of
var table = new DocumentFormat.OpenXml.Drawing.Table();
use
var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
This goes for all the other table elements (cells etc) as well.
I recommend using OpenXMLSDK. If you end up with an invalid file it will show you what's wrong with it.

Related

TableStyle not working when using DocumentFormat.OpenXml.Wordprocessing

I'm trying to add a table to Word Document using OpenXML. I've found some examples and they seem to work just fine, with the exception of TableStyle. I've tried Appending, Appending as a Child (not sure what to use when, but tried both) but whatever I do - style is never applied. The width is getting applied tho.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
public static void InsertTableInDoc(string filepath)
{
// Open a WordprocessingDocument for editing using the filepath.
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true))
{
// Assign a reference to the existing document body.
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
// Create a table.
Table tbl = new Table();
// Set the style and width for the table.
TableProperties tableProp = new TableProperties();
TableStyle tableStyle = new TableStyle() { Val = "TableGrid" };
// Make the table width 100% of the page width.
TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct };
// Apply
tableProp.Append(tableStyle, tableWidth);
// Add 3 columns to the table.
TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn());
tbl.AppendChild(tg);
// Create 1 row to the table.
TableRow tr1 = new TableRow();
// Add a cell to each column in the row.
TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("1"))));
TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("2"))));
TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("3"))));
tr1.Append(tc1, tc2, tc3);
// Add row to the table.
tbl.AppendChild(tr1);
// Add the table to the document
body.AppendChild(tbl);
}
}
public static void CreateWordprocessingDocument(string fileName)
{
string[,] data = {
{"Texas", "TX"},
{"California", "CA"},
{"New York", "NY"},
{"Massachusetts", "MA"}
};
using (var wordDocument = WordprocessingDocument.Open(fileName, true))
{
// We need to change the file type from template to document.
wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document);
var body = wordDocument.MainDocumentPart.Document;
Table table = new Table();
TableProperties props = new TableProperties();
TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };
props.Append(tableStyle);
table.AppendChild(props);
for (var i = 0; i <= data.GetUpperBound(0); i++)
{
var tr = new TableRow();
for (var j = 0; j <= data.GetUpperBound(1); j++)
{
var tc = new TableCell();
tc.Append(new Paragraph(new Run(new Text(data[i, j]))));
tc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
tr.Append(tc);
}
table.Append(tr);
}
body.Append(table);
wordDocument.MainDocumentPart.Document.Save();
}
}
I've tried using TableProperties with TableBorders example and that seems to work fine, I've also tried playing with TableLook using this example, but again TableStyle was not getting applied. I am missing something about TableStyles that is just not working.
After some research, it seems that when you create an OpenXML document it's basically empty. There are no styles, no table styles, no nothing and Word just doesn't magically make it work. Each style you want to use needs to be defined in a document, meaning you need to add a table to a document with the proper style for it to show up. So after using OpenXML SDK 2.5 Productivity Tool I was able to extract styles for tables from a newly created documents with tables.
When you use OpenXML SDK 2.5 productivity tool you get code reflection so you can have it auto-generate code for you.
So I just copied the Styles to document, and once that is done referencing table styles in the Table itself should work!
private void GenerateStyleDefinitionsPart1Content(StyleDefinitionsPart styleDefinitionsPart1)
... TOO LONG TO add it all
It took me a while to understand it, but with OpenXML SDK 2.5 productivity tool it's much easier - highly recommended.

How to replace text with Image / Table in OpenXML (C# .Net core 3.1)

I am just using OpenXML for manipulating docx document. I have templates that has notation like
{{userFirstName}}
{{tableOfUsers}}
{{signatureImage}} etc
I need to replace those text with table, image etc. How to do that in Openxml ?
I'm using C# .Net core 3.1 with OpenXML 2.5
My code was like this, but the table still not inserted into the right place:
var fileName = Path.Combine(_hostingEnv.WebRootPath, "test/test.docx");
var fileNameResult = Path.Combine(_hostingEnv.WebRootPath, "test/result.docx");
byte[] byteArray = System.IO.File.ReadAllBytes(fileName);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (WordprocessingDocument wd = WordprocessingDocument.Open(stream, true))
{
Table table = new Table();
// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new BottomBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new LeftBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new RightBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideHorizontalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideVerticalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
}
)
);
// Append the TableProperties object to the empty table.
table.AppendChild<TableProperties>(tblProp);
// Create a row.
TableRow tr = new TableRow();
// Create a cell.
TableCell tc1 = new TableCell();
// Specify the width property of the table cell.
tc1.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
// Specify the table cell content.
tc1.Append(new Paragraph(new Run(new Text("some text"))));
// Append the table cell to the table row.
tr.Append(tc1);
// Create a second table cell by copying the OuterXml value of the first table cell.
TableCell tc2 = new TableCell(tc1.OuterXml);
// Append the table cell to the table row.
tr.Append(tc2);
// Append the table row to the table.
table.Append(tr);
var tblStr = table.ToString();
//wd.MainDocumentPart.Document.Body.Append(table);
Text tablePl = wd.MainDocumentPart.Document.Body.Descendants<Text>().Where(x => x.Text == "{{tableOfUsers}}").First();
if(tablePl != null)
{
var parent = tablePl.Parent;
tablePl.Parent.InsertAfter<Table>(table, tablePl);
tablePl.Remove();
}
string docText = null;
using (StreamReader sr = new StreamReader(wd.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("{{name}}");
docText = regexText.Replace(docText, "Claire " + DateTime.Now.ToString());
// Regex regextable = new Regex("{{tableOfUsers}}");
// docText = regextable.Replace(docText, tblStr);
using (StreamWriter sw = new StreamWriter(wd.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
await System.IO.File.WriteAllBytesAsync(fileNameResult, stream.ToArray());
}
_fileRepo.SetPath("test");
string fileName2 = "result.docx";
var data = await _fileRepo.DownloadFile(fileName2);
return File(data, "application/octet-stram", "filename.docx");
}
My docx file looks like
Hello {{name}}
Here is the list of users : {{tableOfUsers}}
Sincerely,
{{signatureImage}}
Use the code below to insert a table:
............
string tablePlaceholder = "{{tableOfUsers}}";
Text tablePl = wd.MainDocumentPart.Document.Body
.Descendants<Text>()
.Where(x => x.Text.Contains(tablePlaceholder))
.First();
if (tablePl != null)
{
//Insert the table after the paragraph.
var parent = tablePl.Parent.Parent.Parent;
parent.InsertAfter(table, tablePl.Parent.Parent);
tablePl.Text = tablePl.Text.Replace(tablePlaceholder, "");
wd.MainDocumentPart.Document.Save();
}
string docText = wd.MainDocumentPart.Document.Body.OuterXml;
Regex regexText = new Regex("{{name}}");
docText = regexText.Replace(docText, "Claire " + DateTime.Now.ToString());
wd.MainDocumentPart.Document.Body = new Body(docText);
wd.MainDocumentPart.Document.Save();
.............
You are looking for {{table}} in your code, but the notation in your template is {{tableOfUsers}}.

Remove cell borders in table in Word document (OpenXml.Wordprocessing)

I'm using DocumentFormat.OpenXml.Wordprocessing to add a table in a Word document. What I need is to remove the border of the first 4(/6) cells in the last 3(/N) rows of the table. These rows are added like:
t.Append(new TableRow(
new TableCell(new Paragraph(new Run(new Text()))),
new TableCell(new Paragraph(new Run(new Text()))),
new TableCell(new Paragraph(new Run(new Text()))),
new TableCell(new Paragraph(new Run(new Text()))),
new TableCell(new Paragraph(new Run(new Text("Total:")))),
new TableCell(new Paragraph(new Run(new Text(priceTotal.ToString()))))
));
How do I set the TableCellBorders? I've tried a few things like:
TableCell cell = new TableCell();
cell.TableCellProperties.TableCellBorders.LeftBorder.Size.Value = 0;
cell.TableCellProperties.TableCellBorders.RightBorder.Size.Value = 0;
cell.TableCellProperties.TableCellBorders.TopBorder.Size.Value = 0;
cell.TableCellProperties.TableCellBorders.BottomBorder.Size.Value = 0;
However, everything that I've tried returns System.NullReferenceException. What is the proper way of removing the cell borders?
You can create a table in word with no borders like this:
public static void CreateTable(string fileName)
{
// Use the file name and path passed in as an argument
// to open an existing Word 2007 document.
using (WordprocessingDocument doc
= WordprocessingDocument.Open(fileName, true))
{
// Create an empty table.
Table table = new Table();
// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.None),
},
new BottomBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.None),
},
new LeftBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.None),
},
new RightBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.None),
},
new InsideHorizontalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.None),
},
new InsideVerticalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.None),
}
)
);
// Append the TableProperties object to the empty table.
table.AppendChild<TableProperties>(tblProp);
// Create a row.
TableRow tr = new TableRow();
// Create a cell.
TableCell tc1 = new TableCell();
// Specify the width property of the table cell.
tc1.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
// Specify the table cell content.
tc1.Append(new Paragraph(new Run(new Text("some text"))));
// Append the table cell to the table row.
tr.Append(tc1);
// Create a second table cell by copying the OuterXml value of the first table cell.
TableCell tc2 = new TableCell(tc1.OuterXml);
// Append the table cell to the table row.
tr.Append(tc2);
// Append the table row to the table.
table.Append(tr);
// Append the table to the document.
doc.MainDocumentPart.Document.Body.Append(table);
}
}
Customize and optimize it, to your needs :)

Problems applying a tablestyle

I'm trying to apply a table style to a table in openxml word.
I've looked at several examples, but I'm stumped on why the tablestyle is not showing up... I've checked the other posts like Apply a TableStyle to a Word Table
This is the code:
public Table CreateTable(string tableStyle, Headings headingsList)
{
Table table = new Table();
// Set the Style
TableProperties tblProps = new TableProperties();
TableStyle tblStyle = new TableStyle() { Val = "LightGrid-Accent4" };
TableWidth tblWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct};
// TODO: Requires a class and remove hardcoding
TableLook tblLook = new TableLook() { FirstRow = true, LastRow = false, FirstColumn = false, LastColumn = false, NoHorizontalBand = false, NoVerticalBand = true };
tblProps.TableStyle = tblStyle;
tblProps.TableWidth = tblWidth;
table.Append(tblProps);
TableRow tr = new TableRow();
foreach (Heading heading in headingsList)
{
TableCell tc = new TableCell();
TableCellWidth tcw = new TableCellWidth() { Width = heading.Width.ToString(), Type = TableWidthUnitValues.Pct };
tc.Append(tcw);
tc.Append(new Paragraph(new Run(new Text(heading.Title))));
tr.Append(tc);
}
table.Append(tr);
return table;
}
I've looked at the OpenXML tool and had a look at the generated document which also looks fine. In the document, however, the table isn't formatted.
Any ideas would be appreciated.

How to delete data or table within two bookmarks from word document using OpenXml in C#

I am creating word document in C# using OpenXML.
I can insert my Text after specified bookmark, but how can delete data within two bookmarks.
Following is the code to insert text after specified Bookmark.
string fileName = #"C:\Users\sharepointadmin\Desktop\volc.docx";
TableValues ObjTableValues = new TableValues();
List<TableValues> allValues = new System.Collections.Generic.List<TableValues>();
for (int i = 1; i <= 5; i++)
{
ObjTableValues = new TableValues();
ObjTableValues.EmpID = i.ToString();
ObjTableValues.EmpName = "Emp" + i.ToString();
ObjTableValues.EmpDesig = "SE";
ObjTableValues.EmpDept = "Software";
allValues.Add(ObjTableValues);
//ConvertMailMergeEscape(fileName);
}
AddTable(fileName, allValues);
}
using (var document = WordprocessingDocument.Open(fileName, true))
{
IDictionary<String, BookmarkStart> bookmarkMap = new Dictionary<String, BookmarkStart>();
var doc = document.MainDocumentPart.Document;
var mainpart = document.MainDocumentPart;
var res = from ObjTableValues in mainpart.Document.Body.Descendants<BookmarkStart>() where ObjTableValues.Name == "testbookmark" select ObjTableValues;
var bookmark = res.SingleOrDefault();
if (bookmark != null)
{
var parent = bookmark.Parent;
run.Append(text);
Paragraph newParagraph = new Paragraph(run);
// insert after bookmark parent
parent.InsertAfterSelf(newParagraph);
foreach (BookmarkStart bookmarkStart in document.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
{
bookmarkMap[bookmarkStart.Name] = bookmarkStart;
}
MoveToRangeStart ranstart = new MoveToRangeStart();
foreach (BookmarkStart bookmarkStart in bookmarkMap.Values)
{
Run bookmarkText = bookmarkStart.NextSibling<Run>();
if (bookmarkText != null)
{
//bookmarkText.GetFirstChild<Text>().Text = "blah";
}
}
DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
TableProperties props = new TableProperties(
new TableBorders(
new TopBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new BottomBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new LeftBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new RightBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideHorizontalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideVerticalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
}));
table.AppendChild<TableProperties>(props);
foreach (TableValues Tableitem in allValues)
{
var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
var tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
tc.Append(new Paragraph(new Run(new Text(Tableitem.EmpID))));
tr.Append(tc);
tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
tc.Append(new Paragraph(new Run(new Text(Tableitem.EmpName))));
tr.Append(tc);
tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
tc.Append(new Paragraph(new Run(new Text(Tableitem.EmpDesig))));
tr.Append(tc);
tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
tc.Append(new Paragraph(new Run(new Text(Tableitem.EmpDept))));
tr.Append(tc);
table.Append(tr);
}
doc.Body.Append(table);
doc.Save();
}
}
}
}
Can any one help me please.
I assume you want to delete some table or data from word document. If this is the case than I will suggest you to enable the developer tab in Microsoft Word. For Microsoft Word 2007 if you click on Office Button and than go to "Word Options" button which is at the bottom of drop down menue. Now enable Show "Developer tab in The Ribbon".
Once you have activated the developer tab now you can see an additional tab "Developer" in your Microsoft Word. From this tab if you click on the Rich Text icon (Marked with Aa), will insert a tag on your word document. Now, If you right click on the tag, you can give this tag a name and id.
Now you can access this tag by its id or name in C#.
e.g. the tag name you have given is 'Test Tag'
MainDocumentPart mainPart = doc.MainDocumentPart;
List<SdtBlock> taggedContentControls = mainPart.Document.Descendants<SdtBlock>().ToList();
foreach (var tagControl in taggedContentControls)
{
string tagName = tagControl.Descendants<SdtAlias>().First().Val.Value;
if(tagName== "Test Tag")
{
// you can insert any data in this tag over here
}
Now, with similar approach let's suppose you have a table and some other data in this tag that you want to delete
foreach (var tagControl in taggedContentControls)
{
string tagName = tagControl.Descendants<SdtAlias>().First().Val.Value;
if (tagName.Contains("Test Tag"))
{
// If we want to delete table only
//tagControl.SdtContentBlock.Descendants<Table>().First().Remov();
// If you want to remove everything in this tag
tagControl.SdtContentBlock.Remove();
}
}
dont forget to save your document at the end of this operation
i mean mainpart.Document.Save();
for simplicity I have written multiple LINQ statements to fetch tag from the document. You can change them according to your understanding.
I hope it will help you to get your problem sorted.
Regards

Categories

Resources