Can not add bullets for word using OpenXml - openxml

My expected result is:
Hello
world!
but when i using below codes:
MainDocumentPart mainDocumentPart =
package.AddMainDocumentPart();
DocumentFormat.OpenXml.Wordprocessing.Document elementW =
new DocumentFormat.OpenXml.Wordprocessing.Document(
new Body(
new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
new NumberingProperties(
new NumberingLevelReference() { Val = 0 },
new NumberingId() { Val = 1 })
),
new Run(
new RunProperties(),
new Text("Hello, ") { Space = new DocumentFormat.OpenXml.EnumValue<DocumentFormat.OpenXml.SpaceProcessingModeValues> { InnerText = "preserve" } })),
new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
new ParagraphProperties(
new NumberingProperties(
new NumberingLevelReference() { Val = 0 },
new NumberingId() { Val = 1 })),
new Run(
new RunProperties(),
new Text("world!")
{
Space = new DocumentFormat.OpenXml.EnumValue<DocumentFormat.OpenXml.SpaceProcessingModeValues> { InnerText = "preserve" }
})));
elementW.Save(mainDocumentPart);
Result is:
Hello
world!
How can i get my expected result?

I realize this is far too late but maybe it can help others with the same question. The marked answer (by amurra) doesn't actually achieve the desired result. It simply creates a document with the list as content, just more completely than you. What you have added to the main document part is fine.
In the XML format, list items are defined as paragraphs with an indentation level and a numbering ID. This ID references the numbering rules defined in the NumberingDefinitionsPart of the document.
In your case, because you've set the numbering ID to be 1, the following code would map that ID of 1 to reflect a bulleted list as desired. Note the NumberingFormat and LevelText objects inside the Level object. These are the key components for your formatting.
NumberingDefinitionsPart numberingPart =
mainDocumentPart.AddNewPart<NumberingDefinitionsPart>("myCustomNumbering");
Numbering numElement = new Numbering(
new AbstractNum(
new Level(
new NumberingFormat() { Val = NumberFormatValues.Bullet },
new LevelText() { Val = "ยท" }
) { LevelIndex = 0 }
) { AbstractNumberId = 0 },
new NumberingInstance(
new AbstractNumId(){ Val = 0 }
){ NumberID = 1 }
);
numElement.Save(numberingPart);
For more information, check out the documentation for all the related classes on the Wordprocessing Namespace on MSDN, or the Working With Numbering markup article.

This should create you a blank document with your expected output:
// Creates an Document instance and adds its children.
public Document GenerateDocument()
{
Document document1 = new Document();
document1.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006");
document1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
document1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
document1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
document1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
document1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
document1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
document1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
document1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
Body body1 = new Body();
Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "00AF4948", RsidParagraphProperties = "00625634", RsidRunAdditionDefault = "00625634" };
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId(){ Val = "ListParagraph" };
NumberingProperties numberingProperties1 = new NumberingProperties();
NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference(){ Val = 0 };
NumberingId numberingId1 = new NumberingId(){ Val = 1 };
numberingProperties1.Append(numberingLevelReference1);
numberingProperties1.Append(numberingId1);
paragraphProperties1.Append(paragraphStyleId1);
paragraphProperties1.Append(numberingProperties1);
Run run1 = new Run();
Text text1 = new Text();
text1.Text = "Hello";
run1.Append(text1);
paragraph1.Append(paragraphProperties1);
paragraph1.Append(run1);
Paragraph paragraph2 = new Paragraph(){ RsidParagraphAddition = "00625634", RsidParagraphProperties = "00625634", RsidRunAdditionDefault = "00625634" };
ParagraphProperties paragraphProperties2 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId2 = new ParagraphStyleId(){ Val = "ListParagraph" };
NumberingProperties numberingProperties2 = new NumberingProperties();
NumberingLevelReference numberingLevelReference2 = new NumberingLevelReference(){ Val = 0 };
NumberingId numberingId2 = new NumberingId(){ Val = 1 };
numberingProperties2.Append(numberingLevelReference2);
numberingProperties2.Append(numberingId2);
paragraphProperties2.Append(paragraphStyleId2);
paragraphProperties2.Append(numberingProperties2);
Run run2 = new Run();
Text text2 = new Text();
text2.Text = "world!";
run2.Append(text2);
paragraph2.Append(paragraphProperties2);
paragraph2.Append(run2);
SectionProperties sectionProperties1 = new SectionProperties(){ RsidR = "00625634", RsidSect = "00AF4948" };
HeaderReference headerReference1 = new HeaderReference(){ Type = HeaderFooterValues.Even, Id = "rId7" };
HeaderReference headerReference2 = new HeaderReference(){ Type = HeaderFooterValues.Default, Id = "rId8" };
FooterReference footerReference1 = new FooterReference(){ Type = HeaderFooterValues.Even, Id = "rId9" };
FooterReference footerReference2 = new FooterReference(){ Type = HeaderFooterValues.Default, Id = "rId10" };
HeaderReference headerReference3 = new HeaderReference(){ Type = HeaderFooterValues.First, Id = "rId11" };
FooterReference footerReference3 = new FooterReference(){ Type = HeaderFooterValues.First, Id = "rId12" };
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(headerReference1);
sectionProperties1.Append(headerReference2);
sectionProperties1.Append(footerReference1);
sectionProperties1.Append(footerReference2);
sectionProperties1.Append(headerReference3);
sectionProperties1.Append(footerReference3);
sectionProperties1.Append(pageSize1);
sectionProperties1.Append(pageMargin1);
sectionProperties1.Append(columns1);
sectionProperties1.Append(docGrid1);
body1.Append(paragraph1);
body1.Append(paragraph2);
body1.Append(sectionProperties1);
document1.Append(body1);
return document1;
}

Related

OpenXML Excel C# Update Stylesheet and add new Style to existing Stylesheet

I need to add another style to an existing stylesheet. I created this style using the OpenXML Productivity Tools. Unfortunately I can't manage to add this style to the existing stylesheet. The stylesheet is always overwritten. Do I need to adjust the counts (borders, fills, etc)? Or is there a better way?
void AppendStylesToStylesheet(WorkbookStylesPart workbookStylesPart)
{
var styleSheet = workbookStylesPart.Stylesheet;
var fonts1 = new Fonts { Count = 1U, KnownFonts = true };
var font1 = new Font();
font1.Append(new FontSize { Val = 11D });
font1.Append(new Color { Theme = 1U });
font1.Append(new FontName { Val = "Calibri" });
font1.Append(new FontFamilyNumbering { Val = 2 });
font1.Append(new FontScheme { Val = FontSchemeValues.Minor });
fonts1.Append(font1);
var fills1 = new Fills { Count = 3U };
var fill1 = new Fill();
fill1.Append(new PatternFill { PatternType = PatternValues.None });
var fill2 = new Fill();
fill2.Append(new PatternFill { PatternType = PatternValues.Gray125 });
var fill3 = new Fill();
var patternFill3 = new PatternFill { PatternType = PatternValues.Solid };
patternFill3.Append(new ForegroundColor { Theme = 0U, Tint = -4.9989318521683403E-2D });
patternFill3.Append(new BackgroundColor { Indexed = 64U });
fill3.Append(patternFill3);
fills1.Append(fill1);
fills1.Append(fill2);
fills1.Append(fill3);
var borders1 = new Borders { Count = 2U };
var border1 = new Border();
var leftBorder1 = new LeftBorder();
var rightBorder1 = new RightBorder();
var topBorder1 = new TopBorder();
var bottomBorder1 = new BottomBorder();
var diagonalBorder1 = new DiagonalBorder();
border1.Append(leftBorder1);
border1.Append(rightBorder1);
border1.Append(topBorder1);
border1.Append(bottomBorder1);
border1.Append(diagonalBorder1);
var border2 = new Border();
var leftBorder2 = new LeftBorder();
var rightBorder2 = new RightBorder();
var topBorder2 = new TopBorder { Style = BorderStyleValues.Dotted };
topBorder2.Append(new Color { Theme = 0U, Tint = -0.24994659260841701D });
var bottomBorder2 = new BottomBorder { Style = BorderStyleValues.Dotted };
bottomBorder2.Append(new Color { Theme = 0U, Tint = -0.24994659260841701D });
var diagonalBorder2 = new DiagonalBorder();
border2.Append(leftBorder2);
border2.Append(rightBorder2);
border2.Append(topBorder2);
border2.Append(bottomBorder2);
border2.Append(diagonalBorder2);
borders1.Append(border1);
borders1.Append(border2);
var cellStyleFormats1 = new CellStyleFormats { Count = 1U };
cellStyleFormats1.Append(new CellFormat { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U });
var cellFormats1 = new CellFormats { Count = 3U };
var cellFormat2 = new CellFormat { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U };
var cellFormat3 = new CellFormat { NumberFormatId = 14U, FontId = 0U, FillId = 2U, BorderId = 1U, FormatId = 0U, ApplyNumberFormat = true, ApplyFill = true, ApplyBorder = true, ApplyAlignment = true };
var alignment1 = new Alignment { Vertical = VerticalAlignmentValues.Center };
cellFormat3.Append(alignment1);
var cellFormat4 = new CellFormat { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U, ApplyAlignment = true };
var alignment2 = new Alignment { Vertical = VerticalAlignmentValues.Center };
cellFormat4.Append(alignment2);
cellFormats1.Append(cellFormat2);
cellFormats1.Append(cellFormat3);
cellFormats1.Append(cellFormat4);
var cellStyles1 = new CellStyles { Count = 1U };
var cellStyle1 = new CellStyle { Name = "Standard", FormatId = 0U, BuiltinId = 0U };
cellStyles1.Append(cellStyle1);
var differentialFormats1 = new DifferentialFormats { Count = 0U };
var tableStyles1 = new TableStyles { Count = 0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" };
var colors1 = new Colors();
var mruColors1 = new MruColors();
var color4 = new Color { Rgb = "FFFFFFCC" };
mruColors1.Append(color4);
colors1.Append(mruColors1);
var stylesheetExtensionList1 = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
var slicerStyles1 = new X14.SlicerStyles { DefaultSlicerStyle = "SlicerStyleLight1" };
stylesheetExtension1.Append(slicerStyles1);
var stylesheetExtension2 = new StylesheetExtension { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" };
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
var timelineStyles1 = new X15.TimelineStyles { DefaultTimelineStyle = "TimeSlicerStyleLight1" };
stylesheetExtension2.Append(timelineStyles1);
stylesheetExtensionList1.Append(stylesheetExtension1);
stylesheetExtensionList1.Append(stylesheetExtension2);
styleSheet.Append(fonts1);
styleSheet.Append(fills1);
styleSheet.Append(borders1);
styleSheet.Append(cellStyleFormats1);
styleSheet.Append(cellFormats1);
styleSheet.Append(cellStyles1);
styleSheet.Append(differentialFormats1);
styleSheet.Append(tableStyles1);
styleSheet.Append(colors1);
styleSheet.Append(stylesheetExtensionList1);
styleSheet.Save();
}

How can embed a excel file to PowerPoint file by OpenXML?

I want embed a excel file to powerpoint file:
I had try this code, but it can't add object:
// Open the source document as read/write.
using (var presentationDocument = PresentationDocument.Open(strFile, true))
{
var presentationPart = presentationDocument.PresentationPart;
var newSlidePart = GetSlidePartsInOrder( presentationPart).Last();
string datafile = #"F:\AUTOM\t1.xlsx";
ShapeTree tree = newSlidePart.Slide.CommonSlideDatShapeTree;
GraphicFrame graphicFrame = new GraphicFrame();
var embedId = "rId" + (newSlidePart.Slide.Elements().Count() + 1915);
var nonVisualPictureProperties = new NonVisualGraphicFrameProperties(
new NonVisualDrawingProperties { Id = (UInt32Value)4U, Name = "Chart 3" },
new NonVisualGraphicFrameDrawingProperties(),
new ApplicationNonVisualDrawingProperties());
var blipFill = new BlipFill();
var blip = new Blip { Embed = embedId };
// Creates an BlipExtensionList instance and adds its children
var blipExtensionList = new BlipExtensionList();
var blipExtension = new BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1D}" };
var useLocalDpi = new UseLocalDpi { Val = false };
useLocalDpi.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
blipExtension.Append(useLocalDpi);
blipExtensionList.Append(blipExtension);
bliAppend(blipExtensionList);
var stretch = new Stretch();
var fillRectangle = new FillRectangle();
stretch.Append(fillRectangle);
blipFill.Append(blip);
blipFill.Append(stretch);
// Create new Embedded Package Part
EmbeddedPackagePart embPackage = newSlidePart.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", embedId);
// Feed imported data from an excel file into the embedded package
embPackage.FeedData(new FileStream(datafile, FileMode.Open, FileAccess.ReadWrite));
var aspectRatio = 1;
// Compute the image's offset on the page (in x and y), and its width cx and height cy.
// Note that sizes are expressed in EMU (English Metric Units)
// const int emusPerCm = 360000;
var cy = 5029200L;
var cx = (long)(cy * aspectRatio);
if (cx > 8229600L)
{
cx = 8229600L;
cy = (long)(cx / aspectRatio);
}
// Creates an ShapeProperties instance and adds its children.
var shapeProperties = new ShapeProperties();
var transform2D = new Transform2D();
var offset = new Offset { X = (9144000L - cx) / 2, Y = 1524000L };
var extents = new Extents { Cx = cx, Cy = cy };
transform2D.Append(offset);
transform2D.Append(extents);
var presetGeometry = new PresetGeometry { Preset = ShapeTypeValues.Rectangle };
var adjustValueList = new AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(transform2D);
shapeProperties.Append(presetGeometry);
graphicFrame.Append(nonVisualPictureProperties);
graphicFrame.Append(blipFill);
graphicFrame.Append(shapeProperties);
tree.AppendChild(graphicFrame);
// Save the modified presentation.
presentationPart.Presentation.Save();
}
How can embed a excel file to PowerPoint file by OpenXML?

Need more efficient way to convert Entities to DataTable

So, I have a method that converts entities into a DataTable. The only problem is it is very slow. I made sure to call .ToList() on the IQueryable to make it go ahead and load before processing the results into a DataTable. It takes hardly any time to load the 3000+ rows into memory. However, the real time slayer is in the following iteration in the method:
foreach (var index in imgLeaseIndexes)
{
DataRow dataRow = dataTable.NewRow();
dataRow["StateCode"] = index.StateCode;
dataRow["CountyCode"] = index.CountyCode;
dataRow["EntryNumber"] = index.EntryNumber;
dataRow["Volume"] = index.Volume;
dataRow["Page"] = index.Page;
dataRow["PageCount"] = index.ImgLocation.PageCount;
dataRow["CreateDate"] = index.ImgLocation.CreateDate;
dataTable.Rows.Add(dataRow);
}
And here is the complete method, for what it's worth:
private DataTable buildImgLeaseIndexDataTable(List<ImgLeaseIndex> imgLeaseIndexes)
{
var dataTable = new DataTable();
var dataColumns = new List<DataColumn>();
var tdiReportProperties =
new List<string>() { "StateCode", "CountyCode", "EntryNumber", "Volume", "Page", "PageCount", "CreateDate" };
Type imgLeaseIndexType = imgLeaseIndexes.FirstOrDefault().GetType();
PropertyInfo[] imgLeaseIndexPropertyInfo = imgLeaseIndexType.GetProperties();
dataColumns.AddRange(
(from propertyInfo in imgLeaseIndexPropertyInfo
where tdiReportProperties.Contains(propertyInfo.Name)
select new DataColumn()
{
ColumnName = propertyInfo.Name,
DataType = (propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) ?
propertyInfo.PropertyType.GetGenericArguments()[0] : propertyInfo.PropertyType
})
.ToList());
Type imgLocationType = imgLeaseIndexes.FirstOrDefault().ImgLocation.GetType();
PropertyInfo[] imgLocationPropertyInfo = imgLocationType.GetProperties();
dataColumns.AddRange(
(from propertyInfo in imgLocationPropertyInfo
where tdiReportProperties.Contains(propertyInfo.Name)
select new DataColumn()
{
ColumnName = propertyInfo.Name,
DataType = (propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) ?
propertyInfo.PropertyType.GetGenericArguments()[0] : propertyInfo.PropertyType
})
.ToList());
dataTable.Columns.AddRange(dataColumns.ToArray());
foreach (var index in imgLeaseIndexes)
{
DataRow dataRow = dataTable.NewRow();
dataRow["StateCode"] = index.StateCode;
dataRow["CountyCode"] = index.CountyCode;
dataRow["EntryNumber"] = index.EntryNumber;
dataRow["Volume"] = index.Volume;
dataRow["Page"] = index.Page;
dataRow["PageCount"] = index.ImgLocation.PageCount;
dataRow["CreateDate"] = index.ImgLocation.CreateDate;
dataTable.Rows.Add(dataRow);
}
return dataTable;
}
Does anyone have ideas on how I can make this more efficient and why it is so slow as is?
UPDATE:
I removed the reflection and explicitly set the data columns at compile time per the feedback I've received so far, but it is still really slow. This is what the updated code looks like:
private DataTable buildImgLeaseIndexDataTable(List<ImgLeaseIndex> imgLeaseIndexes)
{
var dataTable = new DataTable();
var stateCodeDataColumn = new DataColumn();
stateCodeDataColumn.ColumnName = "StateCode";
stateCodeDataColumn.Caption = "State Code";
stateCodeDataColumn.DataType = typeof(Int16);
dataTable.Columns.Add(stateCodeDataColumn);
var countyCodeDataColumn = new DataColumn();
countyCodeDataColumn.ColumnName = "CountyCode";
countyCodeDataColumn.Caption = "County Code";
countyCodeDataColumn.DataType = typeof(Int16);
dataTable.Columns.Add(countyCodeDataColumn);
var entryNumberDataColumn = new DataColumn();
entryNumberDataColumn.ColumnName = "EntryNumber";
entryNumberDataColumn.Caption = "Entry Number";
entryNumberDataColumn.DataType = typeof(string);
dataTable.Columns.Add(entryNumberDataColumn);
var volumeDataColumn = new DataColumn();
volumeDataColumn.ColumnName = "Volume";
volumeDataColumn.DataType = typeof(string);
dataTable.Columns.Add(volumeDataColumn);
var pageDataColumn = new DataColumn();
pageDataColumn.ColumnName = "Page";
pageDataColumn.DataType = typeof(string);
dataTable.Columns.Add(pageDataColumn);
var pageCountDataColumn = new DataColumn();
pageCountDataColumn.ColumnName = "PageCount";
pageCountDataColumn.Caption = "Page Count";
pageCountDataColumn.DataType = typeof(string);
dataTable.Columns.Add(pageCountDataColumn);
var createDateDataColumn = new DataColumn();
createDateDataColumn.ColumnName = "CreateDate";
createDateDataColumn.Caption = "Create Date";
createDateDataColumn.DataType = typeof(DateTime);
dataTable.Columns.Add(createDateDataColumn);
foreach (var index in imgLeaseIndexes)
{
DataRow dataRow = dataTable.NewRow();
dataRow["StateCode"] = index.StateCode;
dataRow["CountyCode"] = index.CountyCode;
dataRow["EntryNumber"] = index.EntryNumber;
dataRow["Volume"] = index.Volume;
dataRow["Page"] = index.Page;
dataRow["PageCount"] = index.ImgLocation.PageCount;
dataRow["CreateDate"] = index.ImgLocation.CreateDate;
dataTable.Rows.Add(dataRow);
}
return dataTable;
}
Any ideas on what else might be causing this?
UPDATE 2:
So it looks like other people have had this problem - specific to creating and setting the DataRows. My co-worker came across this:
The DataRow value setter is slow!
I'm going to try some of the stuff suggested in the link.
As Thiago mentioned in the comments the problem is the use of reflection.
The reflection part is where you are using PropertyInfo. You are getting the structure of the data types at runtime. But these are known at compile time.

Open XML: Convert a Paragraph to simple HTML

I have a Paragraph object and wish to convert the inner text it contains into HTML fragments.
I use the Open XML SDK 2.0 from Microsoft.
[Test]
public void GetHTMLOutOfParagraphsWithoutHeadingInformation()
{
var paragraphs = new List<Paragraph>();
StyleDefinitionsPart styles = null;
// Open the file read-only since we don't need to change it.
using (var wordprocessingDocument = WordprocessingDocument.Open(documentFileName, true))
{
paragraphs = wordprocessingDocument.MainDocumentPart.Document.Body
.OfType<Paragraph>().ToList();
styles = wordprocessingDocument.MainDocumentPart.StyleDefinitionsPart;
foreach (var p in paragraphs)
{
using (var memoryStream = new MemoryStream())
{
var doc = WordprocessingDocument.Create(memoryStream, WordprocessingDocumentType.Document);
doc.AddMainDocumentPart().AddPart(styles);
doc.MainDocumentPart.Document = new Document();
doc.MainDocumentPart.Document.Body = new Body();
doc.MainDocumentPart.Document.Body.Append(p.CloneNode(true));
doc.MainDocumentPart.Document.Save();
Console.WriteLine(GetHTMLOfDoc(doc));
}
}
}
}
string GetHTMLOfDoc(WordprocessingDocument doc)
{
HtmlConverterSettings settings = new HtmlConverterSettings()
{
PageTitle = "Test Title",
CssClassPrefix = "Pt",
Css = "",
ConvertFormatting = false,
};
XElement html = HtmlConverter.ConvertToHtml(doc, settings);
var notNullAnyMore = html.XPathSelectElement("//*[local-name() = 'body']");
return notNullAnyMore.ToStringNewLineOnAttributes();
}
}

Fix the cell width in Word using Open XML SDK

I have a table with one row in a docx file and I want to add some rows. For the first existing row I set the GridSpan to 3. In the next one I want add a row only with two cell, then I have the result as on the picture. How can I fix the new row width to the table width? The same I want to do, when I add only a one cell in the new row.
My code:
private static TableRow AddRow(WordprocessingDocument docx, Table tbl, int cellsQuantity)
{
TableRow newRow = new TableRow();
var firstCell = tbl.Descendants<TableRow>().First()
.Descendants<TableCell>().First();
firstCell.Append(new TableCellProperties(new GridSpan() { Val = 3 }));
for (int i = 0, max = cellsQuantity; i < max; i++)
{
// TableCellProperties tcp = new TableCellProperties(new TableCellWidth() { Width = firstCell.TableCellProperties.TableCellWidth.Width, Type = firstCell.TableCellProperties.TableCellWidth.Type });
TableCell cell = new TableCell(new Paragraph(new Run(new Text("test"))));
newRow.AppendChild(cell);
}
tbl.Append(newRow);
return newRow;
}
Ok, I thing I got it :)
private static TableRow AddRow(WordprocessingDocument docx, Table tbl, int cellsQuantity)
{
TableRow newRow = new TableRow();
var grid = tbl.Descendants<TableGrid>().First();
var firstCell = tbl.Descendants<TableRow>().First()
.Descendants<TableCell>().First();
firstCell.Append(new TableCellProperties(new GridSpan() { Val = 4 }));
int ind = 0;
int[] widthPerColumn = new int[] { 3070, 1536, 1535, 3071 };
grid.Descendants<GridColumn>().ToList().ForEach(x =>
{
x.Width = widthPerColumn[ind++].ToString();
});
int[] gridSpan = null;
switch (cellsQuantity)
{
case 4:
gridSpan = new int[] { 1, 1, 1, 1 };
break;
case 3:
gridSpan = new int[] { 1, 2, 1 };
break;
case 2:
gridSpan = new int[] { 2, 2 };
break;
case 1:
gridSpan = new int[] { 4 };
break;
default:
throw new InvalidOperationException("The cellsQuantity variable must have a value from [1,4] range");
}
for (int i = 0, max = cellsQuantity; i < max; i++)
{
TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = gridSpan[i] });
TableCell cell = new TableCell(tcp, new Paragraph(new Run(new Text("test"))));
newRow.AppendChild(cell);
}
tbl.Append(newRow);
return newRow;
}
TableCell tCell = new TableCell();
tCell.Append(new TableCellProperties(
new GridSpan { Val = table.LastChild.ChildElements.Count },
new Justification { Val = JustificationValues.Right })
);