Friday, October 10, 2014

Change text in a word file using OpenXML

using (SPSite oSite = new SPSite("SP SITE URL"))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        SPFile oFile = oWeb.GetFile("FILE TEMPLATE URL");
        byte[] byteArray = oFile.OpenBinary();
        using (MemoryStream memStr = new MemoryStream())
        {
            memStr.Write(byteArray, 0, byteArray.Length);
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStr, true))
            {
                Table table = wordDoc.MainDocumentPart.Document.Body.Elements<Table>().First();//find first table
                TableRow row = table.Elements<TableRow>().ElementAt(7);//get the 7th row
                TableCell cell = row.Elements<TableCell>().ElementAt(2);//get the 2nd cell
                Paragraph p = cell.Elements<Paragraph>().First();//1st paragraph
                Run r = p.Elements<Run>().First();//1st run
                Text t = r.Elements<Text>().First();//get the text
                t.Text = "TEXT TO BE UPDATED";//set the text
            }
        }
    }
}

No comments:

Post a Comment