c# How to write in Microsoft Interop Word - c#

I am writing my reports directly in microsoft word file, the problem is I cannot write a different text. It just override my other text.
Word.Application myWord = new Word.Application();
//create the document
Word.Document myDoc = myWord.Documents.Add();
//ADD PARAGRAPH
myDoc.Content.Text = "Identified Market/Visitors" + " " + "Museum (as a whole)" + " " + "Percentage" + " ";
myDoc.Content.Text = "2" + " " + "76)" + " " + "25% "+ " ";
saveFileDialog1.Filter = "Word Document|*.docx";
string path = saveFileDialog1.FileName;
myDoc.Close();
The second Content Text overrides the First Content Text.
How can I write another line of text?

The best way to generate docx is to use OpenXmlSDK.
The easiest way to write code is to create docx in word which looks like report you want and reverse Enginier C# code from docx using open xml sdk tools and not to reinvent the wheel.
Generated code for your text:
Body body1 = new Body();
Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "008B2DA9", RsidParagraphProperties = "008B2DA9", RsidRunAdditionDefault = "008B2DA9", ParagraphId = "769280AB", TextId = "395E2934" };
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
Tabs tabs1 = new Tabs();
TabStop tabStop1 = new TabStop(){ Val = TabStopValues.Left, Position = 3686 };
TabStop tabStop2 = new TabStop(){ Val = TabStopValues.Left, Position = 6804 };
tabs1.Append(tabStop1);
tabs1.Append(tabStop2);
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
Languages languages1 = new Languages(){ Val = "en-US" };
paragraphMarkRunProperties1.Append(languages1);
paragraphProperties1.Append(tabs1);
paragraphProperties1.Append(paragraphMarkRunProperties1);
Run run1 = new Run(){ RsidRunProperties = "005F7E61" };
RunProperties runProperties1 = new RunProperties();
Languages languages2 = new Languages(){ Val = "en-US" };
runProperties1.Append(languages2);
Text text1 = new Text();
text1.Text = "Identified Market/Visitors";
run1.Append(runProperties1);
run1.Append(text1);
Run run2 = new Run();
RunProperties runProperties2 = new RunProperties();
Languages languages3 = new Languages(){ Val = "en-US" };
runProperties2.Append(languages3);
TabChar tabChar1 = new TabChar();
run2.Append(runProperties2);
run2.Append(tabChar1);
Run run3 = new Run(){ RsidRunProperties = "005F7E61" };
RunProperties runProperties3 = new RunProperties();
Languages languages4 = new Languages(){ Val = "en-US" };
runProperties3.Append(languages4);
Text text2 = new Text();
text2.Text = "Museum (as a whole)";
run3.Append(runProperties3);
run3.Append(text2);
Run run4 = new Run();
RunProperties runProperties4 = new RunProperties();
Languages languages5 = new Languages(){ Val = "en-US" };
runProperties4.Append(languages5);
TabChar tabChar2 = new TabChar();
run4.Append(runProperties4);
run4.Append(tabChar2);
Run run5 = new Run(){ RsidRunProperties = "005F7E61" };
RunProperties runProperties5 = new RunProperties();
Languages languages6 = new Languages(){ Val = "en-US" };
runProperties5.Append(languages6);
Text text3 = new Text();
text3.Text = "Percentage";
run5.Append(runProperties5);
run5.Append(text3);
paragraph1.Append(paragraphProperties1);
paragraph1.Append(run1);
paragraph1.Append(run2);
paragraph1.Append(run3);
paragraph1.Append(run4);
paragraph1.Append(run5);
Paragraph paragraph2 = new Paragraph(){ RsidParagraphMarkRevision = "008B2DA9", RsidParagraphAddition = "008B2DA9", RsidParagraphProperties = "008B2DA9", RsidRunAdditionDefault = "008B2DA9", ParagraphId = "6C5F87B4", TextId = "46169FF3" };
ParagraphProperties paragraphProperties2 = new ParagraphProperties();
Tabs tabs2 = new Tabs();
TabStop tabStop3 = new TabStop(){ Val = TabStopValues.Left, Position = 3686 };
TabStop tabStop4 = new TabStop(){ Val = TabStopValues.Left, Position = 6804 };
tabs2.Append(tabStop3);
tabs2.Append(tabStop4);
ParagraphMarkRunProperties paragraphMarkRunProperties2 = new ParagraphMarkRunProperties();
Languages languages7 = new Languages(){ Val = "en-US" };
paragraphMarkRunProperties2.Append(languages7);
paragraphProperties2.Append(tabs2);
paragraphProperties2.Append(paragraphMarkRunProperties2);
Run run6 = new Run();
RunProperties runProperties6 = new RunProperties();
Languages languages8 = new Languages(){ Val = "en-US" };
runProperties6.Append(languages8);
Text text4 = new Text();
text4.Text = "2";
run6.Append(runProperties6);
run6.Append(text4);
Run run7 = new Run();
RunProperties runProperties7 = new RunProperties();
Languages languages9 = new Languages(){ Val = "en-US" };
runProperties7.Append(languages9);
TabChar tabChar3 = new TabChar();
Text text5 = new Text();
text5.Text = "76";
run7.Append(runProperties7);
run7.Append(tabChar3);
run7.Append(text5);
Run run8 = new Run();
RunProperties runProperties8 = new RunProperties();
Languages languages10 = new Languages(){ Val = "en-US" };
runProperties8.Append(languages10);
TabChar tabChar4 = new TabChar();
Text text6 = new Text();
text6.Text = "25%";
run8.Append(runProperties8);
run8.Append(tabChar4);
run8.Append(text6);
paragraph2.Append(paragraphProperties2);
paragraph2.Append(run6);
paragraph2.Append(run7);
paragraph2.Append(run8);
Paragraph paragraph3 = new Paragraph(){ RsidParagraphMarkRevision = "005F7E61", RsidParagraphAddition = "00BA3985", RsidParagraphProperties = "005F7E61", RsidRunAdditionDefault = "008B2DA9", ParagraphId = "2562476B", TextId = "454E7663" };
ParagraphProperties paragraphProperties3 = new ParagraphProperties();
ParagraphMarkRunProperties paragraphMarkRunProperties3 = new ParagraphMarkRunProperties();
Languages languages11 = new Languages(){ Val = "en-US" };
paragraphMarkRunProperties3.Append(languages11);
paragraphProperties3.Append(paragraphMarkRunProperties3);
BookmarkStart bookmarkStart1 = new BookmarkStart(){ Name = "_GoBack", Id = "0" };
BookmarkEnd bookmarkEnd1 = new BookmarkEnd(){ Id = "0" };
paragraph3.Append(paragraphProperties3);
paragraph3.Append(bookmarkStart1);
paragraph3.Append(bookmarkEnd1);
SectionProperties sectionProperties1 = new SectionProperties(){ RsidRPr = "005F7E61", RsidR = "00BA3985" };
PageSize pageSize1 = new PageSize(){ Width = (UInt32Value)12240U, Height = (UInt32Value)15840U };
PageMargin pageMargin1 = new PageMargin(){ Top = 1440, Right = (UInt32Value)1440U, Bottom = 1440, Left = (UInt32Value)1440U, Header = (UInt32Value)720U, Footer = (UInt32Value)720U, Gutter = (UInt32Value)0U };
Columns columns1 = new Columns(){ Space = "720" };
DocGrid docGrid1 = new DocGrid(){ LinePitch = 360 };
sectionProperties1.Append(pageSize1);
sectionProperties1.Append(pageMargin1);
sectionProperties1.Append(columns1);
sectionProperties1.Append(docGrid1);
body1.Append(paragraph1);
body1.Append(paragraph2);
body1.Append(paragraph3);
body1.Append(sectionProperties1);
document1.Append(body1);
PS: Even though it's weird that you build table using string format. Use table in your docx from which you create C# code.

To start next sentence in a new line, just add newline ("\r\n" or Environment.NewLine) to the end of each text:
myDoc.Content.Text = "Identified Market/Visitors" + " " + "Museum (as a whole)" + " " + "Percentage" + " " + Environment.NewLine;
myDoc.Content.Text += "2" + " " + "76)" + " " + "25% "+ " " + Environment.NewLine;

Related

Insert text at the start of a document in Word - openXML

I am using OpenXML to manipulate Microsoft Word files (.docx).
I am sending the Word files as memory stream, editing them and then send them back to browser so they open in client office program.
I want to insert text, approximatley 10 lines, at the start of a document which already got content. I am doing it like this;
using (var wordprocessingDocument = WordprocessingDocument.Open(mem, true))
{
Paragraph firstParagraph = wordprocessingDocument.MainDocumentPart.Document.Descendants<Paragraph>().First();
Run run1 = new Run();
Text text1 = new Text();
text1.Text = "Document type: ";
run1.Append(text1);
Run run2 = new Run();
Break break1 = new Break();
run2.Append(break1);
ProofError proofError1 = new ProofError() { Type = ProofingErrorValues.SpellStart };
Run run3 = new Run();
Text text2 = new Text();
text2.Text = "Document ID";
run3.Append(text2);
ProofError proofError2 = new ProofError() { Type = ProofingErrorValues.SpellEnd };
Run run4 = new Run();
Break break2 = new Break();
Text text3 = new Text();
text3.Text = "Document Title";
run4.Append(break2);
run4.Append(text3);
firstParagraph.Append(run1);
firstParagraph.Append(run2);
firstParagraph.Append(proofError1);
firstParagraph.Append(run3);
firstParagraph.Append(proofError2);
firstParagraph.Append(run4);
Paragraph paragraph3 = new Paragraph() { RsidParagraphAddition = "0068718C", RsidParagraphProperties = "0068718C", RsidRunAdditionDefault = "00E1050C" };
Run run5 = new Run();
Text text4 = new Text();
text4.Text = "A";
run5.Append(text4);
Run run6 = new Run() { RsidRunAddition = "00126F2D" };
Text text5 = new Text();
text5.Text = "tlet";
run6.Append(text5);
paragraph3.Append(run5);
paragraph3.Append(run6);
Paragraph paragraph4 = new Paragraph() { RsidParagraphMarkRevision = "0068718C", RsidParagraphAddition = "00E1050C", RsidParagraphProperties = "0068718C", RsidRunAdditionDefault = "00E1050C" };
BookmarkStart bookmarkStart1 = new BookmarkStart() { Name = "_GoBack", Id = "0" };
BookmarkEnd bookmarkEnd1 = new BookmarkEnd() { Id = "0" };
paragraph4.Append(bookmarkStart1);
paragraph4.Append(bookmarkEnd1);
SectionProperties sectionProperties1 = new SectionProperties() { RsidRPr = "0068718C", RsidR = "00E1050C", RsidSect = "000C7A63" };
}
My problem is that if I already got some text from the first line, then my text will be appended after the original text there. How can I push the original content some lines down, and insert my text above?
Use PrependChild instead of Append. Append will always insert at the end of the current element. So if you already have content in the first paragraph your append will put your text at the end of it. You can also insert your text as a new first paragraph by calling Document.PrependChild(firstParagraph)

Add hyperlink with an image in Open xml document

Hi Currently I have added an image to my word document using open xml. I need to add an hyperlink to the image. So when someone click on the image in the document it will take him to the specific web url. How can i achieve this. Please someone help me. Adding the image code is added bellow.
var run1 = new Run();
var picture1 = new Picture();
var shape1 = new Shape() { Id = "_x0000_i1025" + x};
string rId = "rId" + x ;
var imageData1 = new ImageData() { RelationshipId = rId };
shape1.Append(imageData1);
picture1.Append(shape1);
run1.Append(picture1);
mainPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
new System.Uri(matchString, System.UriKind.RelativeOrAbsolute), rId);
DocumentFormat.OpenXml.Wordprocessing.TableRow tr1 = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
DocumentFormat.OpenXml.Wordprocessing.TableCell Name1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph(new Run(new Text(item.FirstName))));
DocumentFormat.OpenXml.Wordprocessing.TableCell Message1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph(run1));
DocumentFormat.OpenXml.Wordprocessing.TableCell Time1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph(new Run(new Text(item.CreatedDate))));
tr1.Append(Name1, Message1, Time1);
table.AppendChild(tr1);
x++;
I found the answer. May this help someone.
var run1 = new Run();
var picture1 = new Picture();
var shape1 = new Shape() { Id = "_x0000_i1025" + x};
string hyperid="hprid_"+x;
var hlink = new Hyperlink() { Id=hyperid, DocLocation=matchString}; ;
hlink.Append(picture1);
string rId = "rId" + x ;
var imageData1 = new ImageData() { RelationshipId = rId };
shape1.Append(imageData1);
picture1.Append(shape1);
run1.Append(hlink);
mainPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
new System.Uri(matchString, System.UriKind.RelativeOrAbsolute), rId);
mainPart.AddHyperlinkRelationship(new Uri(matchString), true, hyperid);
DocumentFormat.OpenXml.Wordprocessing.TableRow tr1 = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
DocumentFormat.OpenXml.Wordprocessing.TableCell Name1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph(new Run(new Text(item.FirstName))));
DocumentFormat.OpenXml.Wordprocessing.TableCell Message1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph(run1));
DocumentFormat.OpenXml.Wordprocessing.TableCell Time1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph(new Run(new Text(item.CreatedDate))));
tr1.Append(Name1, Message1, Time1);
table.AppendChild(tr1);

How do I create a check box in C# using Open XML SDK

I would like to create a certain number of checkbox using Open XML SDK in C#. How would I do that?
Example:
(Checkbox) - Shoes
(Checkbox) - Shirt
The checkbox count also varies. I am reading a template document, then make edits to return. I have something like this so far:
string documentText;
using (StreamReader reader ...)
{
documentText = reader.ReadToEnd();
}
string addClothes = "";
Run newCheckBox = GenerateRun();
foreach(var item in ClothesList)
{
addClothes = item.clothing;
//MY DILEMMA
documentText = documentText.Replace("##clothing##", newCheckBox + addClothes + "NewLine");
}
public Run GenerateRun()
{
Run run1 = new Run() { RsidRunProperties = "004C0D9A", RsidRunAddition = "00850FA5" };
FieldCode fieldCode1 = new FieldCode() { Space = SpaceProcessingModeValues.Preserve };
fieldCode1.Text = " FORMCHECKBOX ";
run1.Append(fieldCode1);
return run1;
}
using the OpenXML SDK i think it goes something like this:
(raw copy/paste - the value of -1636166143 might be way off)
using w14 = DocumentFormat.OpenXml.Office2010.Word
SdtRun sdtRun1 = new SdtRun();
SdtProperties sdtProperties1 = new SdtProperties();
SdtId sdtId1 = new SdtId(){ Val = -1636166143 };
W14.SdtContentCheckBox sdtContentCheckBox1 = new W14.SdtContentCheckBox();
W14.Checked checked1 = new W14.Checked(){ Val = W14.OnOffValues.Zero };
W14.CheckedState checkedState1 = new W14.CheckedState(){ Font = "MS Gothic", Val = "2612" };
W14.UncheckedState uncheckedState1 = new W14.UncheckedState(){ Font = "MS Gothic", Val = "2610" };
sdtContentCheckBox1.Append(checked1);
sdtContentCheckBox1.Append(checkedState1);
sdtContentCheckBox1.Append(uncheckedState1);
sdtProperties1.Append(sdtId1);
sdtProperties1.Append(sdtContentCheckBox1);
SdtContentRun sdtContentRun1 = new SdtContentRun();
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
RunFonts runFonts1 = new RunFonts(){ Hint = FontTypeHintValues.EastAsia, Ascii = "MS Gothic", HighAnsi = "MS Gothic", EastAsia = "MS Gothic" };
runProperties1.Append(runFonts1);
Text text1 = new Text();
text1.Text = "☐";
run1.Append(runProperties1);
run1.Append(text1);
sdtContentRun1.Append(run1);
Any text you want after the checkbox, comes after the above code

Open XML Word C# - Split into Two Columns

I was wondering how would it be possible to split the word document into two columns. The reason why I want to do this is because I want to be able to fit all of the information on one page.
Thank you so much for your help and time!
My Code
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
var margin_size = 100;
PageMargin pargeMargins = new PageMargin();
pargeMargins.Top = margin_size;
pargeMargins.Bottom = margin_size;
SectionProperties sectionProps = new SectionProperties();
sectionProps.Append(pargeMargins);
Body body = mainPart.Document.AppendChild(new Body());
body.Append(sectionProps);
ParagraphProperties paragraphProperties = new ParagraphProperties
(
//new ParagraphStyleId() { Val = "No Spacing" },
new SpacingBetweenLines() { After = "0" }
);
Paragraph para_main = body.AppendChild(new Paragraph(paragraphProperties));
// Creating the Header where the Serial Number will exist
// Serial Number
Run run_mainHeader = para_main.AppendChild(new Run());
RunProperties runProp_mainHeader = new RunProperties(); // Create run properties.
FontSize size_mainHeader = new FontSize();
size_mainHeader.Val = new StringValue("48");
runProp_mainHeader.Append(size_mainHeader);
run_mainHeader.Append(runProp_mainHeader); // Append all of the properties
run_mainHeader.Append(new Text("S/N: " + sn));
// Serial Barcode
Run run_barcode = para_main.AppendChild(new Run());
RunProperties runProp_barcode = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode = new RunFonts(); // Create font
runFontMain_barcode.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode = new FontSize();
size_barcode.Val = new StringValue("48");
runProp_barcode.Append(runFontMain_barcode);
runProp_barcode.Append(size_barcode);
run_barcode.PrependChild<RunProperties>(runProp_barcode);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode.AppendChild(new Text("*" + sn + "*"));
run_barcode.AppendChild(new Break());
// Tube Type
Run run_tubetype = para_main.AppendChild(new Run());
RunProperties runProp_tubetype = new RunProperties(); // Create run properties.
FontSize size_tubetype = new FontSize();
size_tubetype.Val = new StringValue("38");
runProp_tubetype.Append(size_tubetype);
run_tubetype.Append(runProp_tubetype); // Append all of the properties
run_tubetype.Append(new Text("Tube Type: " + forms[0].TubeType + " "));
//run_tubetype.Append(new Break());
// Tube Barcode
Run run_barcode_tube = para_main.AppendChild(new Run());
RunProperties runProp_barcode_tube = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode_tube = new RunFonts(); // Create font
runFontMain_barcode_tube.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode_tube = new FontSize();
size_barcode_tube.Val = new StringValue("48");
runProp_barcode_tube.Append(runFontMain_barcode_tube);
runProp_barcode_tube.Append(size_barcode_tube);
run_barcode_tube.PrependChild<RunProperties>(runProp_barcode_tube);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode_tube.AppendChild(new Text("*" + forms[0].TubeType + "*"));
run_barcode_tube.AppendChild(new Break());
// Goes through all of the forms
foreach (var form in forms)
{
// Set up a header per form
Run run_header = para_main.AppendChild(new Run());
RunProperties runProp_formHeader = new RunProperties();
Bold bold = new Bold();
Underline ul = new Underline() { Val = DocumentFormat.OpenXml.Wordprocessing.UnderlineValues.Single };
FontSize size_formHeader = new FontSize();
size_formHeader.Val = new StringValue("24");
runProp_formHeader.Append(size_formHeader);
runProp_formHeader.Append(bold);
runProp_formHeader.Append(ul);
run_header.AppendChild(new RunProperties(runProp_formHeader));
//run_header.AppendChild(new RunProperties(new Bold(), new Underline()));
string username = form.Username;
string proces_header = form.HeaderTitle;
run_header.AppendChild(new Text(proces_header));
run_header.AppendChild(new Break());
// Goes through all of the fields that each form contains.
for (int i = 0; i < form.FieldList.Count; i++)
{
// Do not need to print out user or serial for each form.
if (!(form.FieldList[i].Token == "SNT"))
{
Run run_data = para_main.AppendChild(new Run());
if (form.FieldList[i].Default)
{
run_data.AppendChild(new Text(form.FieldList[i].Label));
}
else
{
run_data.AppendChild(new Text(form.FieldList[i].Label + " " + form.FieldList[i].Spec + form.FieldList[i].Value));
}
run_data.AppendChild(new Break());
}
}
}
mainPart.Document.Save();
wordDoc.Close();
return "Success";
}
Currently the code prints out everything top-down on one column. And I want it with two columns
You can two or how many columns you want using the Columns Class for the SectionProperties and ParagraphProperties Class
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.columns(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.paragraphproperties(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sectionproperties(v=office.14).aspx
This should do it:
// Add a new main document part.
package.AddMainDocumentPart();
// Create the Document DOM.
package.MainDocumentPart.Document = new Document();
Body bd = package.MainDocumentPart.Document.Body = new Body();
//write a first paragraph on two columns
var paragrap1 = new Paragraph();
var paragraphSectionProperties = new ParagraphProperties(new SectionProperties());
var paragraphColumns = new Columns();
paragraphColumns.EqualWidth = true;
paragraphColumns.ColumnCount = 2;
paragraphSectionProperties.Append(paragraphColumns);
paragrap1.Append(paragraphSectionProperties);
paragrap1.Append(new Run(new Text(str)));
bd.AppendChild(paragrap1);
//write another paragraph without paragraph properties
bd.Append(new Paragraph(new Run(new Text(str))));
//set the body properties default three columns
var sectionProperties = new SectionProperties();
var columns = new Columns();
columns.EqualWidth = true;
columns.ColumnCount = 3;
sectionProperties.Append(columns);
bd.Append(sectionProperties);
package.MainDocumentPart.Document.Save();
You can do it for the complete document with this code:
var sectionProperty = document.Body.Descendants<SectionProperties>().First();
var paragraphColumns = new Columns {EqualWidth = true, ColumnCount = 2};
sectionProperty.Append(paragraphColumns);
Try with..
Word.Application WordApp = new Word.Application();
Word.Document BaseDoc = default(Word.Document);
Word.Document DestDoc = default(Word.Document);
int intNumberOfPages = 0;
string intNumberOfChars = null;
int intPage = 0;
//Word Constants
const var wdGoToPage = 1;
const var wdStory = 6;
const var wdExtend = 1;
const var wdCharacter = 1;
//Show WordApp
WordApp.ShowMe();
//Load Base Document
BaseDoc = WordApp.Documents.Open(Filename);
BaseDoc.Repaginate();
//Loop through pages
intNumberOfPages = BaseDoc.BuiltInDocumentProperties("Number of Pages").value;
intNumberOfChars = BaseDoc.BuiltInDocumentProperties("Number of Characters").value;
for (intPage = 1; intPage <= intNumberOfPages; intPage++) {
if (intPage == intNumberOfPages) {
WordApp.Selection.EndKey(wdStory); }
else {
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.MoveLeft(Unit = wdCharacter, Count = 1);
}
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Copy();
Application.DoEvents();
//Create New Document
DestDoc = WordApp.Documents.Add;
DestDoc.Activate();
WordApp.Selection.Paste();
DestDoc.SaveAs(NewFileName + intPage.ToString + ".doc");
DestDoc.Close();
DestDoc = null;
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Delete();
Application.DoEvents();
}
BaseDoc.Close(false);
BaseDoc = null;
WordApp.Quit();
WordApp = null;

Open XML (Microsoft Word): C# Table Justification

How would I align my table in the middle of the word document in open xml?
Here is my code and I want to align the table in the middle.
Here is my code. I'm trying to use TableJustification, but it seems like its not working
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Run run = new Run();
// Goes through all of the forms
foreach (var form in forms)
{
Table table = new Table();
// Initialize all of the table properties
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 }
)
);
// Align the table to the center
TableJustification justs_center = new TableJustification() { Val = _____ };
table.AppendChild(justs_center);
table.AppendChild<TableProperties>(tblProp);
Paragraph para = body.AppendChild(new Paragraph());
Run run_header = para.AppendChild(new Run());
RunProperties runProps = run_header.AppendChild(new RunProperties(new Bold()));
string username = form.Username;
string proces_header = form.HeaderTitle;
run_header.AppendChild(new Text(proces_header + " | " + username));
for (int i = 0; i < form.FieldList.Count; i++)
{
if (!(form.FieldList[i].Token == "USR" || form.FieldList[i].Token == "SNT"))
{
TableRow tr = new TableRow();
TableCell header_cell = new TableCell();
header_cell.Append(new Paragraph(new Run(new Text(form.FieldList[i].Label + ": " + form.FieldList[i].Value))));
tr.Append(header_cell);
table.Append(tr);
}
}
wordDoc.MainDocumentPart.Document.Body.Append(table);
}
mainPart.Document.Save();
wordDoc.Close();
return "Success";
}
}
Table t = new Table(
new TableProperties(
...
new TableJustification() { Val = TableRowAlignmentValues.Center},
...),
new TableRow(...),
);
Trying to center the table with the accepted answer did not seem to work. I needed to apply the center justification to all of the rows as well
var t = new Table();
var tableProps = new TableProperties();
tableProps.TableJustification = new TableJustification { Val = TableRowAlignmentValues.Center };
t.Append(tableProps);
var row = new TableRow();
var rowProps = new TableRowProperties();
rowProps.Append(new TableJustification { Val = TableRowAlignmentValues.Center });
row.Append(rowProps);
Found using the Open XML Productivity Tool
Actually, you need to apply the center justification to all rows in TableRowProperties only. Even if you don't apply justification in TableProperties, the table will be centered anyway. And I'm interested to find out what is the purpose of justification in TableRowProperties if someone knows.

Categories