I am working on a project, which involves with creating data sheet. I have managed to create tables in docx file by following code provided from MSDN, but when I try to apply style (eg. border set to none, shading, cell width, etc.) to the table I created, it wont append on it.
So I assume I have to use table.RemoveAllChildren
then append the new style
. But if I do so, the entire table will be removed and thus I have to re-create the table. There must be a better way of doing it.
Please advise.
The following is a sample code iIhave, with 1 cell table. shaded with dark-blue, I am trying to remove the table border, set cell width and modify text.
public void docHeaderTableVal(string FileLocation, string replacingVal, int tableNum, int rowNum, int cellNum) //replace a value
{
try
{
using (var doc = WordprocessingDocument.Open(FileLocation, true))
{
// Find the first table in the document.
Table table =
doc.MainDocumentPart.Document.Body.Elements<Table>().ElementAt(tableNum);
TableProperties props = new TableProperties(
new TableBorders(
new TopBorder
{
Val = new EnumValue<BorderValues>(BorderValues.None),
//Size = 10
},
new BottomBorder
{
Val = new EnumValue<BorderValues>(BorderValues.None),
//Size = 10
},
new LeftBorder
{
Val = new EnumValue<BorderValues>(BorderValues.None),
//Size = 10
},
new RightBorder
{
Val = new EnumValue<BorderValues>(BorderValues.None),
//Size = 10
},
new InsideHorizontalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.None),
//Size = 10
},
new InsideVerticalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.None),
//Size = 10
}
)
);
table.AppendChild<TableProperties>(props);
TableRow row = table.Elements<TableRow>().ElementAt(rowNum);
TableCell cell = row.Elements<TableCell>().ElementAt(cellNum);
cell.RemoveAllChildren();
//cell.TableCellProperties.TableCellWidth.Width = "2500";
//finding first run and its first text then replace with passed-in text.
Paragraph p = new Paragraph() { RsidParagraphAddition = "004F7104", RsidParagraphProperties = "008F2986", RsidRunAdditionDefault = "004F7104" };
ParagraphProperties pPr = new ParagraphProperties();
Justification just1 = new Justification() { Val = JustificationValues.Center };
pPr.Append(just1);
Run r = new Run();
RunProperties rProp = new RunProperties(); //making an instance of run property
RunFonts rFont = new RunFonts();
FontSize size = new FontSize();
Color color = new Color() { Val = "#FFFFFF"};
Bold bld = new Bold();
Italic italic = new Italic();
rFont.Ascii = "Arial Black";
size.Val = new StringValue("32");
rProp.Append(rFont, size, color, bld, italic);
r.PrependChild<RunProperties>(rProp);
Text t = new Text(replacingVal);
r.Append(t);
p.Append(pPr);
p.Append(r);
//back ground shading for the title cell;
cell.AppendChild(new TableCellProperties(new Shading { Val = ShadingPatternValues.Clear, Color = "auto", Fill = "##17365d" }));
cell.Append(p);
}
}
catch
{
MessageBox.Show("Can not replace table value due to file open error.");
}
}