Showing posts with label OpenXML. Show all posts
Showing posts with label OpenXML. Show all posts

Sunday, September 4, 2016

Update tags in Word document with Data using OpenXML

The objective is to replace the specified tags in a word document(.docx) using OpenXml.
Below is a sample of the word document structure

1) Document content:


2) Footer:

The code sample is as follows:

            using (WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\Users\dev5setup\Desktop\DEPT_TEST.docx", true))
            {
                Dictionary<string, string> tagMappings = GetTagMappingsForTemplate();

                IEnumerable<Paragraph> paras = doc.MainDocumentPart.Document.Descendants<Paragraph>();
                foreach (Paragraph para in paras)
                {
                    // get all runs under the paragraph and convert to be array
                    Run[] runArr = para.Descendants<Run>().ToArray();
                    // foreach each run
                    foreach (Run run in runArr)
                    {
                        string modifiedString = "";
                        int count = 0;
                        string innerText = run.InnerText;

                        #region replace tags
                        foreach (KeyValuePair<string, string> mapping in tagMappings)
                        {
                            if (count == 0)
                            {
                                modifiedString = run.InnerText.Replace(mapping.Key, mapping.Value);
                            }
                            else
                            {
                                modifiedString = modifiedString.Replace(mapping.Key, mapping.Value);
                            }                          
                            count++;
                        }
                        #endregion

                        // if the InnerText doesn't modify
                        if (modifiedString != run.InnerText)
                        {
                            Text t = new Text(modifiedString);
                            run.RemoveAllChildren<Text>();
                            run.AppendChild<Text>(t);
                        }
                    }
                }
                doc.MainDocumentPart.Document.Save();
             
                //Update the word document footer section
                FooterPart pp = doc.MainDocumentPart.FooterParts.ElementAt(0);
                IEnumerable<Paragraph> footerParas = pp.Footer.Descendants<Paragraph>();

                foreach (Paragraph footerPara in footerParas)
                {
                    // get all runs under the paragraph and convert to an array
                    Run[] runArr = footerPara.Descendants<Run>().ToArray();
                    // foreach each run
                    foreach (Run run in runArr)
                    {
                        string modifiedString = "";
                        int count = 0;
                        string innerText = run.InnerText;

                        #region replace tags
                        foreach (KeyValuePair<string, string> mapping in tagMappings)
                        {
                            if (count == 0)
                            {
                                modifiedString = run.InnerText.Replace(mapping.Key, mapping.Value);
                            }
                            else
                            {
                                modifiedString = modifiedString.Replace(mapping.Key, mapping.Value);
                            }
                            count++;
                        }
                        #endregion

                        // if the InnerText doesn't modify
                        if (modifiedString != run.InnerText)
                        {
                            Text t = new Text(modifiedString);
                            run.RemoveAllChildren<Text>();
                            run.AppendChild<Text>(t);
                        }
                    }
                }              
            }


Saturday, September 3, 2016

Read a Excel Cell value using OpenXML

//DLL references in the solution
DocumentFormat.OpenXml
Microsoft.Office.Interop.Excel

//using directives
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

//Method      
public string ReadCellValue(string fileName, string sheetName, string addressName)
        {
            string value = null;
         
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
            {
                WorkbookPart myWorkBookPart = document.WorkbookPart;
                Sheet theSheet = myWorkBookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).FirstOrDefault();

                if (theSheet == null)
                {
                    throw new ArgumentException("sheetName");
                }

                WorksheetPart myWorkSheetPart = (WorksheetPart)myWorkBookPart.GetPartById((theSheet.Id));
                Cell targetCell = myWorkSheetPart.Worksheet.Descendants<Cell>().Where(c => c.CellReference == addressName).FirstOrDefault();

                if (targetCell != null)
                {
                    value = targetCell.InnerText;

                    if (targetCell.DataType != null)
                    {
                        switch (targetCell.DataType.Value)
                        {
                            case CellValues.SharedString:

                                var stringTable = myWorkBookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
                                if (stringTable != null)
                                {
                                    value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
                                }
                                break;

                            case CellValues.Boolean:
                                switch (value)
                                {
                                    case "0":
                                        value = "FALSE";
                                        break;
                                    default:
                                        value = "TRUE";
                                        break;
                                }
                                break;
                        }
                    }
                }
            }
            return value;
        }

//Call method parameters sample
ReadCellValue(@"C:\sample\My test workbook.xlsm", "Sheet Name", "E102");