Export data to docx file using Open XML SDK

Date: 8 Feb 2010 Comments: 0

Here’s simple example how can we export some table data to docx file using Open XML SDK. If you are not familiar with Open XML SDK, you can check out first Introduction to Open XML SDK.

In this example:
1) Create some string array that represent table data
2) Create a new Docx file and init it
3) Create styles for the table and fill it with data
4) Fill the table with data
5) Add the table to the document and save the changes

//t some data to export in table
string[][] data = {new string[]{“column 1″, “column 2″, “column 3″, “column 4″, “column 5″},
new string[]{“A”, “B”, “C”, “D”, “E”},
new string[]{“1″, “2″, “3″, “4″, “5″},
new string[]{“Dev”, “The”, “Web”, “dot”, “NET”}
};

/*t create and init a new docx file and
a WordprocessingDocument object to represent it t*/
WordprocessingDocument doc = WordprocessingDocument.Create(“E:\\dox-export.docx”,
WordprocessingDocumentType.Document);

MainDocumentPart mainDocPart = doc.AddMainDocumentPart();
mainDocPart.Document = new Document();
Body body = new Body();
mainDocPart.Document.Append(body);

/*t init the cell border styles t*/
TableCellProperties cellProperties = new TableCellProperties(
new TableCellBorders
{
TopBorder = new TopBorder
{
Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDots),
Size = new UInt32Value((uint)8),
Color = new StringValue(“000000″)
},
RightBorder = new RightBorder
{
Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDots),
Size = new UInt32Value((uint)8),
Color = new StringValue(“000000″)
},
BottomBorder = new BottomBorder
{
Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDots),
Size = new UInt32Value((uint)8),
Color = new StringValue(“000000″)
},
LeftBorder = new LeftBorder
{
Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDots),
Size = new UInt32Value((uint)8),
Color = new StringValue(“000000″)
},
});

/*t fill the string[][] data into
DocumentFormat.OpenXml.Wordprocessing.Table object t*/

Table table = new Table();
for (int i = 0; i < data.Length; ++i)
{
TableRow row = new TableRow();

for (int j = 0; j < data[i].Length; ++j)
{
TableCell cell = new TableCell(cellProperties.Clone() as TableCellProperties);

cell.Append(new Paragraph(
new Run(
new Text(data[i][j])
)));

row.Append(cell);
}

table.Append(row);
}

/*t add some info about the dox export t*/
body.Append(new Paragraph(
new Run(
new Text(“Table exported by DevTheWeb.NET”)
)));

body.Append(table);

/*t don’t forget to save your changes t*/
doc.MainDocumentPart.Document.Save();
doc.Dispose();

That’s all, if we open the dox file, we can see the exported table:

Leave a Reply


Spam protection by WP Captcha-Free