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.
Related
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 :)
I have this code using openxml sdk which generates table in PPT report.
This line is the reason for table style.
tableStyleId.Text = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";
Style is :
I need to change the style and colors but I couldn't find anything for that. Please help.
private D.Table GenerateTable(int projectID, string reportType)
{
// Declare and instantiate table
D.Table table = new D.Table();
// Specify the required table properties for the table
D.TableProperties tableProperties = new D.TableProperties() { FirstRow = true, BandRow = false };
D.TableStyleId tableStyleId = new D.TableStyleId();
tableStyleId.Text = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";
tableProperties.Append(tableStyleId);
D.TableGrid tableGrid1 = new D.TableGrid();
System.Data.DataTable dtData = new System.Data.DataTable();
if (reportType == "projcharter")
{
//tblXBenefit
dtData = GetBenefit(projectID);
// Declare and instantiate tablegrid and colums
//D.TableGrid tableGrid1 = new D.TableGrid();
D.GridColumn gridColumn1 = new D.GridColumn() { Width = 1848000L };
D.GridColumn gridColumn2 = new D.GridColumn() { Width = 648000L };
D.GridColumn gridColumn3 = new D.GridColumn() { Width = 648000L };
D.GridColumn gridColumn4 = new D.GridColumn() { Width = 648000L };
tableGrid1.Append(gridColumn1);
tableGrid1.Append(gridColumn2);
tableGrid1.Append(gridColumn3);
tableGrid1.Append(gridColumn4);
}
table.Append(tableProperties);
table.Append(tableGrid1);
// Instantiate the table header row
D.TableRow tableHRow = new D.TableRow() { Height = 0L };
for (int column = 0; column < dtData.Columns.Count; column++)
{
tableHRow.Append(CreateTextCell(dtData.Columns[column].ToString()));
}
table.Append(tableHRow);
// Instantiate the table data row
for (int row = 0; row < dtData.Rows.Count; row++)
{
// Instantiate the table row
D.TableRow tableRow = new D.TableRow() { Height = 0L };
for (int column = 0; column < dtData.Columns.Count; column++)
{
tableRow.Append(CreateTextCell(dtData.Rows[row][column].ToString()));
}
table.Append(tableRow);
}
return table;
}
Links to previous questions:
create dynamic table in powerpoint using openXML with c# and ASP.net
unable to generate second table in PPT report using openxml
How to ignore/solve "Repair" message from Powerpoint report generated by OpenXML with ASP.net
Solved it.
So what I did was, I created a new ppt > inserted tables with required design manually in it and then saved it as ppt xml (you will see this option in save as).
Open that xml search for tablestyleid and use that value in the code.
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.
Trying to style a table using a predefined style but nothing is working. I've tried with a a newly created document and one created from a saved template. Using the SDK Productivity tool I can see the style is there in the template but it's not being applied. I've tried appended the style or setting it directly and neither seem to work.
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.GetDocument().Body;
Table table = new Table();
TableProperties props = new TableProperties();
TableStyle tableStyle = new TableStyle { Val = "Light Shading Accent 1" };
props.TableStyle = tableStyle;
//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.GetDocument().Save();
}
}
Finally figured it out. I was using the style name and not the style id. So the line where the style is declared should look like:
TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };
I'm creating the table cell as follows:
private static TableCell GetHeaderCell(string cellText)
{
var tc = new TableCell(new Paragraph(new Run(new Text(cellText))));
return tc;
}
I want it to be blue with white text.
I've tried the following, but it doesn't work; when I try to open the document I get an error that there is a problem with the contents:
private static TableCell GetHeaderCell(string cellText)
{
var props = new TableCellProperties();
var solidFill = new SolidFill();
var rgbColorHex = new RgbColorModelHex() { Val = "FF0000" };//Red Background for Single TableCell.
solidFill.Append(rgbColorHex);
props.Append(solidFill);
var paragraph = new Paragraph(new Run(new Text(cellText)));
var tc = new TableCell(paragraph, props);
return tc;
}
The full error is as follows:
This is a two part question:
1) How can I modify the foreground of an OpenXML TableCell
The foreground of an OpenXML TableCell is defined by the properties of a Run, called the RunProperties. To add a color to a run, you have to add the Color object using the Val property.
// Create the RunProperties object for your run
DocumentFormat.OpenXml.Wordprocessing.RunProperties rp =
new DocumentFormat.OpenXml.Wordprocessing.RunProperties();
// Add the Color object for your run into the RunProperties
rp.Append(DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "ABCDEF" });
// Create the Run object
DocumentFormat.OpenXml.WordProcessing.Run run =
new DocumentFormat.OpenXml.WordProcessing.Run();
// Assign your RunProperties to your Run
run.RunProperties = rp;
// Add your text to your Run
run.Append(new Text("My Text"));
See reference question.
2) How can I modify the background of an OpenXML TableCell
The TableCell background can be modified using the TableCellProperties, similar to the above Run, which uses RunProperties. However, you apply a Shading object to your TableCellProperties.
// Create the TableCell object
DocumentFormat.OpenXml.Wordprocessing.TableCell tc =
new DocumentFormat.OpenXml.Wordprocessing.TableCell();
// Create the TableCellProperties object
TableCellProperties tcp = new TableCellProperties(
new TableCellWidth { Type = TableWidthUnitValues.Auto, }
);
// Create the Shading object
DocumentFormat.OpenXml.Wordprocessing.Shading shading =
new DocumentFormat.OpenXml.Wordprocessing.Shading() {
Color = "auto",
Fill = "ABCDEF",
Val = ShadingPatternValues.Clear
};
// Add the Shading object to the TableCellProperties object
tcp.Append(shading);
// Add the TableCellProperties object to the TableCell object
tc.Append(tcp);
// also need to ensure you include the text, otherwise it causes an error (it did for me!)
tc.Append(new Paragraph(new Run(new Text(cellText))));
See reference question.
DocumentFormat.OpenXml.WordProcessingRunProperties rp =
new DocumentFormat.OpenXml.WordProcessingRunProperties();
=
DocumentFormat.OpenXml.WordProcessing.RunProperties rp =
new DocumentFormat.OpenXml.WordProcessing.RunProperties();
??