Exemple #1
0
        /// <summary>
        /// Get ContentControl from a ContentControl
        /// </summary>
        /// <param name="pBlock">Root Content Control</param>
        /// <param name="pTag">ContentControl tag to find</param>
        /// <returns>The ContentControl</returns>
        public static SdtBlock GetContentControl(SdtBlock pBlock, string pTag)
        {
            SdtBlock cc = pBlock.Descendants<SdtBlock>().Where
                      (r => r.SdtProperties.GetFirstChild<Tag>().Val == pTag).Single();

            return cc;
        }
Exemple #2
0
        /// <summary>
        /// Get the DocumentFormat.OpenXml.Wordprocessing.Table from the tag
        /// </summary>
        public DocumentFormat.OpenXml.Wordprocessing.Table GetTable(string tag)
        {
            string           tblTag   = "StockTableTag";
            MainDocumentPart mainPart = Document.MainDocumentPart;
            //StockService.baseDS.stockCodeDataTable tbl = Gateway.PriceData.getPriceDataToDay();
            SdtBlock ccWithTable = mainPart.Document.Body.Descendants <SdtBlock>().Where
                                       (r => r.SdtProperties.GetFirstChild <Tag>().Val == tblTag).Single();

            // This should return only one table.
            DocumentFormat.OpenXml.Wordprocessing.Table theTable = ccWithTable.Descendants <DocumentFormat.OpenXml.Wordprocessing.Table>().Single();
            return(theTable);
        }
Exemple #3
0
 public static void replacePicture(string filePath)
 {
     using (WordprocessingDocument doc =
                WordprocessingDocument.Open(filePath, true))
     {
         SdtBlock cc = doc.MainDocumentPart.Document.Body.Descendants <SdtBlock>()
                       .FirstOrDefault(c =>
         {
             SdtProperties p = c.Elements <SdtProperties>().FirstOrDefault();
             if (p != null)
             {
                 // Is it a picture content control?
                 SdtContentPicture pict =
                     p.Elements <SdtContentPicture>().FirstOrDefault();
                 // Get the alias.
                 SdtAlias a = p.Elements <SdtAlias>().FirstOrDefault();
                 if (pict != null)
                 {
                     return(true);
                 }
             }
             return(false);
         });
         string embed = null;
         if (cc != null)
         {
             Drawing dr = cc.Descendants <Drawing>().FirstOrDefault();
             if (dr != null)
             {
                 Blip blip = dr.Descendants <Blip>().FirstOrDefault();
                 if (blip != null)
                 {
                     embed = blip.Embed;
                 }
             }
         }
         if (embed != null)
         {
             IdPartPair idpp = doc.MainDocumentPart.Parts
                               .Where(pa => pa.RelationshipId == embed).FirstOrDefault();
             if (idpp != null)
             {
                 ImagePart ip = (ImagePart)idpp.OpenXmlPart;
                 using (FileStream fileStream =
                            File.Open("test.png", FileMode.Open))
                     ip.FeedData(fileStream);
             }
         }
     }
 }
        public void AnalyseReport(WordprocessingDocument wordDoc)
        {
            wDoc = wordDoc;
            //PROCESSING STRING EXPRESSION IN WORD
            this.SearchAndReplace(wordDoc, "", "", true);

            //PROCESSING StockTable_Tag
            string           tblTag   = "StockTable_Tag";
            MainDocumentPart mainPart = wordDoc.MainDocumentPart;
            //StockService.baseDS.stockCodeDataTable tbl = Gateway.PriceData.getPriceDataToDay();
            SdtBlock ccWithTable = mainPart.Document.Body.Descendants <SdtBlock>().Where
                                       (r => r.SdtProperties.GetFirstChild <Tag>().Val == tblTag).Single();

            // This should return only one table.
            Table theTable = ccWithTable.Descendants <Table>().Single();
            // Get the last row in the table.
            TableRow theRow = theTable.Elements <TableRow>().Last();

            StockReport stockReport = StockReport.getInstance();

            databases.tmpDS.dataVarrianceDataTable tbl = stockReport.TopBiggestChangeTable();
            foreach (databases.tmpDS.dataVarrianceRow item in tbl.Rows)
            {
                try
                {
                    TableRow rowCopy = (TableRow)theRow.CloneNode(true);
                    rowCopy.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                              (new Run(new Text(item.code.ToString()))));
                    rowCopy.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                              (new Run(new Text(String.Format("{0:0,0}", item.val1 * 1000) + " VNĐ"))));
                    rowCopy.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                              (new Run(new Text(String.Format("{0:0,0}", item.val2 * 1000) + " VNĐ"))));
                    rowCopy.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                              (new Run(new Text(String.Format("{0:0,0}", item.value * 1000) + " VNĐ"))));
                    rowCopy.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                              (new Run(new Text((item.percent / 100).ToString("P")))));
                    theTable.AppendChild(rowCopy);
                }
                catch (Exception ex)
                {
                    continue;
                }
            }
            theTable.RemoveChild(theRow);
        }
Exemple #5
0
        public static void FillTextBox(this SdtBlock sdtBlock, string newText)
        {
            // Get Textbox content
            SdtContentBlock content = sdtBlock.Descendants <SdtContentBlock>().FirstOrDefault();

            if (content != null)
            {
                // Retrieve old paragraph to get the current style of text
                Paragraph oldParagraph = content.Elements <Paragraph>().FirstOrDefault();

                // Create a new text
                var paragraph = CreateParagraph(oldParagraph, newText);

                // Replace old text with new one
                if (oldParagraph != null)
                {
                    content.ReplaceChild(paragraph, oldParagraph);
                }
                else
                {
                    content.Append(paragraph);
                }
            }
        }
Exemple #6
0
        public void Update(DocumentFormat.OpenXml.Wordprocessing.Tag tag, DataView dataView, bool?completePage, int?linesInPage, MainDocumentPart mainPart)
        {
            // This should return only one table.
            SdtBlock sdtBlock = tag.Ancestors <SdtBlock>().Single();

            Table theTable = sdtBlock.Descendants <Table>().Single();

            var tableRows = theTable.Elements <TableRow>().ToList();


            TableRow theRow    = tableRows.Last();
            TableRow headerRow = tableRows.First();

            Orientation orientation = theRow.InnerText.ToLower().StartsWith("v") ? Orientation.Vertical : Orientation.Horizontal;

            for (int i = tableRows.Count() - 1; i >= 1; i--)
            {
                TableRow row = tableRows[i];

                theTable.RemoveChild(row);
            }


            var rowCells = theRow.Descendants <TableCell>().ToList();

            for (int j = 0; j < rowCells.Count; j++)
            {
                //TableCell cell = rowCells[j];
                theRow.Descendants <TableCell>().ElementAt(j).RemoveAllChildren <Paragraph>();
            }

            var headerCells = headerRow.Descendants <TableCell>().ToList();


            int totaLines = 0;

            int rowCount = 0;

            if (orientation == Orientation.Horizontal)
            {
                foreach (DataRowView row in dataView)
                {
                    TableRow rowCopy = (TableRow)theRow.CloneNode(true);

                    for (int j = 0; j < headerCells.Count; j++)
                    {
                        //TableCell cell = headerCells[j];
                        //string value = string.Empty;
                        //value = row.Row[j].ToString();
                        //rowCopy.Descendants<TableCell>().ElementAt(j).Append(new Paragraph
                        //(new Run(new Text(value))));
                        rowCopy.Descendants <TableCell>().ElementAt(j).Append(GetElement(dataView, row.Row, j, mainPart));
                    }

                    theTable.AppendChild(rowCopy);
                    rowCount++;

                    if (completePage.HasValue && completePage.Value && linesInPage.HasValue)
                    {
                        totaLines += GetRowLines(theTable, rowCopy);
                    }
                }
            }
            else
            {
                foreach (DataRowView row in dataView)
                {
                    for (int j = 0; j < headerCells.Count; j++)
                    {
                        TableRow rowCopy = (TableRow)theRow.CloneNode(true);

                        rowCopy.Descendants <TableCell>().ElementAt(0).Append(GetElement(dataView, row.Row, j, mainPart));
                        rowCopy.Descendants <TableCell>().ElementAt(1).Append(new Paragraph(new Run(new Text(""))));

                        theTable.AppendChild(rowCopy);
                        rowCount++;

                        if (completePage.HasValue && completePage.Value && linesInPage.HasValue)
                        {
                            totaLines += GetRowLines(theTable, rowCopy);
                        }
                    }
                }
            }


            //if (orientation == Orientation.Horizontal)
            //{
            if (completePage.HasValue && completePage.Value && linesInPage.HasValue)
            {
                for (int i = totaLines % linesInPage.Value; i < linesInPage.Value; i++)
                {
                    TableRow rowCopy = (TableRow)theRow.CloneNode(true);

                    for (int j = 0; j < headerCells.Count; j++)
                    {
                        string    value = string.Empty;
                        TableCell cell  = headerCells[j];
                        rowCopy.Descendants <TableCell>().ElementAt(j).Append(new Paragraph
                                                                                  (new Run(new Text(value))));
                    }

                    theTable.AppendChild(rowCopy);
                }
            }
            //}
        }
Exemple #7
0
        /// <summary>
        /// FillDataObject
        /// </summary>
        /// <param name="dataInputObject"></param>
        /// <param name="stream"></param>
        public void FillDataObject(object dataInputObject, Stream stream)
        {
            if (dataInputObject != null)
            {
                if (stream != null && stream.CanRead && stream.CanWrite)
                {
                    // Use OpenXML to process
                    var dictionary = GetDictionaryFromObject(dataInputObject);
                    using (WordprocessingDocument word = WordprocessingDocument.Open(stream, true))
                    {
                        var part     = word.MainDocumentPart;
                        var elements = part.Document.Descendants <SdtElement>().ToList();
                        foreach (SdtElement element in elements)
                        {
                            SdtAlias alias = element.Descendants <SdtAlias>().FirstOrDefault();
                            if (alias != null)
                            {
                                // Get title of content control
                                var title = alias.Val.Value;
                                if (dictionary.ContainsKey(title))
                                {
                                    object value = dictionary[title];
                                    if (element.ToString().Equals("DocumentFormat.OpenXml.Wordprocessing.SdtRun"))
                                    {
                                        SdtRun run = element as SdtRun;
                                        if (run != null)
                                        {
                                            SdtContentRun contentRun = run.Descendants <SdtContentRun>().FirstOrDefault();
                                            Run           xRun       = contentRun.Descendants <Run>().FirstOrDefault();
                                            if (xRun == null)
                                            {
                                                contentRun.AppendChild(new Run());
                                                xRun = contentRun.Descendants <Run>().FirstOrDefault();
                                            }
                                            Text text = xRun.Descendants <Text>().FirstOrDefault();
                                            if (text == null)
                                            {
                                                xRun.AppendChild(new Text(value.ToString()));
                                                text = xRun.Descendants <Text>().FirstOrDefault();
                                            }
                                            text.Text = value.ToString();
                                        }
                                    }
                                    else if (element.ToString().Equals("DocumentFormat.OpenXml.Wordprocessing.SdtBlock"))
                                    {
                                        SdtBlock block = element as SdtBlock;
                                        if (block != null)
                                        {
                                            SdtContentBlock contentBlock = block.Descendants <SdtContentBlock>().FirstOrDefault();
                                            Run             xRun         = contentBlock.Descendants <Run>().FirstOrDefault();
                                            if (xRun == null)
                                            {
                                                contentBlock.AppendChild(new Run());
                                                xRun = contentBlock.Descendants <Run>().FirstOrDefault();
                                            }
                                            Text text = xRun.Descendants <Text>().FirstOrDefault();
                                            if (text == null)
                                            {
                                                xRun.AppendChild(new Text(value.ToString()));
                                                text = xRun.Descendants <Text>().FirstOrDefault();
                                            }
                                            text.Text = value.ToString();
                                        }
                                    }
                                }
                            }
                        }

                        part.Document.Save();
                    }
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Fill data object into word file that has arrBytesSource data.
        /// </summary>
        /// <param name="dataInputObject"></param>
        /// <param name="arrBytesSource"></param>
        /// <returns>The MemoryStream object.</returns>
        public Stream FillDataObject(object dataInputObject, byte[] arrBytesSource)
        {
            MemoryStream memoryStream = null;

            try
            {
                if (dataInputObject != null)
                {
                    if (arrBytesSource != null && arrBytesSource.Length > 0)
                    {
                        #region Fix bug TFS #1971
                        //memoryStream = new MemoryStream(arrBytesSource, true);
                        memoryStream = new MemoryStream();
                        memoryStream.Write(arrBytesSource, 0, arrBytesSource.Length);
                        memoryStream.Position = 0;
                        #endregion

                        // Use OpenXML to process
                        var dictionary = GetDictionaryFromObject(dataInputObject);
                        using (WordprocessingDocument word = WordprocessingDocument.Open(memoryStream, true))
                        {
                            var part     = word.MainDocumentPart;
                            var elements = part.Document.Descendants <SdtElement>().ToList();
                            foreach (SdtElement element in elements)
                            {
                                SdtAlias alias = element.Descendants <SdtAlias>().FirstOrDefault();
                                if (alias != null)
                                {
                                    // Get title of content control
                                    var title = alias.Val.Value;
                                    if (dictionary.ContainsKey(title))
                                    {
                                        object value = dictionary[title];

                                        if (value != null)
                                        {
                                            if (element.ToString().Equals("DocumentFormat.OpenXml.Wordprocessing.SdtRun"))
                                            {
                                                SdtRun run = element as SdtRun;
                                                if (run != null)
                                                {
                                                    if (value is bool)
                                                    {
                                                        SdtContentCheckBox contentCheckBox = run.Descendants <SdtContentCheckBox>().FirstOrDefault();
                                                        if (contentCheckBox != null)
                                                        {
                                                            if (string.Compare(value.ToString(), Boolean.TrueString, true) == 0)
                                                            {
                                                                contentCheckBox.Checked.Val = string.Compare(value.ToString(), Boolean.TrueString, true) == 0 ? OnOffValues.One : OnOffValues.Zero;
                                                                SdtContentRun contentRun = run.Descendants <SdtContentRun>().FirstOrDefault();
                                                                if (contentRun != null)
                                                                {
                                                                    Run xRun = contentRun.Descendants <Run>().FirstOrDefault();
                                                                    if (xRun != null)
                                                                    {
                                                                        SymbolChar checkedSymbolChar = xRun.Descendants <SymbolChar>().FirstOrDefault();
                                                                        if (checkedSymbolChar != null)
                                                                        {
                                                                            checkedSymbolChar.Char = new HexBinaryValue(CheckedSymbolChar);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        SdtContentRun contentRun = run.Descendants <SdtContentRun>().FirstOrDefault();
                                                        Run           xRun       = contentRun.Descendants <Run>().FirstOrDefault();
                                                        if (xRun == null)
                                                        {
                                                            contentRun.AppendChild(new Run());
                                                            xRun = contentRun.Descendants <Run>().FirstOrDefault();
                                                        }
                                                        Text text = xRun.Descendants <Text>().FirstOrDefault();
                                                        if (text == null)
                                                        {
                                                            xRun.AppendChild(new Text(value.ToString()));
                                                            text = xRun.Descendants <Text>().FirstOrDefault();
                                                        }
                                                        text.Text = value.ToString();
                                                    }
                                                }
                                            }
                                            else if (element.ToString().Equals("DocumentFormat.OpenXml.Wordprocessing.SdtBlock"))
                                            {
                                                SdtBlock block = element as SdtBlock;
                                                if (block != null)
                                                {
                                                    if (value is bool)
                                                    {
                                                        SdtContentCheckBox contentCheckBox = block.Descendants <SdtContentCheckBox>().FirstOrDefault();
                                                        if (contentCheckBox != null)
                                                        {
                                                            if (string.Compare(value.ToString(), Boolean.TrueString, true) == 0)
                                                            {
                                                                contentCheckBox.Checked.Val = string.Compare(value.ToString(), Boolean.TrueString, true) == 0 ? OnOffValues.One : OnOffValues.Zero;
                                                                SdtContentRun contentRun = block.Descendants <SdtContentRun>().FirstOrDefault();
                                                                if (contentRun != null)
                                                                {
                                                                    Run xRun = contentRun.Descendants <Run>().FirstOrDefault();
                                                                    if (xRun != null)
                                                                    {
                                                                        SymbolChar checkedSymbolChar = xRun.Descendants <SymbolChar>().FirstOrDefault();
                                                                        if (checkedSymbolChar != null)
                                                                        {
                                                                            checkedSymbolChar.Char = new HexBinaryValue(CheckedSymbolChar);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        SdtContentBlock contentBlock = block.Descendants <SdtContentBlock>().FirstOrDefault();
                                                        Run             xRun         = contentBlock.Descendants <Run>().FirstOrDefault();
                                                        if (xRun == null)
                                                        {
                                                            contentBlock.AppendChild(new Run());
                                                            xRun = contentBlock.Descendants <Run>().FirstOrDefault();
                                                        }
                                                        Text text = xRun.Descendants <Text>().FirstOrDefault();
                                                        if (text == null)
                                                        {
                                                            xRun.AppendChild(new Text(value.ToString()));
                                                            text = xRun.Descendants <Text>().FirstOrDefault();
                                                        }
                                                        text.Text = value.ToString();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            part.Document.Save();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ULSLogging.LogError(ex);
                throw ex;
            }

            return(memoryStream);
        }
Exemple #9
0
        public static void Find_table(List <List <string> > List1, string path1, string path2)
        {
            List <string> Tables  = new List <string>();
            int           flazhok = 0;
            int           fcount  = 0;
            int           k       = 0;

            byte[]        byteArray = File.ReadAllBytes(path1);
            List <string> M         = new List <string>();
            int           u         = 0;
            int           m         = 0;

            using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, (int)byteArray.Length);



                using (WordprocessingDocument outDoc = WordprocessingDocument.Open(mem, true))
                {
                    var doc = outDoc.MainDocumentPart.Document;

                    MainDocumentPart mainPart = outDoc.MainDocumentPart;


                    DocDefaults defaults = doc.MainDocumentPart.StyleDefinitionsPart.Styles.Descendants <DocDefaults>().FirstOrDefault();

                    RunFonts runFont = defaults.RunPropertiesDefault.RunPropertiesBaseStyle.RunFonts;
                    runFont.Ascii = "Calibri";
                    //runFont.AsciiTheme = "Times New Roman";
                    string   font = runFont.Ascii;
                    FontSize fs   = new FontSize();
                    fs.Val = "8";
                    string[] tblTag = new string[0];//Табличные теги

                    for (int f1 = 0; f1 < List1.Count; f1++)
                    {
                        flazhok = 0;
                        Array.Resize(ref tblTag, tblTag.Length + 1);

                        fcount = 0;
                        int i = 0;



                        tblTag[i] = List1[k][fcount].ToString();
                        m         = k;
                        fcount++;
                        i++;



                        var ccWithTable1 = mainPart.Document.Body.Descendants <SdtElement>();


                        bool     b           = true;
                        SdtBlock ccWithTable = mainPart.Document.Body.Descendants <SdtBlock>().FirstOrDefault();

                        int index = 0;



                        foreach (var tt in ccWithTable1)
                        {
                            if (tt.SdtProperties.GetFirstChild <Tag>().Val == tblTag[index])
                            {
                                ccWithTable = mainPart.Document.Body.Descendants <SdtBlock>().Where
                                                  (r => r.SdtProperties.GetFirstChild <Tag>().Val == tblTag[index]).Single();

                                Tables.Add(tblTag[index]);
                                flazhok = 1;
                                break;
                            }
                        }
                        int count = 0;
                        int countt = 0;
                        int r2 = 3; int n = 0;
                        var tr2 = new TableRow(); var tr3 = new TableRow();
                        if (flazhok == 1)
                        {
                            int struct2 = 0;
                            for (int u23 = 1; u23 < List1[k].Count; u23++)
                            {
                                if (u23 >= 15 + struct2)
                                {
                                    countt++;
                                    struct2 += 15;
                                }
                            }

                            int   f5 = 0; int f6 = 0;
                            Table theTable = ccWithTable.Descendants <Table>().FirstOrDefault();

                            TableRow row8 = theTable.Elements <TableRow>().ElementAt(r2);



                            theTable.InsertAfter <TableRow>(tr2, row8);
                            int county = 0;
                            int u2     = 1;
                            int u233   = 1;
                            int u234   = 1;

                            fs.Val = "16";

                            for (int u23 = 0; u23 < countt; u23++)
                            {
                                if (u23 != 0)
                                {
                                    u233 = u2 + 1;
                                    u234 = u233 - 1;
                                }
                                county = 0;
                                for (u2 = 1; u2 < List1[0].Count(); u2++)
                                {
                                    u2 = u233;
                                    if (u2 > 15)
                                    {
                                        if (county == 0)
                                        {
                                            {
                                                u233 = u233 - 1;
                                            }
                                        }
                                    }
                                    county++;
                                    u233++;
                                    b = true;

                                    if (u2 >= u234 + 15)
                                    {
                                        break;
                                    }

                                    else
                                    {
                                        b = false;



                                        int i3 = 0;
                                        int i8 = 3;
                                        int y  = 0;
                                        int b3 = 0;

                                        int c = 0;
                                        M.Clear();
                                        //TableRow row2 = theTable.Elements<TableRow>().ElementAt(i8);

                                        TableCell cell = tr2.Elements <TableCell>().FirstOrDefault();



                                        int[] gridSpan1 = null;
                                        gridSpan1 = new int[] { 1, 7 };
                                        TableCellProperties tcp3 = new TableCellProperties(new GridSpan()
                                        {
                                            Val = gridSpan1[b3]
                                        }); b3++;



                                        TableCell cell2 = new TableCell();

                                        cell2.Append(new Paragraph
                                                         (new Run(new Text(""))));
                                        tr2.AppendChild(cell2);

                                        /*
                                         *   Paragraph p3 = cell2.Elements<Paragraph>().First();
                                         *   Run t2 = p3.Elements<Run>().First();
                                         *   RunProperties rPr2 = new RunProperties(
                                         *  new RunFonts()
                                         *  {
                                         *      Ascii = font,
                                         *      HighAnsi = font
                                         *  },
                                         *
                                         *                 new FontSize()
                                         *                 {
                                         *                     Val = fs.Val
                                         *                 });
                                         *
                                         *   t2.PrependChild<RunProperties>(rPr2);
                                         *
                                         */



                                        if (b == false)
                                        {
                                            if (u2 >= u234 + 15 - 1 && u2 != List1[0].Count - 1)
                                            {
                                                n   = 14;
                                                tr2 = new TableRow();
                                                r2++;
                                                row8 = theTable.Elements <TableRow>().ElementAt(r2);

                                                theTable.InsertAfter <TableRow>(tr2, row8);
                                            }
                                        }
                                        else
                                        {
                                            if (u2 != List1[0].Count() - 1)
                                            {
                                                if (u2 >= 16 + n)
                                                {
                                                    n   = n + 15;
                                                    tr2 = new TableRow();
                                                    r2++;
                                                    row8 = theTable.Elements <TableRow>().ElementAt(r2);

                                                    theTable.InsertAfter <TableRow>(tr2, row8);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        int n18 = 0;
                        int tyacheika = 1; int count7 = 0;
                        Dictionary <int, int> d3 = new Dictionary <int, int>();

                        for (tyacheika = 1; tyacheika < List1[0].Count(); tyacheika++)
                        {
                            d3.Add(tyacheika + n18, n18 + 15 + tyacheika - 1);

                            n18 += 14;
                        }


                        Table theTable2         = ccWithTable.Descendants <Table>().FirstOrDefault();
                        Dictionary <int, int> d = new Dictionary <int, int>();
                        int g = 0;
                        TableCellProperties tcp1 = new TableCellProperties();
                        List <int>          l    = new List <int>();
                        int n15 = 0;

                        int yy     = 1;
                        int prt    = 1;
                        int lcount = 1;
                        int t16    = 0;
                        int t17    = 0;

                        bool flag = true;
                        int  ff = 0;  int ff2 = 0;
                        int  yacheika1 = 1;
                        int  perv      = 0;
                        int  count55   = 0;
                        int  yperv     = 0;
                        bool flazhok2  = true;
                        prt = yacheika1;
                        int ccount = 0;
                        prt = yy;
                        bool nk   = true;
                        int  nor2 = 0;
                        int  nor  = 0;
                        for (int yacheika12 = 1; yacheika12 < List1[0].Count(); yacheika12++)
                        {
                            if (perv >= 16)
                            {
                                break;
                            }
                            g   = 0;
                            t16 = 0;
                            if (flazhok2 == false)
                            {
                                g          = ff;
                                yacheika12 = ff2;
                                n15        = nor;
                                t16        = t17;
                            }


                            if (flag == false)
                            {
                                perv++;
                                yacheika12 = perv;
                                count55    = 0;
                            }

                            for (yacheika1 = yacheika12; yacheika1 < List1[0].Count(); yacheika1++)
                            {
                                yacheika12++;
                                if (yacheika1 == 10)
                                {
                                }
                                if (count55 == 0)
                                {
                                    perv = yacheika1;
                                }
                                count55++;
                                flag = true;
                                if (g > 15)
                                {
                                    break;
                                }
                                flazhok2 = true;

                                t16++;
                                t17 = t16;
                                ff  = g;

                                ff2 = yacheika1;

                                if (n15 + 15 + yacheika1 >= List1[0].Count())
                                {
                                    flag = false;
                                    break;
                                }
                                string k4 = List1[0][yacheika1 + n15];
                                string k5 = List1[0][n15 + 15 + yacheika1];
                                string oneone = ""; string twotwo = "";
                                string one1 = List1[0][yacheika1 + n15];
                                string one2 = List1[0][n15 + 15 + yacheika1 - 1];
                                bool   ka   = true;



                                if (n15 + 15 + yacheika1 <= List1[0].Count() - 1)
                                {
                                    if (List1[0][yacheika1 + n15] != List1[0][n15 + 15 + yacheika1])
                                    {
                                        n15     += 15;
                                        nor      = n15;
                                        nk       = false;
                                        flazhok2 = false;
                                        yperv    = perv;
                                        break;
                                    }


                                    g++;


                                    if (n15 + 15 + yacheika1 <= List1[0].Count() - 1)
                                    {
                                        foreach (var pair in d3)
                                        {
                                            if (pair.Key <= yacheika1 + n15 && yacheika1 + n15 <= pair.Value)
                                            {
                                                oneone = pair.Key.ToString();
                                                break;
                                            }
                                        }


                                        foreach (var pair1 in d3)
                                        {
                                            if (pair1.Key <= n15 + 15 + yacheika1 - 1 && n15 + 15 + yacheika1 - 1 <= pair1.Value)
                                            {
                                                twotwo = pair1.Key.ToString();
                                                break;
                                            }
                                        }

                                        bool flag33 = true;
                                        if (List1[0][Convert.ToInt32(oneone)] != List1[0][Convert.ToInt32(twotwo)])
                                        {
                                            flag33 = false;


                                            nk = true;

                                            n15 += 15;
                                            nor  = n15;

                                            flazhok2 = false;

                                            break;
                                        }

                                        if (List1[0][yacheika1 + n15] == List1[0][n15 + 15 + yacheika1])
                                        {
                                            if (flag33 != false)
                                            {
                                                l.Add(t16 - 1 + 4);


                                                l.Add(t16 + 5 - 1);
                                                n15 += 14;

                                                nor = n15;
                                                nk  = true;
                                            }
                                        }
                                    }
                                }
                            }


                            n15 = 0;

                            for (int i1 = 0; i1 < l.Count; i1++)
                            {
                                if (!d.ContainsKey(l[i1]))
                                {
                                    d.Add(l[i1], l[i1]);
                                }
                            }

                            bool       kas  = true;
                            List <int> list = new List <int>(d.Keys);
                            bool       yp   = true;
                            if (list.Count != 0)
                            {
                                for (int i1 = 0; i1 < list.Count(); i1++)
                                {
                                    if (list[i1] >= 18)
                                    {
                                        if (list[i1] >= 18)
                                        {            /*
                                                      * list.Remove(list[i1]);
                                                      * */
                                            yp = false;
                                        }
                                    }
                                }

                                /*
                                 * kas = false;
                                 * l.Clear();
                                 * list.Clear();
                                 * d.Clear();
                                 * */



                                if (kas == true)
                                {
                                    if (perv < 16)
                                    {
                                        int yacheika = 0;
                                        //  List<int> list = new List<int>(d.Keys);
                                        yacheika = yacheika1;


                                        /*
                                         * if (yp == false)
                                         * {*/

                                        tcp1 = new TableCellProperties(

                                            new VerticalMerge()
                                        {
                                            Val = MergedCellValues.Restart
                                        }
                                            );
                                        theTable2.Elements <TableRow>().ElementAt(list[0]).ElementAt(perv - 1).Append(tcp1);

                                        for (int t = 1; t < list.Count; t++)
                                        {
                                            TableCellProperties tcp11 = new TableCellProperties(

                                                new VerticalMerge()
                                            {
                                                Val = MergedCellValues.Continue
                                            }
                                                );


                                            theTable2.Elements <TableRow>().ElementAt(list[t]).ElementAt(perv - 1).Append(tcp11);
                                        }
                                    }

                                    /*
                                     * else
                                     * {
                                     *
                                     *  for (int t = 1; t < list.Count; t++)
                                     *  {
                                     *      TableCellProperties tcp11 = new TableCellProperties(
                                     *
                                     *      new VerticalMerge()
                                     *      {
                                     *          Val = MergedCellValues.Continue
                                     *      }
                                     *       );
                                     *      theTable2.Elements<TableRow>().ElementAt(list[t]).ElementAt(perv - 1).Append(tcp11);
                                     *
                                     *  }
                                     * // }
                                     * /*
                                     *
                                     *
                                     *                                                  for (int t = 1; t < list.Count - 1; t++)
                                     *  {
                                     *      TableCellProperties tcp11 = new TableCellProperties(
                                     *
                                     *      new VerticalMerge()
                                     *      {
                                     *          Val = MergedCellValues.Continue
                                     *      }
                                     *       );
                                     *
                                     */
                                    // theTable2.Elements<TableRow>().ElementAt(list[t]).ElementAt(perv - 1).Append(tcp11);
                                }



                                l.Clear();

                                d.Clear();
                            }
                        }

                        //  theTable2.Elements<TableRow>().ElementAt(theTable2.Elements<TableRow>().Count() - 1).Remove();
                    }
                }



                /*
                 * TableCellProperties tcp10 = new TableCellProperties(
                 *
                 * new VerticalMerge()
                 * {
                 * Val = MergedCellValues.Restart
                 * }
                 * );
                 * int t = d[l[0]];
                 * theTable.Elements<TableRow>().ElementAt(d[l[1]]).Elements<TableCell>().ElementAt(yacheika).Append(tcp10);
                 *
                 *
                 */

                //TableRow r23 = theTable.Elements<TableRow>().ElementAt(row1);

                /*
                 *          if (flag != false)
                 *          {
                 *              if (list.Count != 0)
                 *              {
                 *                  TableCellProperties tcp1 = new TableCellProperties(
                 *
                 * new VerticalMerge()
                 * {
                 *     Val = MergedCellValues.Restart
                 * }
                 *  );
                 *                  theTable.Elements<TableRow>().ElementAt(list[0]).ElementAt(yacheika1).Append(tcp1);
                 *
                 *                  for (int i11 = 1; i11 < d.Count; i11++)
                 *                  {
                 *                      TableCellProperties tcp11 = new TableCellProperties(
                 *
                 *     new VerticalMerge()
                 *     {
                 *         Val = MergedCellValues.Continue
                 *     }
                 *      );
                 *
                 *
                 *                      theTable.Elements<TableRow>().ElementAt(list[i11]).ElementAt(yacheika1).Append(tcp11);
                 *
                 *                  }
                 *              }
                 *
                 *          }
                 *          d.Clear();
                 *
                 *      }
                 *
                 *  }
                 *
                 *
                 *  /*
                 * TableCellProperties tcp11 = new TableCellProperties(
                 *
                 * new VerticalMerge()
                 * {
                 * Val = MergedCellValues.Restart
                 * }
                 * );
                 *  theTable.Elements<TableRow>().ElementAt(d[l[1]]).Elements<TableCell>().ElementAt(yacheika).Append(tcp11);
                 *
                 *
                 *
                 *  TableCellProperties tcp12 = new TableCellProperties(
                 *
                 * new VerticalMerge()
                 * {
                 * Val = MergedCellValues.Continue
                 * }
                 * );
                 *  theTable.Elements<TableRow>().ElementAt(d[l[2]]).ElementAt(yacheika).Append(tcp12);
                 * }
                 */



                /*
                 *
                 *                   for (int u2 = 1; u2 < List1[k].Count; u2++)
                 *                {
                 *
                 *                  if (theTable.Elements<TableRow>().ElementAt(u2-1) == theTable.Elements<TableRow>().ElementAt(u2))
                 *                      {
                 *                          TableCellProperties tcp10 = new TableCellProperties(
                 *
                 * new VerticalMerge()
                 * {
                 * Val = MergedCellValues.Restart
                 * }
                 * );
                 *
                 *                          TableCell cl = new TableCell();
                 *                          cl = tr2.Elements<TableCell>().ElementAt(u2);
                 *
                 *                          theTable.Elements<TableRow>().ElementAt(u2).Elements<TableCell>().ElementAt(u2).Append(tcp10);
                 *                         cl= theTable.Elements<TableRow>().ElementAt(u2).Elements<TableCell>().ElementAt(u2);
                 *                      }
                 *                  }
                 *
                 *              }
                 *
                 *
                 *
                 */



                /*
                 *
                 * for (int u3 = 5; u3 < theTable.Elements<TableRow>().Count(); u3++)
                 * {
                 *  TableRow tr5 = theTable.Elements<TableRow>().ElementAt(u3);
                 * string d= theTable.Elements<TableRow>().ElementAt(u3).InnerText;
                 * for (int u4 = 0; u4 < tr5.Elements<TableCell>().Count(); u4++)
                 * {
                 *
                 *     TableRow tr = theTable.Elements<TableRow>().ElementAt(u3);
                 *     TableCell tc12 = tr.Elements<TableCell>().ElementAt(u4);
                 *     string text = theTable.Elements<TableRow>().ElementAt(u3).ElementAt(u4).InnerText;
                 *     string text2 = theTable.Elements<TableRow>().ElementAt(u3 - 1).ElementAt(u4).InnerText;
                 *
                 *     if (text == text2)
                 *     {
                 *
                 *         count++;
                 *     }}}
                 *
                 *
                 *
                 *
                 *
                 *
                 * int schet = 0;
                 * for (int u3 = 5; u3 < theTable.Elements<TableRow>().Count(); u3++)
                 * {
                 *  TableRow tr5 = theTable.Elements<TableRow>().ElementAt(u3);
                 * string d= theTable.Elements<TableRow>().ElementAt(u3).InnerText;
                 * for (int u4 = 0; u4 < tr5.Elements<TableCell>().Count(); u4++)
                 * {
                 *
                 *     TableRow tr = theTable.Elements<TableRow>().ElementAt(u3);
                 *     TableCell tc12 = tr.Elements<TableCell>().ElementAt(u4);
                 *     string text = theTable.Elements<TableRow>().ElementAt(u3).ElementAt(u4).InnerText;
                 *     string text2 = theTable.Elements<TableRow>().ElementAt(u3 - 1).ElementAt(u4).InnerText;
                 *
                 *     if (text == text2)
                 *     {
                 *
                 *         count++;
                 *
                 *
                 *         string c1 = theTable.Elements<TableRow>().ElementAt(u3).Elements<TableCell>().ElementAt(u4).InnerText;
                 *
                 *
                 *
                 *
                 *
                 *
                 *
                 *
                 *
                 *
                 *         TableCellProperties tcp10 = new TableCellProperties(
                 *
                 * new VerticalMerge()
                 * {
                 * Val = MergedCellValues.Restart
                 * }
                 * );
                 *
                 *
                 *         theTable.Elements<TableRow>().ElementAt(u3 - 2).ElementAt(u4).Append(tcp10);
                 *
                 *
                 *
                 *
                 *
                 *
                 *         TableCellProperties tcp1 = new TableCellProperties(
                 *
                 * new VerticalMerge()
                 * {
                 * Val = MergedCellValues.Continue
                 * }
                 * );
                 *         theTable.Elements<TableRow>().ElementAt(u3).ElementAt(u4).Append(tcp1);
                 *         // tc12 = theTable.Elements<TableRow>().ElementAt(u3).Elements<TableCell>().ElementAt(u4);
                 *
                 *
                 *     }
                 * }
                 *
                 *
                 *
                 */



                try
                {
                    File.Delete(path2);


                    using (FileStream fileStream = new FileStream(path2,
                                                                  System.IO.FileMode.CreateNew))
                    {
                        mem.WriteTo(fileStream);
                    }
                }


                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        public void GenerateTable(string document, string tag, string startDate, string endDate)
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
            {
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;

                string   fromString = startDate;
                string   toString   = endDate;
                DateTime fromDate   = DateTime.ParseExact(fromString, "dd/MM/yyyy", null);
                DateTime toDate     = DateTime.ParseExact(toString, "dd/MM/yyyy", null);
                // date tag
                SdtRun controlTag = mainPart.Document.Body.Descendants <SdtRun>().Where
                                        (r => r.SdtProperties.GetFirstChild <Tag>().Val == "dateTag").SingleOrDefault();
                SdtContentRun contentRun = controlTag.GetFirstChild <SdtContentRun>();
                contentRun.GetFirstChild <Run>().GetFirstChild <Text>().Text = "Date: " + fromDate.ToLongDateString() + " to " + toDate.ToLongDateString();

                // This should return only one content control element: the one with
                // the specified tag value.
                // If not, "Single()" throws an exception.
                SdtBlock ccWithTable = mainPart.Document.Body.Descendants <SdtBlock>().Where
                                           (r => r.SdtProperties.GetFirstChild <Tag>().Val == tag).Single();
                // This should return only one table.
                Table theTable = ccWithTable.Descendants <Table>().Single();

                CurrentStatus     cstatus = CurrentStatus.Current;
                EndorsementStatus estatus = EndorsementStatus.Active;

                /***********************Area of health with active committees***********************/
                // display area of health which has active committees
                // in which the active committees have active reps
                // in which the active reps have prep and meeting time
                var areaOfHealth = (from aoh in db.CommitteeAreaOfHealth
                                    from comm in db.Committees
                                    from area in db.CommitteeModel_CommitteeAreaOfHealth
                                    from conh in db.ConsumerRepCommitteeHistory
                                    from conr in db.ConsumerReps
                                    where aoh.CommitteeAreaOfHealthModelID == area.CommitteeAreaOfHealthModelID
                                    where area.CommitteeModelID == comm.CommitteeModelID
                                    where conh.CommitteeModelID == comm.CommitteeModelID
                                    where conr.ConsumerRepModelID == conh.ConsumerRepModelID
                                    where comm.CurrentStatus == cstatus
                                    where conr.EndorsementStatus == estatus
                                    where conh.ReportedDate >= fromDate && conh.ReportedDate <= toDate
                                    where conh.PrepTime > 0 || conh.Meetingtime > 0
                                    select aoh).Distinct();

                int sumTotalCommittees       = 0;
                int totalSumTotalReps        = 0;
                int totalSumTotalPrepTime    = 0;
                int totalSumTotalMeetingTime = 0;
                int totalSumTotalTime        = 0;

                foreach (var aoh in areaOfHealth)
                {
                    // copy the table
                    Table tableCopy = (Table)theTable.CloneNode(true);
                    // add the table
                    ccWithTable.AppendChild(tableCopy);

                    // get the first row first element in the table
                    TableRow firstRow = tableCopy.Elements <TableRow>().First();
                    // get the last row in the table
                    TableRow lastRow = tableCopy.Elements <TableRow>().Last();

                    // add value to the first row in the table
                    firstRow.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "24"
                    }, new Bold()),
                                                                                   new Text(aoh.AreaOfHealthName.ToString()))));
                    firstRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                   new Text("Number of Reps"))));
                    firstRow.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                   new Text("Prep Hours"))));
                    firstRow.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                   new Text("Meeting Hours"))));
                    firstRow.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                   new Text("Total Hours"))));

                    // display active committees within the area of health
                    // in which active committees have active reps with prep time or meeting time
                    var committees = (from com in db.Committees
                                      from aohh in db.CommitteeModel_CommitteeAreaOfHealth
                                      from crch in db.ConsumerRepCommitteeHistory
                                      from csr in db.ConsumerReps
                                      where com.CommitteeModelID == aohh.CommitteeModelID
                                      where aohh.CommitteeAreaOfHealthModelID == aoh.CommitteeAreaOfHealthModelID
                                      where crch.CommitteeModelID == com.CommitteeModelID
                                      where crch.ConsumerRepModelID == csr.ConsumerRepModelID
                                      where com.CurrentStatus == cstatus
                                      where csr.EndorsementStatus == estatus
                                      where crch.PrepTime > 0 || crch.Meetingtime > 0
                                      where crch.ReportedDate >= fromDate && crch.ReportedDate <= toDate
                                      select com).Distinct();

                    int totalCommittees     = 0;
                    int sumTotalReps        = 0;
                    int sumTotalPrepTime    = 0;
                    int sumTotalMeetingTime = 0;
                    int sumTotalTime        = 0;

                    foreach (var com in committees)
                    {
                        // all consumer reps within the committee
                        var consumerReps = (from cr in db.ConsumerReps
                                            from ch in db.ConsumerRepCommitteeHistory
                                            where ch.CommitteeModelID == com.CommitteeModelID
                                            where ch.ConsumerRepModelID == cr.ConsumerRepModelID
                                            where cr.EndorsementStatus == estatus
                                            where ch.ReportedDate >= fromDate && ch.ReportedDate <= toDate
                                            where ch.PrepTime > 0 || ch.Meetingtime > 0
                                            select cr).Distinct();

                        int totalReps        = 0;
                        int totalPrepTime    = 0;
                        int totalMeetingTime = 0;
                        int totalTime        = 0;

                        foreach (var cr in consumerReps)
                        {
                            // newest reported date of the consumer rep
                            var maxReportedDate = (from ch in db.ConsumerRepCommitteeHistory
                                                   where cr.ConsumerRepModelID == ch.ConsumerRepModelID
                                                   where ch.CommitteeModelID == com.CommitteeModelID
                                                   where ch.ReportedDate >= fromDate && ch.ReportedDate <= toDate
                                                   where cr.EndorsementStatus == estatus
                                                   select ch.ReportedDate).Max();

                            // newest consumer rep history of the consumer rep
                            var consumerRepHisotry = (from ch in db.ConsumerRepCommitteeHistory
                                                      where cr.ConsumerRepModelID == ch.ConsumerRepModelID
                                                      where ch.CommitteeModelID == com.CommitteeModelID
                                                      where ch.ReportedDate >= fromDate && ch.ReportedDate <= toDate
                                                      where cr.EndorsementStatus == estatus
                                                      where ch.ReportedDate == maxReportedDate
                                                      select ch).Distinct();

                            // total
                            totalReps++;

                            foreach (var ch in consumerRepHisotry)
                            {
                                totalPrepTime    += ch.PrepTime;
                                totalMeetingTime += ch.Meetingtime;
                                totalTime         = totalMeetingTime + totalPrepTime;
                            }
                        }

                        // row for each committee
                        TableRow rowCopy = (TableRow)lastRow.CloneNode(true);
                        rowCopy.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(com.CommitteeName.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(totalReps.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(totalPrepTime.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(totalMeetingTime.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(totalTime.ToString()))));
                        tableCopy.AppendChild(rowCopy);

                        // sum of total
                        totalCommittees++;
                        sumTotalReps        += totalReps;
                        sumTotalPrepTime    += totalPrepTime;
                        sumTotalMeetingTime += totalMeetingTime;
                        sumTotalTime        += totalTime;
                    }
                    // remove the empty placeholder row from the table.
                    tableCopy.RemoveChild(lastRow);

                    // add a final row to the table
                    tableCopy.AppendChild(lastRow);
                    lastRow.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text("Committees active in the period: " + totalCommittees.ToString()))));
                    lastRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text(sumTotalReps.ToString()))));
                    lastRow.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text(sumTotalPrepTime.ToString()))));
                    lastRow.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text(sumTotalMeetingTime.ToString()))));
                    lastRow.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text(sumTotalTime.ToString()))));

                    // total sum of total
                    sumTotalCommittees       += totalCommittees;
                    totalSumTotalReps        += sumTotalReps;
                    totalSumTotalPrepTime    += sumTotalPrepTime;
                    totalSumTotalMeetingTime += sumTotalMeetingTime;
                    totalSumTotalTime        += sumTotalTime;
                }
                //remove the template table
                theTable.Remove();

                //***********************Other active committees***********************/
                //get last row of active committees
                TableRow lastRowActive = theTable.Elements <TableRow>().Last();
                //get first row of active committees
                TableRow firstRowActive = theTable.Elements <TableRow>().First();

                //first row values
                firstRowActive.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                                 (new Run(
                                                                                     new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                     new Text("Active Committees that Have Not Met in This Period".ToString()))));
                firstRowActive.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                 (new Run(
                                                                                     new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "20"
                }, new Bold()),
                                                                                     new Text("Number of Reps".ToString()))));

                var activeCommittees = (from aCom in db.Committees
                                        from aComh in db.ConsumerRepCommitteeHistory
                                        where aComh.CommitteeModelID == aCom.CommitteeModelID
                                        where aComh.PrepTime == 0 && aComh.Meetingtime == 0
                                        where aComh.ReportedDate >= fromDate && aComh.ReportedDate <= toDate
                                        where aCom.CurrentStatus == cstatus
                                        select aCom).Distinct();

                int totalcommittees = 0;
                int totalsumrep     = 0;

                foreach (var aCom in activeCommittees)
                {
                    var activeReps = (from aRep in db.ConsumerReps
                                      from aComh in db.ConsumerRepCommitteeHistory
                                      where aRep.ConsumerRepModelID == aComh.ConsumerRepModelID
                                      where aComh.CommitteeModelID == aCom.CommitteeModelID
                                      where aComh.ReportedDate >= fromDate && aComh.ReportedDate <= toDate
                                      where aRep.EndorsementStatus == estatus
                                      select aRep).Distinct();

                    int totalprep = 0;
                    int totalmeet = 0;
                    int totalrep  = 0;

                    foreach (var aRep in activeReps)
                    {
                        var maxDate = (from aComh in db.ConsumerRepCommitteeHistory
                                       where aComh.CommitteeModelID == aCom.CommitteeModelID
                                       where aComh.ConsumerRepModelID == aRep.ConsumerRepModelID
                                       where aComh.ReportedDate >= fromDate && aComh.ReportedDate <= toDate
                                       select aComh.ReportedDate).Max();

                        var activeComh = from aComh in db.ConsumerRepCommitteeHistory
                                         where aComh.CommitteeModelID == aCom.CommitteeModelID
                                         where aComh.ConsumerRepModelID == aRep.ConsumerRepModelID
                                         where aComh.ReportedDate >= fromDate && aComh.ReportedDate <= toDate
                                         where aComh.ReportedDate == maxDate
                                         select aComh;

                        foreach (var aComh in activeComh)
                        {
                            totalprep += aComh.PrepTime;
                            totalmeet += aComh.Meetingtime;
                        }

                        totalrep++;
                    }

                    if (totalprep == 0 && totalmeet == 0)
                    {
                        TableRow rowCopyActive = (TableRow)lastRowActive.CloneNode(true);
                        rowCopyActive.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                                        (new Run(
                                                                                            new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                            new Text(aCom.CommitteeName.ToString()))));
                        rowCopyActive.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                        (new Run(
                                                                                            new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                            new Text(totalrep.ToString()))));
                        // add row
                        theTable.AppendChild(rowCopyActive);

                        // total active committees and reps that is doesn't have a prep time
                        totalcommittees++;
                        totalsumrep += totalrep;
                    }
                }
                // remove empty row
                theTable.RemoveChild(lastRowActive);

                /***********************Total number***********************/
                sumTotalCommittees += totalcommittees;
                totalSumTotalReps  += totalsumrep;

                // three more rows
                for (int i = 0; i < 3; i++)
                {
                    TableRow rowFinalCopy = (TableRow)lastRowActive.CloneNode(true);
                    theTable.AppendChild(rowFinalCopy);
                }
                // Get the last row in the last two rows
                TableRow theLastRow = theTable.Elements <TableRow>().Last();
                // Get the second last row
                TableRow theSecondLastRow = theTable.Elements <TableRow>().Reverse().Skip(1).First();
                // Get the third last row
                TableRow theThirdLastRow = theTable.Elements <TableRow>().Reverse().Skip(2).First();

                // edit the final three rows
                theThirdLastRow.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "20"
                }, new Bold()),
                                                                                      new Text("Committees Active in the Period in this Grouping: " + totalcommittees.ToString()))));
                theThirdLastRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "20"
                }, new Bold()),
                                                                                      new Text(totalsumrep.ToString()))));

                theSecondLastRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                   (new Run(
                                                                                       new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                       new Text("Total Reps".ToString()))));
                theSecondLastRow.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                                   (new Run(
                                                                                       new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                       new Text("Total Prep Hours".ToString()))));
                theSecondLastRow.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                                   (new Run(
                                                                                       new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                       new Text("Total Meeting Hours"))));
                theSecondLastRow.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                                   (new Run(
                                                                                       new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                       new Text("Total Hours"))));

                theLastRow.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text("Total Committees Active in this Period: " + sumTotalCommittees.ToString()))));
                theLastRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text(totalSumTotalReps.ToString()))));
                theLastRow.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text(totalSumTotalPrepTime.ToString()))));
                theLastRow.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text(totalSumTotalMeetingTime.ToString()))));
                theLastRow.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text(totalSumTotalTime.ToString()))));

                // add the template table
                ccWithTable.AppendChild(theTable);

                // Save the changes to the table back into the document.
                mainPart.Document.Save();
            }
        }
Exemple #11
0
        public void CreateMSWordDocument(Guid identifier)
        {
            var    myResume    = _resumeManagerRepository.Get(m => m.Guid.Equals(identifier)).First().Resume;
            string projPath    = HttpContext.Current.Server.MapPath("~/Content/");
            string outFilePath = Path.Combine(projPath, "doc", myResume.ResumeManager.Link);

            byte[] templateBytes = System.IO.File.ReadAllBytes(projPath + "MSWordTemplates\\template4.dotx");

            using (MemoryStream templateStream = new MemoryStream())
            {
                templateStream.Write(templateBytes, 0, (int)templateBytes.Length);

                using (WordprocessingDocument doc = WordprocessingDocument.Open(templateStream, true))
                {
                    doc.ChangeDocumentType(WordprocessingDocumentType.Document);
                    var mainPart = doc.MainDocumentPart;

                    // Get the Document Settings Part
                    DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;

                    // Create a new attachedTemplate and specify a relationship ID
                    AttachedTemplate attachedTemplate1 = new AttachedTemplate()
                    {
                        Id = "relationId1"
                    };

                    // Append the attached template to the DocumentSettingsPart
                    documentSettingPart1.Settings.Append(attachedTemplate1);

                    // Add an ExternalRelationShip of type AttachedTemplate.
                    // Specify the path of template and the relationship ID
                    documentSettingPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(projPath + "MSWordTemplates\\template4.dotx", UriKind.Absolute), "relationId1");

                    string fullname = string.Format("{0} {1}", myResume.FirstName, myResume.LastName);
                    SetCCText(mainPart, "FullName", fullname);

                    SetCCText(mainPart, "Goal", myResume.Goal);
                    SetCCText(mainPart, "Location", myResume.CurrentLocation);

                    string email = myResume.Contacts.First(c => c.ContactTitle.Title.Equals("EMail")).Data;
                    SetCCText(mainPart, "Email", email);

                    string phone = myResume.Contacts.First(c => c.ContactTitle.Title.Equals("Phone")).Data;
                    SetCCText(mainPart, "Phone", phone);

                    RemoveCCChild(mainPart, "OtherContacts");
                    foreach (var contact in myResume.Contacts.Where(c => !c.ContactTitle.Title.Equals("EMail") && !c.ContactTitle.Title.Equals("Phone")))
                    {
                        AppendCCText(mainPart, "OtherContacts", string.Format("{0}: {1}", contact.ContactTitle.Title, contact.Data));
                    }

                    // ОБРАЗОВАНИЕ
                    if (myResume.Education.Count > 0)
                    {
                        SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Education").Single();
                        Table    theTable       = contentControl.Descendants <Table>().Single();
                        TableRow defaultRow     = theTable.Elements <TableRow>().Last();

                        foreach (var institution in myResume.Education)
                        {
                            TableRow rowCopy = (TableRow)defaultRow.CloneNode(true);

                            // период учебы
                            var periodRun = rowCopy.Descendants <TableCell>().ElementAt(0).GetFirstChild <Paragraph>().GetFirstChild <Run>();
                            periodRun.GetFirstChild <Text>().Text = string.Format("{0} –", institution.From.Format());
                            periodRun.Append(new Break());
                            periodRun.Append(new Text(institution.To.Format()));

                            // описание уч. заведениия:
                            // название и город
                            TableCell secondColumn = rowCopy.Descendants <TableCell>().ElementAt(1);
                            SetCCText(secondColumn, "InstitutionName", string.Format("{0}, г. {1}", institution.Name, institution.City));

                            // кафедра
                            if (string.IsNullOrEmpty(institution.Department))
                            {
                                secondColumn.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "InstitutionDepartment").Single().Parent.Remove();
                            }
                            else
                            {
                                SetCCText(secondColumn, "InstitutionDepartment", institution.Department);
                            }

                            // специальность
                            SetCCText(secondColumn, "InstitutionSpeciality", institution.Specialty);
                            secondColumn.Elements <Paragraph>().Last().Append(new Run(new Break()));

                            theTable.AppendChild(rowCopy);
                        }
                        theTable.RemoveChild(defaultRow);
                    }
                    else
                    {
                        mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Education").Single().Remove();
                    }

                    // ОПЫТ РАБОТЫ
                    if (myResume.WorkExp.Count > 0)
                    {
                        SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Experience").Single();
                        Table    theTable       = contentControl.Descendants <Table>().Single();
                        TableRow defaultRow     = theTable.Elements <TableRow>().Last();

                        foreach (var workPlace in myResume.WorkExp)
                        {
                            TableRow rowCopy = (TableRow)defaultRow.CloneNode(true);

                            // период в который работали
                            var periodRun = rowCopy.Descendants <TableCell>().ElementAt(0).GetFirstChild <Paragraph>().GetFirstChild <Run>();
                            periodRun.GetFirstChild <Text>().Text = string.Format("{0} –", workPlace.From.Format());
                            periodRun.Append(new Break());
                            periodRun.Append(new Text(workPlace.To.Format()));

                            // описание работы:
                            // название работы и город
                            TableCell secondColumn = rowCopy.Descendants <TableCell>().ElementAt(1);
                            SetCCText(secondColumn, "WorkplaceName", string.Format("{0}, г. {1}", workPlace.Name, workPlace.City));

                            // должность
                            SetCCText(secondColumn, "WorkplacePosition", workPlace.Position);

                            // обязанности
                            if (workPlace.Duties.Count > 0)
                            {
                                RemoveCCChild(secondColumn, "WorkplaceDuties");
                                foreach (var duty in workPlace.Duties)
                                {
                                    AppendCCText(secondColumn, "WorkplaceDuties", string.Format("– {0}", duty.Name));
                                }
                            }
                            else
                            {
                                secondColumn.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "WorkplaceDuties").Single().Parent.Remove();
                            }

                            //secondColumn.Elements<Paragraph>().Last().Append(new Run(new Break()));

                            theTable.AppendChild(rowCopy);
                        }
                        theTable.RemoveChild(defaultRow);
                    }
                    else
                    {
                        mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Experience").Single().Remove();
                    }


                    // СЕРТИФИКАТЫ
                    if (myResume.CertificatesAndTrainings.Count > 0)
                    {
                        RemoveCCChild(mainPart, "Certificates");
                        foreach (var certificate in myResume.CertificatesAndTrainings)
                        {
                            AppendCCText(mainPart, "Certificates", string.Format("{0} – {1}{2}", certificate.Date.Year, certificate.Name, certificate.Location != null ? string.Format(", г. {0}", certificate.Location) : ""));
                        }
                    }
                    else
                    {
                        RemoveCC(mainPart, "Section_Certificates");
                    }

                    // ЯЗЫКИ
                    if (myResume.Languages.Count > 0)
                    {
                        SdtBlock        contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Languages").Single();
                        SdtContentBlock contentRun     = contentControl.GetFirstChild <SdtContentBlock>();
                        Paragraph       defaultLi      = contentRun.GetFirstChild <Paragraph>();

                        foreach (var language in myResume.Languages)
                        {
                            Paragraph copy = (Paragraph)defaultLi.CloneNode(true);
                            copy.Descendants <Text>().Where(t => t.Text == "lang").Single().Text  = language.Name;
                            copy.Descendants <Text>().Where(t => t.Text == "level").Single().Text = language.Level;
                            contentRun.Append(copy);
                        }
                        contentRun.RemoveChild(defaultLi);
                    }
                    else
                    {
                        RemoveCC(mainPart, "Section_Languages");
                    }

                    // ЛИЧНЫЕ КАЧЕСТВА
                    if (myResume.PersonalQualities.Count > 0)
                    {
                        SdtBlock        contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "PersonalQualities").Single();
                        SdtContentBlock contentRun     = contentControl.GetFirstChild <SdtContentBlock>();
                        Paragraph       defaultLi      = contentRun.GetFirstChild <Paragraph>();

                        foreach (var quality in myResume.PersonalQualities)
                        {
                            Paragraph copy = (Paragraph)defaultLi.CloneNode(true);
                            copy.Descendants <Text>().Where(t => t.Text == "quality").Single().Text = quality.Name;
                            contentRun.Append(copy);
                        }
                        contentRun.RemoveChild(defaultLi);
                    }
                    else
                    {
                        mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_PersonalQualities").Single().Remove();
                    }

                    // НАВЫКИ
                    if (myResume.Skills.Count > 0)
                    {
                        SdtBlock        contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Skills").Single();
                        SdtContentBlock contentRun     = contentControl.GetFirstChild <SdtContentBlock>();
                        Paragraph       defaultLi      = contentRun.GetFirstChild <Paragraph>();

                        foreach (var skill in myResume.Skills)
                        {
                            Paragraph copy = (Paragraph)defaultLi.CloneNode(true);
                            copy.Descendants <Text>().Where(t => t.Text == "skill").Single().Text = skill.Name;
                            contentRun.Append(copy);
                        }
                        contentRun.RemoveChild(defaultLi);
                    }
                    else
                    {
                        mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Skills").Single().Remove();
                    }

                    mainPart.Document.Save();
                }
                File.WriteAllBytes(outFilePath, templateStream.ToArray());
            }
        }
Exemple #12
0
        public static void GentText(Dictionary <string, string> dict, List <List <string> > List1, string path2, string path3)
        {
            List <string> Tables  = new List <string>();
            int           flazhok = 0;
            int           fcount  = 0;
            int           k       = 0;

            byte[]        byteArray = File.ReadAllBytes(path3);
            List <string> M         = new List <string>();
            int           u         = 0;
            int           m         = 0;

            using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, (int)byteArray.Length);



                using (WordprocessingDocument outDoc = WordprocessingDocument.Open(mem, true))
                {
                    var doc = outDoc.MainDocumentPart.Document;

                    MainDocumentPart mainPart = outDoc.MainDocumentPart;


                    DocDefaults defaults = doc.MainDocumentPart.StyleDefinitionsPart.Styles.Descendants <DocDefaults>().FirstOrDefault();

                    RunFonts runFont = defaults.RunPropertiesDefault.RunPropertiesBaseStyle.RunFonts;
                    runFont.Ascii = "Calibri";
                    //runFont.AsciiTheme = "Times New Roman";
                    string   font = runFont.Ascii;
                    FontSize fs   = new FontSize();
                    fs.Val = "16";
                    string[] tblTag = new string[0];//Табличные теги
                    bool     flag   = true;
                    for (int f1 = 0; f1 < List1.Count; f1++)
                    {
                        flazhok = 0;
                        Array.Resize(ref tblTag, tblTag.Length + 1);

                        fcount = 0;
                        int i = 0;



                        tblTag[i] = List1[k][fcount].ToString();
                        m         = k;
                        fcount++;
                        i++;



                        var ccWithTable1 = mainPart.Document.Body.Descendants <SdtElement>();



                        SdtBlock ccWithTable = mainPart.Document.Body.Descendants <SdtBlock>().FirstOrDefault();

                        int index = 0;



                        foreach (var tt in ccWithTable1)
                        {
                            if (flag != false)
                            {
                                if (tt.SdtProperties.GetFirstChild <Tag>().Val == tblTag[index])
                                {
                                    ccWithTable = mainPart.Document.Body.Descendants <SdtBlock>().Where
                                                      (r => r.SdtProperties.GetFirstChild <Tag>().Val == tblTag[index]).Single();

                                    Tables.Add(tblTag[index]);
                                    flazhok = 1;
                                    flag    = false;
                                }
                            }
                        }
                        int count = 0;
                        int row = 0;
                        int r2 = 3; int n = 0;
                        int u2 = 1;

                        if (flazhok == 1)
                        {
                            Table theTable = ccWithTable.Descendants <Table>().FirstOrDefault();


                            for (row = 4; row < theTable.Elements <TableRow>().Count(); row++)
                            {
                                count = 0; bool p = true;
                                int             countp = 0;
                                TableRow        row8   = theTable.Elements <TableRow>().ElementAt(row);


                                for (int yacheika2 = 0; yacheika2 < theTable.Elements <TableRow>().ElementAt(row).Elements <TableCell>().Count(); yacheika2++)
                                {
                                    if (row == 4)
                                    {
                                        TableCell cell1     = row8.Elements <TableCell>().ElementAt(yacheika2);
                                        int       b3        = 0;
                                        int[]     gridSpan1 = null;
                                        gridSpan1 = new int[] { 1, 7 };
                                        TableCellProperties tcp3 = new TableCellProperties(new GridSpan()
                                        {
                                            Val = gridSpan1[b3]
                                        }); b3++;

                                        TableCell cell23 = new TableCell(tcp3, new Paragraph(new Run(new Text(List1[m][u2]))));

                                        TableCell cell2 = row8.Elements <TableCell>().ElementAt(yacheika2);
                                        cell2 = cell23;

                                        var sdts12 = mainPart.Document.Descendants <SdtElement>();

                                        //TableRow rowCopy = (TableRow)theRow.CloneNode(true);

                                        row8.Descendants <TableCell>().ElementAt(yacheika2).Append(new Paragraph
                                                                                                       (new Run(new Text(List1[m][u2]))));

                                        //row8.Elements<TableCell>().ElementAt(yacheika).InnerText = List1[m][u2];
                                        Paragraph p3 = row8.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>().First();
                                        Run       t2 = p3.Elements <Run>().First();


                                        RunProperties rPr2 = new RunProperties(
                                            new RunFonts()
                                        {
                                            Ascii    = font,
                                            HighAnsi = font
                                        },

                                            new FontSize()
                                        {
                                            Val = fs.Val
                                        });
                                        t2.PrependChild <RunProperties>(rPr2);

                                        if (t2.Count() > 1)
                                        {
                                            t2.LastChild.Remove();
                                        }


                                        if (row8.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>().Count() > 1)
                                        {
                                            foreach (var t3 in row8.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>())
                                            {
                                                if (countp == 0)
                                                {
                                                    t3.Remove();
                                                    break;
                                                }
                                            }
                                        }
                                        foreach (var t3 in row8.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>())
                                        {
                                            if (t3.Elements <ParagraphProperties>().Count() > 1)
                                            {
                                                for (int i7 = 0; i7 < t3.Elements <ParagraphProperties>().Count(); i7++)
                                                {
                                                    t3.Elements <ParagraphProperties>().ElementAt(i7).Remove();
                                                }
                                            }

                                            u2++;



                                            TableCellProperties tcp5 = new TableCellProperties(

                                                new TableCellVerticalAlignment()
                                            {
                                                Val = TableVerticalAlignmentValues.Center
                                            });



                                            ParagraphProperties pp = new ParagraphProperties(new Justification()
                                            {
                                                Val = JustificationValues.Center
                                            });

                                            t3.PrependChild <ParagraphProperties>(pp);

                                            t3.PrependChild <TableCellProperties>(tcp5);
                                        }
                                    }

                                    if (row != 4)
                                    {
                                        countp = 0;

                                        if (theTable.Elements <TableRow>().Count() <= row)
                                        {
                                            break;
                                        }


                                        TableRow row9 = theTable.Elements <TableRow>().ElementAt(row);
                                        row8 = theTable.Elements <TableRow>().ElementAt(row - 1);


                                        // row9 = theTable.Elements<TableRow>().ElementAt(row);
                                        if (yacheika2 == 15)
                                        {
                                            break;
                                        }
                                        if (count == 0)
                                        {
                                            if (u2 <= List1[m].Count() - 1)
                                            {
                                                if (List1[m][u2 - 15] != List1[m][u2])
                                                {
                                                    p = false;
                                                }
                                            }

                                            else
                                            {
                                                break;
                                            }
                                        }
                                        if (p == false)
                                        {
                                            TableCell cell1     = row8.Elements <TableCell>().ElementAt(yacheika2);
                                            int       b3        = 0;
                                            int[]     gridSpan1 = null;
                                            gridSpan1 = new int[] { 1, 7 };
                                            TableCellProperties tcp3 = new TableCellProperties(new GridSpan()
                                            {
                                                Val = gridSpan1[b3]
                                            }); b3++;

                                            // TableCell cell23 = new TableCell(tcp3, new Paragraph(new Run(new Text(List1[m][u2]))));

                                            // TableCell cell2 = row9.Elements<TableCell>().ElementAt(yacheika2);
                                            // cell2 = cell23;

                                            //  var sdts12 = mainPart.Document.Descendants<SdtElement>();

                                            //TableRow rowCopy = (TableRow)theRow.CloneNode(true);

                                            row9.Descendants <TableCell>().ElementAt(yacheika2).Append(new Paragraph
                                                                                                           (new Run(new Text(List1[m][u2]))));

                                            //row8.Elements<TableCell>().ElementAt(yacheika).InnerText = List1[m][u2];
                                            Paragraph p3 = row9.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>().First();
                                            Run       t2 = p3.Elements <Run>().First();

                                            if (row9.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>().Count() > 1)
                                            {
                                                foreach (var t3 in row9.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>())
                                                {
                                                    if (countp == 0)
                                                    {
                                                        t3.Remove();
                                                        break;
                                                    }
                                                }
                                            }
                                            RunProperties rPr2 = new RunProperties(
                                                new RunFonts()
                                            {
                                                Ascii    = font,
                                                HighAnsi = font
                                            },

                                                new FontSize()
                                            {
                                                Val = fs.Val
                                            });
                                            t2.PrependChild <RunProperties>(rPr2);
                                            if (t2.Count() > 1)
                                            {
                                                t2.LastChild.Remove();
                                            }


                                            foreach (var t3 in row9.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>())
                                            {
                                                if (t3.Elements <ParagraphProperties>().Count() > 1)
                                                {
                                                    for (int i7 = 0; i7 < t3.Elements <ParagraphProperties>().Count(); i7++)
                                                    {
                                                        t3.Elements <ParagraphProperties>().ElementAt(i7).Remove();
                                                    }
                                                }



                                                TableCellProperties tcp5 = new TableCellProperties(

                                                    new TableCellVerticalAlignment()
                                                {
                                                    Val = TableVerticalAlignmentValues.Center
                                                });



                                                ParagraphProperties pp = new ParagraphProperties(new Justification()
                                                {
                                                    Val = JustificationValues.Center
                                                });

                                                t3.PrependChild <ParagraphProperties>(pp);

                                                t3.PrependChild <TableCellProperties>(tcp5);
                                            }
                                        }

                                        else
                                        {
                                            countp = 0;
                                            if (List1[m][u2 - 15] != List1[m][u2])
                                            {
                                                // row9 = theTable.Elements<TableRow>().ElementAt(row - 1);



                                                TableCell cell1     = row8.Elements <TableCell>().ElementAt(yacheika2);
                                                int       b3        = 0;
                                                int[]     gridSpan1 = null;
                                                gridSpan1 = new int[] { 1, 7 };
                                                TableCellProperties tcp3 = new TableCellProperties(new GridSpan()
                                                {
                                                    Val = gridSpan1[b3]
                                                }); b3++;

                                                TableCell cell23 = new TableCell(tcp3, new Paragraph(new Run(new Text(List1[m][u2]))));

                                                TableCell cell2 = row8.Elements <TableCell>().ElementAt(yacheika2);
                                                cell2 = cell23;

                                                var sdts12 = mainPart.Document.Descendants <SdtElement>();

                                                //TableRow rowCopy = (TableRow)theRow.CloneNode(true);

                                                row9.Descendants <TableCell>().ElementAt(yacheika2).Append(new Paragraph
                                                                                                               (new Run(new Text(List1[m][u2]))));

                                                //row8.Elements<TableCell>().ElementAt(yacheika).InnerText = List1[m][u2];
                                                Paragraph p3 = row9.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>().First();
                                                Run       t2 = p3.Elements <Run>().First();

                                                if (row9.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>().Count() > 1)
                                                {
                                                    foreach (var t3 in row9.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>())
                                                    {
                                                        if (countp == 0)
                                                        {
                                                            t3.Remove();
                                                            break;
                                                        }
                                                    }
                                                }

                                                RunProperties rPr2 = new RunProperties(
                                                    new RunFonts()
                                                {
                                                    Ascii    = font,
                                                    HighAnsi = font
                                                },

                                                    new FontSize()
                                                {
                                                    Val = fs.Val
                                                });
                                                t2.PrependChild <RunProperties>(rPr2);
                                                if (t2.Count() > 1)
                                                {
                                                    t2.LastChild.Remove();
                                                }



                                                foreach (var t3 in row9.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>())
                                                {
                                                    if (t3.Elements <ParagraphProperties>().Count() > 1)
                                                    {
                                                        for (int i7 = 0; i7 < t3.Elements <ParagraphProperties>().Count(); i7++)
                                                        {
                                                            t3.Elements <ParagraphProperties>().ElementAt(i7).Remove();
                                                        }
                                                    }



                                                    TableCellProperties tcp5 = new TableCellProperties(

                                                        new TableCellVerticalAlignment()
                                                    {
                                                        Val = TableVerticalAlignmentValues.Center
                                                    });



                                                    ParagraphProperties pp = new ParagraphProperties(new Justification()
                                                    {
                                                        Val = JustificationValues.Center
                                                    });

                                                    t3.PrependChild <ParagraphProperties>(pp);

                                                    t3.PrependChild <TableCellProperties>(tcp5);
                                                }
                                            }
                                        }


                                        //string row11 = theTable.Elements<TableRow>().ElementAt(row1).Elements<TableCell>().ElementAt(yacheika1).InnerText;

                                        count++;
                                        u2++;
                                    }
                                }
                            }

//
                            int y = theTable.Elements <TableRow>().Count();

                            for (row = 4; row < theTable.Elements <TableRow>().Count(); row++)
                            {
                                TableRow row8 = theTable.Elements <TableRow>().ElementAt(row);

                                for (int yacheika2 = 0; yacheika2 < theTable.Elements <TableRow>().ElementAt(row).Elements <TableCell>().Count(); yacheika2++)
                                {
                                    foreach (var t3 in row8.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>())
                                    {
                                        Paragraph p3 = row8.Descendants <TableCell>().ElementAt(yacheika2).Elements <Paragraph>().First();
                                        Run       t2 = p3.Elements <Run>().First();


                                        RunProperties rPr2 = new RunProperties(
                                            new RunFonts()
                                        {
                                            Ascii    = font,
                                            HighAnsi = font
                                        },

                                            new FontSize()
                                        {
                                            Val = fs.Val
                                        });
                                        t2.PrependChild <RunProperties>(rPr2);
                                    }
                                }
                            }
                        }

                        var sdts123 = mainPart.Document.Descendants <SdtElement>();


                        foreach (var sdt3 in sdts123)
                        {
                            Tag    ff       = sdt3.SdtProperties.GetFirstChild <Tag>();
                            string old_text = sdt3.SdtProperties.InnerText;


                            if (ff != null)
                            {
                                if (dict.ContainsKey((ff.Val)))
                                {
                                    string value = dict[ff.Val];;
                                    sdt3.Descendants <DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault().Text = value;
                                }
                            }
                        }
                    }
                }


                try
                {
                    File.Delete(path2);


                    using (FileStream fileStream = new FileStream(path2,
                                                                  System.IO.FileMode.CreateNew))
                    {
                        mem.WriteTo(fileStream);
                    }
                }


                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Exemple #13
0
        private void button1_Click(object sender, EventArgs e)
        {
            PriceData.getPriceDataToDay("ACB");
            if (File.Exists("template_output.docx"))
            {
                File.Delete("template_output.docx");
            }
            File.Copy("template_input.docx", "template_output.docx");
            //OpenXMLUtils.createDocument("t.docx");
            //OpenXMLUtils.CreateTable("t.docx");
            //OpenXMLUtils.replacePicture("template.docx");
            using (WordprocessingDocument doc =
                       WordprocessingDocument.Open("template_output.docx", true))
            {
                SearchAndReplacer.SearchAndReplace(doc, "[date]", DateTime.Now.ToShortDateString(), true);
                SearchAndReplacer.SearchAndReplace(doc, "[Market Overview]", "Với  một phiên tăng giá tiếp  tục  trên  cả 2  sàn  trong  ngày  10/1,  các  tín hiệu xác nhận sự đảo chiều giảm điểm đã không xuất hiện, đà tăng giá vẫn chưa có dấu hiệu dừng lại. ", true);
                SearchAndReplacer.SearchAndReplace(doc, "[change1]", "+2.53%", true);
                SearchAndReplacer.SearchAndReplace(doc, "[change2]", "+1.54%", true);
                SearchAndReplacer.SearchAndReplace(doc, "[gtdc1]", "460.12", true);
                SearchAndReplacer.SearchAndReplace(doc, "[gtdc2]", "60.53", true);
                SearchAndReplacer.SearchAndReplace(doc, "[klgd1]", "79.394.580", true);
                SearchAndReplacer.SearchAndReplace(doc, "[klgd2]", "67.007.880", true);
                SearchAndReplacer.SearchAndReplace(doc, "[gtgd1]", "1.523,346", true);
                SearchAndReplacer.SearchAndReplace(doc, "[gtgd2]", "470,871", true);

                // Dispose the previous instance.
                if (documentManipulator != null)
                {
                    documentManipulator.Dispose();
                }

                documentManipulator = new WordDocumentImageManipulator(doc);

                int i = 1;
                foreach (var blip in documentManipulator.GetAllImages())
                {
                    if (i == 1)
                    {
                        documentManipulator.ReplaceImage(
                            blip,
                            new FileInfo("lineChart.jpg"));
                        i++;
                        continue;
                    }
                    documentManipulator.ReplaceImage(
                        blip,
                        new FileInfo("ck" + (i - 1) + ".png"));
                    i++;
                }
                string           tblTag   = "StockTableTag";
                MainDocumentPart mainPart = doc.MainDocumentPart;
                //StockService.baseDS.stockCodeDataTable tbl = Gateway.PriceData.getPriceDataToDay();
                SdtBlock ccWithTable = mainPart.Document.Body.Descendants <SdtBlock>().Where
                                           (r => r.SdtProperties.GetFirstChild <Tag>().Val == tblTag).Single();

                // This should return only one table.
                Table theTable = ccWithTable.Descendants <Table>().Single();
                // Get the last row in the table.
                TableRow theRow = theTable.Elements <TableRow>().Last();
                foreach (var item in lstStockCodes)
                {
                    try
                    {
                        StockService.baseDS.priceDataRow row = Gateway.PriceData.getPriceDataToDay(item);
                        TableRow rowCopy = (TableRow)theRow.CloneNode(true);
                        rowCopy.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                                  (new Run(new Text(row.stockCode.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                  (new Run(new Text(row.openPrice.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                                  (new Run(new Text(row.closePrice.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                                  (new Run(new Text(row.volume.ToString()))));
                        theTable.AppendChild(rowCopy);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
                // Remove the empty placeholder row from the table.
                theTable.RemoveChild(theRow);

                // Save the changes to the table back into the document.
                mainPart.Document.Save();
            }
            MessageBox.Show("Input->template_input.docx and Ouput->template_output.docx. Success!!! The program will be closed!!!");
            this.Close();
        }