public void Apply(Color[] spectrum01, Color[] spectrum23, Color[] wtable)
        {
            if (Spectrum01 != null && spectrum01 != null)
            {
                Spectrum01.SetPixels(spectrum01);
                Spectrum01.Apply();

                System.Array.Copy(spectrum01, SpectrumData01, spectrum01.Length);
            }

            if (Spectrum23 != null && spectrum23 != null)
            {
                Spectrum23.SetPixels(spectrum23);
                Spectrum23.Apply();

                System.Array.Copy(spectrum23, SpectrumData23, spectrum23.Length);
            }

            if (WTable != null && wtable != null)
            {
                WTable.SetPixels(wtable);
                WTable.Apply();

                System.Array.Copy(wtable, WTableData, wtable.Length);
            }
        }
Exemplo n.º 2
0
 static void Main(string[] args)
 {
     //Creates new Word document instance for Word processing
     using (WordDocument document = new WordDocument())
     {
         //Opens the input Word document
         Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Table.docx"));
         document.Open(docStream, FormatType.Docx);
         docStream.Dispose();
         //Opens the source Word document containing table style definition
         WordDocument srcDocument = new WordDocument();
         docStream = File.OpenRead(Path.GetFullPath(@"../../../TableStyles.docx"));
         srcDocument.Open(docStream, FormatType.Docx);
         docStream.Dispose();
         //Gets the table style (CustomStyle) from the styles collection
         WTableStyle srcTableStyle = srcDocument.Styles.FindByName("CustomStyle", StyleType.TableStyle) as WTableStyle;
         //Creates a cloned copy of table style
         WTableStyle clonedTableStyle = srcTableStyle.Clone() as WTableStyle;
         //Adds the cloned copy of source table style to the destination document
         document.Styles.Add(clonedTableStyle);
         //Releases the resources of source Word document instance
         srcDocument.Dispose();
         //Gets table to apply style
         WTable table = (WTable)document.LastSection.Tables[0];
         //Applies the custom table style to the table
         table.ApplyStyle("CustomStyle");
         //Saves the file in the given path
         docStream = File.Create(Path.GetFullPath(@"Result.docx"));
         document.Save(docStream, FormatType.Docx);
         docStream.Dispose();
     }
 }
Exemplo n.º 3
0
        private static WListItemElement GetListItemElementFromXMLData(XmlNode ListItemNode)
        {
            if (ListItemNode != null)
            {
                WListItemElement wlie = new WListItemElement();

                if (ListItemNode.Name == WordXMLTags.WordTagName_Paragraph)
                {
                    WParagraph WPrg = WParagraphReader.GetParagraphFromParagraphXMLNode(ListItemNode);
                    wlie.ListItemElement = WPrg;
                    wlie.ListID          = WPrg.ListID;
                    wlie.ListItemLevel   = WPrg.ListItemLevel;
                }
                else if (ListItemNode.Name == WordXMLTags.WTN_Table)
                {
                    WTable LTable = WTableReader.GetTableFromTableXMLData(ListItemNode.OuterXml);
                    wlie.ListItemElement = LTable;
                    wlie.ListItemLevel   = -1;
                    wlie.ListID          = -1;
                }

                return(wlie);
            }
            return(null);
        }
Exemplo n.º 4
0
        public ActionResult TableStyles(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }
            string       dataPath = ResolveApplicationDataPath("TemplateTableStyle.doc", "Data\\DocIO");
            WordDocument document = new WordDocument(dataPath);

            string dataBase = ResolveApplicationDataPath("Northwind.mdb", "Data");

            // Get Data from the Database.
            AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);
            string          connectionstring = "Data Source = " + ResolveApplicationDataPath("Northwind.mdb", "Data");
            OleDbConnection conn             = new OleDbConnection();

            conn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0;Password=\"\";User ID=Admin;" + connectionstring;
            conn.Open();
            DataSet          ds      = new DataSet();
            OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from Suppliers", conn);

            adapter.Fill(ds);
            ds.Tables[0].TableName = "Suppliers";
            adapter.Dispose();
            conn.Close();

            // Execute Mail Merge with groups.
            document.MailMerge.ExecuteGroup(ds.Tables[0]);

            #region Built-in table styles
            //Get table to apply style.
            WTable table = (WTable)document.LastSection.Tables[0];

            //Apply built-in table style to the table.
            table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent5);
            #endregion

            #region Document save option
            //Save as .docx format
            if (Group1 == "WordDocx")
            {
                return(document.ExportAsActionResult("Sample.docx", FormatType.Docx, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            // Save as WordML(.xml) format
            else if (Group1 == "WordML")
            {
                return(document.ExportAsActionResult("Sample.xml", FormatType.WordML, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            //Save as .pdf format
            else if (Group1 == "Pdf")
            {
                DocToPDFConverter converter = new DocToPDFConverter();
                PdfDocument       pdfDoc    = converter.ConvertToPDF(document);

                return(pdfDoc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
            #endregion Document save option

            return(View());
        }
Exemplo n.º 5
0
        private async void StileOpzioniTabellaWordAsync()
        {
            //Crea una istanza della classe WordDocument
            WordDocument document = new WordDocument();
            //Aggiunge una sezione ad un documento word
            IWSection sectionFirst = document.AddSection();
            //Aggiunge una tabella ad un documento word
            IWTable tableFirst = sectionFirst.AddTable();

            //Dimensiona la tabella
            tableFirst.ResetCells(3, 2);
            //Salva il documento su memory stream
            MemoryStream stream = new MemoryStream();
            await document.SaveAsync(stream, FormatType.Docx);

            document.Open(stream, FormatType.Docx);

            WSection section = document.Sections[0];

            WTable table = section.Tables[0] as WTable;

            //Applica alla tabella lo stile built-in "LightShading"
            table.ApplyStyle(BuiltinTableStyle.LightShading);

            //Abilita una formattazione speciale per le banded columns della tabella
            table.ApplyStyleForBandedColumns = true;

            //Abilita una formattazione speciale per le banded rows of the table
            table.ApplyStyleForBandedRows = true;

            //Disabilita la formattazione speciale per la prima colonna della tabella
            table.ApplyStyleForFirstColumn = false;

            //Abilita una formattazione speciale per la riga di testata della tabella
            table.ApplyStyleForHeaderRow = true;

            //Abilita una formattazione speciale per l'ultima colonna della tabella
            table.ApplyStyleForLastColumn = true;

            //Disabilita la formattazione speciale per l'ultima riga della tabella
            table.ApplyStyleForLastRow = false;

            //Salva e chiudi l'istanza del documento
            //Salva il documento su memory stream
            MemoryStream memoryStream = new MemoryStream();
            await document.SaveAsync(memoryStream, FormatType.Docx);

            //Libera le risorse impegnate dall'istanza WordDocument
            document.Close();

            //Salva lo stream come file di documento Word nella macchina locale
            StorageFile stFile = await Save(memoryStream, "TableStyle.docx");

            DefaultLaunch("TableStyle.docx");
        }
 /// <summary>
 /// Iterates into table.
 /// </summary>
 /// <param name="table">The table.</param>
 /// <param name="fieldType">Type of Field.</param>
 private void RemoveFieldCodesInTable(WTable table)
 {
     //Iterates the row collection in a table
     foreach (WTableRow row in table.Rows)
     {
         //Iterates the cell collection in a table row
         foreach (WTableCell cell in row.Cells)
         {
             RemoveFieldCodesInTextBody(cell);
         }
     }
 }
Exemplo n.º 7
0
        public ActionResult TableStyles(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }
            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;

            dataPath = basePath + @"/DocIO/TemplateTableStyle.doc";
            WordDocument document   = new WordDocument();
            FileStream   fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            document.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;

            //Create MailMergeDataTable
            MailMergeDataTable mailMergeDataTable = GetMailMergeDataTable();

            // Execute Mail Merge with groups.
            document.MailMerge.ExecuteGroup(mailMergeDataTable);

            #region Built-in table styles
            //Get table to apply style.
            WTable table = (WTable)document.LastSection.Tables[0];

            //Apply built-in table style to the table.
            table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent5);
            #endregion

            FormatType type        = FormatType.Docx;
            string     filename    = "Sample.docx";
            string     contenttype = "application/vnd.ms-word.document.12";
            #region Document SaveOption
            //Save as .xml format
            if (Group1 == "WordML")
            {
                type        = FormatType.WordML;
                filename    = "Sample.xml";
                contenttype = "application/msword";
            }
            #endregion Document SaveOption
            MemoryStream ms = new MemoryStream();
            document.Save(ms, type);
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Imports the data from XML file to the table.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.Exception">reader</exception>
        /// <exception cref="XmlException">Unexpected xml tag  + reader.LocalName</exception>
        private static void ImportDataToTable(WTable table)
        {
            FileStream fs     = new FileStream(@"../../../Suppliers.xml", FileMode.Open, FileAccess.Read);
            XmlReader  reader = XmlReader.Create(fs);

            if (reader == null)
            {
                throw new Exception("reader");
            }
            while (reader.NodeType != XmlNodeType.Element)
            {
                reader.Read();
            }
            if (reader.LocalName != "SuppliersList")
            {
                throw new XmlException("Unexpected xml tag " + reader.LocalName);
            }
            reader.Read();
            while (reader.NodeType == XmlNodeType.Whitespace)
            {
                reader.Read();
            }
            while (reader.LocalName != "SuppliersList")
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.LocalName)
                    {
                    case "Suppliers":
                        //Adds new row to the table for importing data from next record.
                        WTableRow tableRow = table.AddRow(true);
                        ImportDataToRow(reader, tableRow);
                        break;
                    }
                }
                else
                {
                    reader.Read();
                    if ((reader.LocalName == "SuppliersList") && reader.NodeType == XmlNodeType.EndElement)
                    {
                        break;
                    }
                }
            }
            reader.Dispose();
            fs.Dispose();
        }
Exemplo n.º 9
0
 static void Main(string[] args)
 {
     //Creates new Word document instance for Word processing
     using (WordDocument document = new WordDocument())
     {
         //Adds a section to the Word document
         IWSection section = document.AddSection();
         //Sets the page margin
         section.PageSetup.Margins.All = 72;
         //Adds a paragrah to the section
         IWParagraph paragraph = section.AddParagraph();
         paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
         paragraph.ParagraphFormat.AfterSpacing        = 20;
         IWTextRange textRange = paragraph.AppendText("Suppliers");
         textRange.CharacterFormat.FontSize  = 14;
         textRange.CharacterFormat.Bold      = true;
         textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(255, 50, 62, 79);
         //Modifies the font size as 10 for default paragraph style
         WParagraphStyle style = document.Styles.FindByName("Normal") as WParagraphStyle;
         style.CharacterFormat.FontSize = 10;
         //Adds a table to the section
         WTable table = section.AddTable() as WTable;
         table.ResetCells(1, 6);
         table[0, 0].Width = 52f;
         table[0, 0].AddParagraph().AppendText("Supplier ID");
         table[0, 1].Width = 128f;
         table[0, 1].AddParagraph().AppendText("Company Name");
         table[0, 2].Width = 70f;
         table[0, 2].AddParagraph().AppendText("Contact Name");
         table[0, 3].Width = 92f;
         table[0, 3].AddParagraph().AppendText("Address");
         table[0, 4].Width = 66.5f;
         table[0, 4].AddParagraph().AppendText("City");
         table[0, 5].Width = 56f;
         table[0, 5].AddParagraph().AppendText("Country");
         //Imports data to the table.
         ImportDataToTable(table);
         //Applies the built-in table style (Medium Shading 1 Accent 1) to the table
         table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent1);
         //Saves the file in the given path
         Stream docStream = File.Create(Path.GetFullPath(@"Result.docx"));
         document.Save(docStream, FormatType.Docx);
         docStream.Dispose();
     }
 }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            //Creates new Word document instance for Word processing
            WordDocument document = new WordDocument();
            //Opens the input Word document
            Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Table.docx"));

            document.Open(docStream, FormatType.Docx);
            docStream.Dispose();
            //Adds a new custom table style
            WTableStyle tableStyle = document.AddTableStyle("CustomStyle") as WTableStyle;

            //Applies formatting for whole table
            tableStyle.TableProperties.RowStripe       = 1;
            tableStyle.TableProperties.ColumnStripe    = 1;
            tableStyle.TableProperties.Paddings.Top    = 0;
            tableStyle.TableProperties.Paddings.Bottom = 0;
            tableStyle.TableProperties.Paddings.Left   = 5.4f;
            tableStyle.TableProperties.Paddings.Right  = 5.4f;
            //Applies conditional formatting for first row
            ConditionalFormattingStyle firstRowStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.FirstRow);

            firstRowStyle.CharacterFormat.Bold      = true;
            firstRowStyle.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255);
            firstRowStyle.CellProperties.BackColor  = Syncfusion.Drawing.Color.Blue;
            //Applies conditional formatting for first column
            ConditionalFormattingStyle firstColumnStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.FirstColumn);

            firstColumnStyle.CharacterFormat.Bold = true;
            //Applies conditional formatting for odd row
            ConditionalFormattingStyle oddRowBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.OddRowBanding);

            oddRowBandingStyle.CellProperties.BackColor = Syncfusion.Drawing.Color.WhiteSmoke;
            //Gets table to apply style
            WTable table = (WTable)document.LastSection.Tables[0];

            //Applies the custom table style to the table
            table.ApplyStyle("CustomStyle");
            //Saves the file in the given path
            docStream = File.Create(Path.GetFullPath(@"Result.docx"));
            document.Save(docStream, FormatType.Docx);
            docStream.Dispose();
            //Releases the resources of Word document instance
            document.Dispose();
        }
Exemplo n.º 11
0
        private static void IterateTextBody(WTextBody textBody)
        {
            for (int i = 0; i < textBody.ChildEntities.Count; i++)
            {
                IEntity bodyItemEntity = textBody.ChildEntities[i];
                switch (bodyItemEntity.EntityType)
                {
                case EntityType.Paragraph:
                    WParagraph paragraph = bodyItemEntity as WParagraph;
                    break;

                case EntityType.Table:
                    WTable table = bodyItemEntity as WTable;
                    IterateTable(table);
                    break;
                }
            }
        }
Exemplo n.º 12
0
        private async void StileTabellaWordAsync()
        {
            //Crea una istanza della classe WordDocument
            WordDocument document = new WordDocument();

            //Apre un documento word esistente nella istanza DocIO
            //document.Open("Table.docx", FormatType.Docx);
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile   storageFile;

            try
            {
                storageFile = await local.GetFileAsync("Table.docx");
            }
            catch (Exception)
            {
                return;
            }
            var streamFile = await storageFile.OpenStreamForReadAsync();

            document.Open(streamFile, FormatType.Docx);

            WSection section = document.Sections[0];

            WTable table = section.Tables[0] as WTable;

            //Applica alla tabella lo stile built-in "LightShading"
            table.ApplyStyle(BuiltinTableStyle.LightShading);

            //Salva e chiudi l'istanza del documento
            //Salva il documento su memory stream
            MemoryStream stream = new MemoryStream();
            await document.SaveAsync(stream, FormatType.Docx);

            //Libera le risorse impegnate dall'istanza WordDocument
            document.Close();

            //Salva lo stream come file di documento Word nella macchina locale
            StorageFile stFile = await Save(stream, "TableStyle.docx");

            DefaultLaunch("TableStyle.docx");
        }
 static void Main(string[] args)
 {
     //Creates new Word document instance for Word processing
     using (WordDocument document = new WordDocument())
     {
         //Opens the input Word document
         Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
         document.Open(docStream, FormatType.Docx);
         docStream.Dispose();
         //Creates a new table
         WTable table = new WTable(document);
         table.ResetCells(1, 6);
         table[0, 0].Width = 52f;
         table[0, 0].AddParagraph().AppendText("Supplier ID");
         table[0, 1].Width = 128f;
         table[0, 1].AddParagraph().AppendText("Company Name");
         table[0, 2].Width = 70f;
         table[0, 2].AddParagraph().AppendText("Contact Name");
         table[0, 3].Width = 92f;
         table[0, 3].AddParagraph().AppendText("Address");
         table[0, 4].Width = 66.5f;
         table[0, 4].AddParagraph().AppendText("City");
         table[0, 5].Width = 56f;
         table[0, 5].AddParagraph().AppendText("Country");
         //Imports data to the table
         ImportDataToTable(table);
         //Applies the built-in table style (Medium Shading 1 Accent 1) to the table
         table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent1);
         //Replaces the table placeholder text with a new table
         TextBodyPart bodyPart = new TextBodyPart(document);
         bodyPart.BodyItems.Add(table);
         document.Replace("[Suppliers table]", bodyPart, true, true, true);
         //Saves the resultant file in the given path
         docStream = File.Create(Path.GetFullPath(@"Result.docx"));
         document.Save(docStream, FormatType.Docx);
         docStream.Dispose();
     }
 }
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Assembly execAssem = typeof(BookmarkNavigationDemo).GetTypeInfo().Assembly;
            // Creating a new document.
            WordDocument document = new WordDocument();

            //Adds section with one empty paragraph to the Word document
            document.EnsureMinimal();
            //sets the page margins
            document.LastSection.PageSetup.Margins.All = 72f;
            //Appends bookmark to the paragraph
            document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
            document.LastParagraph.AppendText("Northwind database with relational data");
            document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
            // Open an existing template document with single section.
            WordDocument nwdInformation = new WordDocument();
            Stream       inputStream    = execAssem.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Bookmark_Template.doc");
            // Open an existing template document.
            await nwdInformation.OpenAsync(inputStream, FormatType.Doc);

            inputStream.Dispose();
            // Open an existing template document with multiple section.
            WordDocument templateDocument = new WordDocument();

            inputStream = execAssem.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.BkmkDocumentPart_Template.doc");
            // Open an existing template document.
            await templateDocument.OpenAsync(inputStream, FormatType.Doc);

            inputStream.Dispose();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the template document.
            BookmarksNavigator bk = new BookmarksNavigator(templateDocument);

            // Move to the NorthWind bookmark in template document
            bk.MoveToBookmark("NorthWind");
            //Gets the bookmark content as WordDocumentPart
            WordDocumentPart documentPart = bk.GetContent();

            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            // Move to the information bookmark
            bk.MoveToBookmark("Information");
            // Get the content of information bookmark.
            TextBodyPart bodyPart = bk.GetBookmarkContent();

            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            // Move to the NorthWind database in the destination document
            bk.MoveToBookmark("NorthwindDatabase");
            //Replace the bookmark content using word document parts
            bk.ReplaceContent(documentPart);
            // Move to the Northwind_Information in the destination document
            bk.MoveToBookmark("Northwind_Information");
            // Replacing content of Northwind_Information bookmark.
            bk.ReplaceBookmarkContent(bodyPart);
            // Move to the text bookmark
            bk.MoveToBookmark("Text");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting text inside the bookmark. This will preserve the source formatting
            bk.InsertText("Northwind Database contains the following table:");
            #region tableinsertion
            WTable tbl = new WTable(document);
            tbl.TableFormat.Borders.BorderType = BorderStyle.None;
            tbl.TableFormat.IsAutoResized      = true;
            tbl.ResetCells(8, 2);
            IWParagraph paragraph;
            tbl.Rows[0].IsHeader = true;
            paragraph            = tbl[0, 0].AddParagraph();
            paragraph.AppendText("Suppliers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[0, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 0].AddParagraph();
            paragraph.AppendText("Customers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 0].AddParagraph();
            paragraph.AppendText("Employees");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 0].AddParagraph();
            paragraph.AppendText("Products");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 0].AddParagraph();
            paragraph.AppendText("Inventory");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 1].AddParagraph();
            paragraph.AppendText("2");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 0].AddParagraph();
            paragraph.AppendText("Shippers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 0].AddParagraph();
            paragraph.AppendText("PO Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 0].AddParagraph();
            paragraph.AppendText("Sales Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 1].AddParagraph();
            paragraph.AppendText("7");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;


            bk.InsertTable(tbl);
            #endregion
            //Move to image bookmark
            bk.MoveToBookmark("Image");
            //Deletes the bookmark
            bk.DeleteBookmarkContent(true);
            // Inserting image to the bookmark.
            IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
            inputStream = execAssem.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Northwind.png");
            pic.LoadImage(inputStream);
            inputStream.Dispose();
            pic.WidthScale  = 50f; // It reduce the image size because it don't fit
            pic.HeightScale = 75f; // in document page.
            Save(rdDoc.IsChecked == true, document);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Creates word document with built - in table styles
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                // Open the template document.
                WordDocument document = new WordDocument(fileName + "TemplateTableStyle.doc");

                //Create MailMergeDataTable
                MailMergeDataTable mailMergeDataTable = GetMailMergeDataTable();

                // Execute Mail Merge with groups.
                document.MailMerge.ExecuteGroup(mailMergeDataTable);

                #region Built-in table styles
                //Get table to apply style.
                WTable table = (WTable)document.LastSection.Tables[0];

                //Apply built-in table style to the table.
                table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent5);
                #endregion

                # region Save Document

                //Save as docx format
                if (wordDocxRadioBtn.Checked)
                {
                    //Saving the document as .docx
                    document.Save("Sample.docx", FormatType.Docx);
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
#if NETCORE
                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.docx")
                            {
                                UseShellExecute = true
                            };
                            process.Start();
#else
                            System.Diagnostics.Process.Start("Sample.docx");
#endif
                            //Exit
                            this.Close();
                        }
                        catch (Win32Exception ex)
                        {
                            MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                //Save as pdf format
                else if (pdfRadioBtn.Checked)
                {
                    DocToPDFConverter converter = new DocToPDFConverter();
                    //Convert word document into PDF document
                    PdfDocument pdfDoc = converter.ConvertToPDF(document);
                    //Save the pdf file
                    pdfDoc.Save("Sample.pdf");
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
#if NETCORE
                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf")
                            {
                                UseShellExecute = true
                            };
                            process.Start();
#else
                            System.Diagnostics.Process.Start("Sample.pdf");
#endif
                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
                # endregion
            }
Exemplo n.º 16
0
        public ActionResult TableStyles(string Group1, string Group2)
        {
            if (Group1 == null)
            {
                return(View());
            }
            string       dataPath = ResolveApplicationDataPath("TemplateTableStyle.doc", "App_Data\\DocIO");
            WordDocument document = new WordDocument(dataPath);

            string dataBase = ResolveApplicationDataPath("Northwind.mdb", "App_Data");
            // Get Data from the Database.
            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataBase);

            conn.Open();
            DataSet          ds      = new DataSet();
            OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from Suppliers", conn);

            adapter.Fill(ds);
            ds.Tables[0].TableName = "Suppliers";
            adapter.Dispose();
            conn.Close();

            // Execute Mail Merge with groups.
            document.MailMerge.ExecuteGroup(ds.Tables[0]);

            #region Built-in table styles
            if (Group1 == "Built-in")
            {
                //Get table to apply style.
                WTable table = (WTable)document.LastSection.Tables[0];

                //Apply built-in table style to the table.
                table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent5);
            }
            #endregion Built-in table styles

            #region Custom Style
            else
            {
                #region Custom table styles
                //Get table to apply style
                WTable table = (WTable)document.LastSection.Tables[0];
                //Apply custom table style to the table
                #region Apply Table style
                WTableStyle                tableStyle = document.AddTableStyle("Tablestyle") as WTableStyle;
                System.Drawing.Color       borderColor = System.Drawing.Color.WhiteSmoke;
                System.Drawing.Color       firstRowBackColor = System.Drawing.Color.Blue;
                System.Drawing.Color       backColor = System.Drawing.Color.WhiteSmoke;
                ConditionalFormattingStyle firstRowStyle, lastRowStyle, firstColumnStyle, lastColumnStyle, oddColumnBandingStyle, oddRowBandingStyle, evenRowBandingStyle;

                #region Table Properties
                tableStyle.TableProperties.RowStripe    = 1;
                tableStyle.TableProperties.ColumnStripe = 1;
                tableStyle.TableProperties.LeftIndent   = 0;

                tableStyle.TableProperties.Paddings.Top    = 0;
                tableStyle.TableProperties.Paddings.Bottom = 0;
                tableStyle.TableProperties.Paddings.Left   = 5.4f;
                tableStyle.TableProperties.Paddings.Right  = 5.4f;

                tableStyle.TableProperties.Borders.Top.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Top.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Top.Color      = System.Drawing.Color.AliceBlue;
                tableStyle.TableProperties.Borders.Top.Space      = 0;

                tableStyle.TableProperties.Borders.Bottom.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Bottom.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Bottom.Color      = borderColor;
                tableStyle.TableProperties.Borders.Bottom.Space      = 0;

                tableStyle.TableProperties.Borders.Left.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Left.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Left.Color      = borderColor;
                tableStyle.TableProperties.Borders.Left.Space      = 0;

                tableStyle.TableProperties.Borders.Right.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Right.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Right.Color      = borderColor;
                tableStyle.TableProperties.Borders.Right.Space      = 0;

                tableStyle.TableProperties.Borders.Horizontal.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Horizontal.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Horizontal.Color      = borderColor;
                tableStyle.TableProperties.Borders.Horizontal.Space      = 0;
                #endregion

                #region Conditional Formatting Properties
                #region First Row Conditional Formatting Style
                firstRowStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.FirstRow);

                #region Character format
                firstRowStyle.CharacterFormat.Bold      = true;
                firstRowStyle.CharacterFormat.BoldBidi  = true;
                firstRowStyle.CharacterFormat.TextColor = System.Drawing.Color.FromArgb(255, 255, 255, 255);
                #endregion

                #region Table Cell Properties
                firstRowStyle.CellProperties.Borders.Top.BorderType = BorderStyle.Single;
                firstRowStyle.CellProperties.Borders.Top.LineWidth  = 1f;
                firstRowStyle.CellProperties.Borders.Top.Color      = borderColor;
                firstRowStyle.CellProperties.Borders.Top.Space      = 0;

                firstRowStyle.CellProperties.Borders.Bottom.BorderType = BorderStyle.Single;
                firstRowStyle.CellProperties.Borders.Bottom.LineWidth  = 1f;
                firstRowStyle.CellProperties.Borders.Bottom.Color      = borderColor;
                firstRowStyle.CellProperties.Borders.Bottom.Space      = 0;

                firstRowStyle.CellProperties.Borders.Left.BorderType = BorderStyle.Single;
                firstRowStyle.CellProperties.Borders.Left.LineWidth  = 1f;
                firstRowStyle.CellProperties.Borders.Left.Color      = borderColor;
                firstRowStyle.CellProperties.Borders.Left.Space      = 0;

                firstRowStyle.CellProperties.Borders.Right.BorderType = BorderStyle.Single;
                firstRowStyle.CellProperties.Borders.Right.LineWidth  = 1f;
                firstRowStyle.CellProperties.Borders.Right.Color      = borderColor;
                firstRowStyle.CellProperties.Borders.Right.Space      = 0;

                firstRowStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;

                firstRowStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;

                firstRowStyle.CellProperties.BackColor    = firstRowBackColor;
                firstRowStyle.CellProperties.ForeColor    = System.Drawing.Color.FromArgb(0, 255, 255, 255);
                firstRowStyle.CellProperties.TextureStyle = TextureStyle.TextureNone;
                #endregion
                #endregion

                #region Last Row Conditional Formatting Style
                lastRowStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.LastRow);

                #region Character format
                lastRowStyle.CharacterFormat.Bold     = true;
                lastRowStyle.CharacterFormat.BoldBidi = true;
                #endregion

                #region Table Cell Properties
                lastRowStyle.CellProperties.Borders.Top.BorderType = BorderStyle.Double;
                lastRowStyle.CellProperties.Borders.Top.LineWidth  = .75f;
                lastRowStyle.CellProperties.Borders.Top.Color      = borderColor;
                lastRowStyle.CellProperties.Borders.Top.Space      = 0;

                lastRowStyle.CellProperties.Borders.Bottom.BorderType = BorderStyle.Single;
                lastRowStyle.CellProperties.Borders.Bottom.LineWidth  = 1f;
                lastRowStyle.CellProperties.Borders.Bottom.Color      = borderColor;
                lastRowStyle.CellProperties.Borders.Bottom.Space      = 0;

                lastRowStyle.CellProperties.Borders.Left.BorderType = BorderStyle.Single;
                lastRowStyle.CellProperties.Borders.Left.LineWidth  = 1f;
                lastRowStyle.CellProperties.Borders.Left.Color      = borderColor;
                lastRowStyle.CellProperties.Borders.Left.Space      = 0;

                lastRowStyle.CellProperties.Borders.Right.BorderType = BorderStyle.Single;
                lastRowStyle.CellProperties.Borders.Right.LineWidth  = 1f;
                lastRowStyle.CellProperties.Borders.Right.Color      = borderColor;
                lastRowStyle.CellProperties.Borders.Right.Space      = 0;

                lastRowStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;

                lastRowStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;
                #endregion
                #endregion

                #region First Column Conditional Formatting Style
                firstColumnStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.FirstColumn);
                #region Character format
                firstColumnStyle.CharacterFormat.Bold     = true;
                firstColumnStyle.CharacterFormat.BoldBidi = true;
                #endregion
                #endregion

                #region Last Column Conditional Formatting Style
                lastColumnStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.LastColumn);
                #region Character format
                lastColumnStyle.CharacterFormat.Bold     = true;
                lastColumnStyle.CharacterFormat.BoldBidi = true;
                #endregion
                #endregion

                #region Odd Column Banding Conditional Formatting Style
                oddColumnBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.OddColumnBanding);
                #region Table Cell Properties
                oddColumnBandingStyle.CellProperties.BackColor    = backColor;
                oddColumnBandingStyle.CellProperties.ForeColor    = System.Drawing.Color.FromArgb(0, 255, 255, 255);
                oddColumnBandingStyle.CellProperties.TextureStyle = TextureStyle.TextureNone;
                #endregion
                #endregion

                #region Odd Row Banding Conditional Formatting Style
                oddRowBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.OddRowBanding);
                #region Table Cell Properties
                oddRowBandingStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;

                oddRowBandingStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;

                oddRowBandingStyle.CellProperties.BackColor    = backColor;
                oddRowBandingStyle.CellProperties.ForeColor    = System.Drawing.Color.FromArgb(0, 255, 255, 255);
                oddRowBandingStyle.CellProperties.TextureStyle = TextureStyle.TextureNone;
                #endregion
                #endregion

                #region Even Row Banding Conditional Formatting Style
                evenRowBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.EvenRowBanding);
                #region Table Cell Properties
                evenRowBandingStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;
                evenRowBandingStyle.CellProperties.Borders.Vertical.BorderType   = BorderStyle.Cleared;
                #endregion
                #endregion
                #endregion
                #endregion
                table.ApplyStyle("Tablestyle");
                #endregion
            }
            #endregion Custom Style

            #region Document save option
            //Save as .docx format
            if (Group2 == "WordDocx")
            {
                return(document.ExportAsActionResult("Sample.docx", FormatType.Docx, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            // Save as WordML(.xml) format
            else if (Group2 == "WordML")
            {
                return(document.ExportAsActionResult("Sample.xml", FormatType.WordML, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            //Save as .pdf format
            else if (Group2 == "Pdf")
            {
                DocToPDFConverter converter = new DocToPDFConverter();
                PdfDocument       pdfDoc    = converter.ConvertToPDF(document);

                return(pdfDoc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
            #endregion Document save option

            return(View());
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            // Creating a new document.
            WordDocument document = new WordDocument();

            //Adds section with one empty paragraph to the Word document
            document.EnsureMinimal();
            //sets the page margins
            document.LastSection.PageSetup.Margins.All = 72f;
            //Appends bookmark to the paragraph
            document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
            document.LastParagraph.AppendText("Northwind database with relational data");
            document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
            // Open an existing template document with single section.
            WordDocument nwdInformation = new WordDocument();
            Stream       inputStream    = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Bookmark_Template.docx");

            // Open an existing template document.
            nwdInformation.Open(inputStream, FormatType.Doc);
            inputStream.Dispose();
            // Open an existing template document with multiple section.
            WordDocument templateDocument = new WordDocument();

            inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.BkmkDocumentPart_Template.docx");
            // Open an existing template document.
            templateDocument.Open(inputStream, FormatType.Doc);
            inputStream.Dispose();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the template document.
            BookmarksNavigator bk = new BookmarksNavigator(templateDocument);

            // Move to the NorthWind bookmark in template document
            bk.MoveToBookmark("NorthWind");
            //Gets the bookmark content as WordDocumentPart
            WordDocumentPart documentPart = bk.GetContent();

            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            // Move to the information bookmark
            bk.MoveToBookmark("Information");
            // Get the content of information bookmark.
            TextBodyPart bodyPart = bk.GetBookmarkContent();

            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            // Move to the NorthWind database in the destination document
            bk.MoveToBookmark("NorthwindDatabase");
            //Replace the bookmark content using word document parts
            bk.ReplaceContent(documentPart);
            // Move to the Northwind_Information in the destination document
            bk.MoveToBookmark("Northwind_Information");
            // Replacing content of Northwind_Information bookmark.
            bk.ReplaceBookmarkContent(bodyPart);
            #region Bookmark selection for table
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            bk.MoveToBookmark("SuppliersTable");
            //Sets the column index where the bookmark starts within the table
            bk.CurrentBookmark.FirstColumn = 1;
            //Sets the column index where the bookmark ends within the table
            bk.CurrentBookmark.LastColumn = 5;
            // Get the content of suppliers table bookmark.
            bodyPart = bk.GetBookmarkContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            bk.MoveToBookmark("Table");
            bk.ReplaceBookmarkContent(bodyPart);
            #endregion
            // Move to the text bookmark
            bk.MoveToBookmark("Text");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting text inside the bookmark. This will preserve the source formatting
            bk.InsertText("Northwind Database contains the following table:");
            #region tableinsertion
            WTable tbl = new WTable(document);
            tbl.TableFormat.Borders.BorderType = BorderStyle.None;
            tbl.TableFormat.IsAutoResized      = true;
            tbl.ResetCells(8, 2);
            IWParagraph paragraph;
            tbl.Rows[0].IsHeader = true;
            paragraph            = tbl[0, 0].AddParagraph();
            paragraph.AppendText("Suppliers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[0, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 0].AddParagraph();
            paragraph.AppendText("Customers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 0].AddParagraph();
            paragraph.AppendText("Employees");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 0].AddParagraph();
            paragraph.AppendText("Products");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 0].AddParagraph();
            paragraph.AppendText("Inventory");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 1].AddParagraph();
            paragraph.AppendText("2");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 0].AddParagraph();
            paragraph.AppendText("Shippers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 0].AddParagraph();
            paragraph.AppendText("PO Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 0].AddParagraph();
            paragraph.AppendText("Sales Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 1].AddParagraph();
            paragraph.AppendText("7");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;


            bk.InsertTable(tbl);
            #endregion
            bk.MoveToBookmark("Image");
            bk.DeleteBookmarkContent(true);
            // Inserting image to the bookmark.
            IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
            inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Northwind.png");
            pic.LoadImage(inputStream);
            inputStream.Dispose();
            pic.WidthScale  = 50f; // It reduce the image size because it don't fit
            pic.HeightScale = 75f; // in document page.


            #region Saving Document
            MemoryStream stream = new MemoryStream();
            document.Save(stream, FormatType.Word2013);
            document.Close();
            if (stream != null)
            {
                SaveAndroid androidSave = new SaveAndroid();
                androidSave.Save("BookmarkNavigation.docx", "application/msword", stream, m_context);
            }

            #endregion
        }
Exemplo n.º 18
0
        private async void FormattaTabellaWordAsync()
        {
            //Crea una istanza della classe WordDocument (un documento Word vuoto)
            WordDocument document = new WordDocument();

            //Apre un documento word esistente nella istanza DocIO
            //document.Open("Table.docx", FormatType.Docx);
            StorageFolder local       = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile   storageFile = await local.GetFileAsync("Table.docx");

            var streamFile = await storageFile.OpenStreamForReadAsync();

            document.Open(streamFile, FormatType.Docx);

            //Accede all'istanza della prima section del documento Word
            WSection section = document.Sections[0];

            //Accede all'istanza della prima tabella nella section
            WTable table = section.Tables[0] as WTable;

            //Specifica il titolo della tabella
            table.Title = "PriceDetails";

            //Specifica la descrizione della tabella
            table.Description = "This table shows the price details of various fruits";

            //Specifica l'indentazione della tabella
            table.IndentFromLeft = 50;

            //Specifica il colore di background della tabella
            table.TableFormat.BackColor = Color.FromArgb(192, 192, 192);

            //Specifica l'allineamento orizzontale della tabella
            table.TableFormat.HorizontalAlignment = RowAlignment.Left;

            //Specifica il padding left, right, top and bottom di tutte le celle della tabella
            table.TableFormat.Paddings.All = 10;

            //Specifica l'auto resize della tabella per ridimensionare automaticamente tutte le celle sulla base del loro contenuto
            table.TableFormat.IsAutoResized = true;

            //Specifica la dimensione riga del border top, bottom, left and right della tabella
            table.TableFormat.Borders.LineWidth = 2f;

            //Specifica la dimensione riga del border orizzontale
            table.TableFormat.Borders.Horizontal.LineWidth = 2f;

            //Specifica la dimensione riga del border verticale
            table.TableFormat.Borders.Vertical.LineWidth = 2f;

            //Specifica il top, bottom, left and right border color delle tabelle
            table.TableFormat.Borders.Color = Color.Red;

            //Specifica il border color orizzontale della tabella
            table.TableFormat.Borders.Horizontal.Color = Color.Red;

            //Specifica il border color vericale della tabella
            table.TableFormat.Borders.Vertical.Color = Color.Red;

            //Specifica il tipo di border della tabella
            table.TableFormat.Borders.BorderType = BorderStyle.Double;

            //Accede all'istanza della prima riga della tabella
            WTableRow row = table.Rows[0];

            //Specifica l'altezza della riga
            row.Height = 20;

            //Specifica il tipo di altezza della riga
            row.HeightType = TableRowHeightType.AtLeast;

            //Salva il documento su memory stream
            MemoryStream stream = new MemoryStream();
            await document.SaveAsync(stream, FormatType.Docx);

            //Libera le risorse impegnate dall'istanza WordDocument
            document.Close();

            //Salva lo stream come file di documento Word nella macchina locale
            StorageFile stFile = await Save(stream, "TableFormatting.docx");

            DefaultLaunch("TableFormatting.docx");
        }
Exemplo n.º 19
0
        public ActionResult ExportDefault(string SaveOption)
        {
            if (SaveOption == null)
            {
                ErrorMessage = "";
                return(View());
            }
            else if (SaveOption == "Excel 2013" || SaveOption == "Excel 2010" || SaveOption == "Excel 2007" || SaveOption == "Excel 2003" || SaveOption == "CSV")
            {
                ErrorMessage = "";
                string          path      = new System.IO.DirectoryInfo(Request.PhysicalPath + "..\\..\\..\\..\\..\\..\\..\\Data\\AdventureWorks\\AdventureWorks_Person_Contact.csv").FullName;
                CheckFileStatus CheckFile = new CheckFileStatus();
                ErrorMessage = CheckFile.CheckFile(path);
                if (ErrorMessage == "")
                {
                    try
                    {
                        //Instantiate the spreadsheet creation engine.
                        ExcelEngine excelEngine = new ExcelEngine();

                        //Instantiate the excel application object.
                        IApplication application = excelEngine.Excel;

                        //A new workbook is created.[Equivalent to creating a new workbook in MS Excel]
                        //The new workbook will have 1 worksheets
                        IWorkbook workbook = application.Workbooks.Create(1);

                        //The first worksheet object in the worksheets collection is accessed.
                        IWorksheet worksheet = workbook.Worksheets[0];
                        var        result    = CustomersData.list();
                        ErrorMessage = null;

                        //Adding header text for worksheet
                        worksheet[1, 1].Text = "Contact Id";
                        worksheet[1, 2].Text = "Full Name";
                        worksheet[1, 3].Text = "Age";
                        worksheet[1, 4].Text = "Phone Number";
                        worksheet[1, 5].Text = "Email Id";
                        worksheet[1, 6].Text = "Modified Date";

                        int i = 1;
                        //Reading each row from the fetched result
                        foreach (PersonDetail records in result)
                        {
                            //Reading each data from the row
                            //Assigning each data to the worksheet based on index
                            worksheet[i + 1, 1].Text = records.ContactId;
                            worksheet[i + 1, 2].Text = records.FullName;
                            worksheet[i + 1, 3].Text = records.Age;
                            worksheet[i + 1, 4].Text = records.PhoneNumber;
                            worksheet[i + 1, 5].Text = records.EmailId;
                            worksheet[i + 1, 6].Text = records.ModifiedDate;
                            i++;
                        }
                        //Assigning Header text with cell color
                        worksheet.Range["A1:F1"].CellStyle.Color      = System.Drawing.Color.FromArgb(51, 153, 51);
                        worksheet.Range["A1:F1"].CellStyle.Font.Color = Syncfusion.XlsIO.ExcelKnownColors.White;
                        worksheet.Range["A1:F1"].CellStyle.Font.Bold  = true;
                        worksheet.UsedRange.AutofitColumns();
                        #endregion

                        //Save as .xls format
                        if (SaveOption == "Excel 2003")
                        {
                            return(excelEngine.SaveAsActionResult(workbook, "Sample.xls", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel97));
                        }
                        //Save as .xlsx format
                        else if (SaveOption == "Excel 2007")
                        {
                            workbook.Version = ExcelVersion.Excel2007;
                            return(excelEngine.SaveAsActionResult(workbook, "Sample.xlsx", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel2007));
                        }
                        //Save as .xlsx format
                        else if (SaveOption == "Excel 2010")
                        {
                            workbook.Version = ExcelVersion.Excel2010;
                            return(excelEngine.SaveAsActionResult(workbook, "Sample.xlsx", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel2010));
                        }
                        //Save as .xlsx format
                        else if (SaveOption == "Excel 2013")
                        {
                            workbook.Version = ExcelVersion.Excel2013;
                            return(excelEngine.SaveAsActionResult(workbook, "Sample.xlsx", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel2013));
                        }
                        //Save as .csv format
                        else if (SaveOption == "CSV")
                        {
                            return(excelEngine.SaveAsActionResult(workbook, "Sample.csv", ",", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.CSV));
                        }
                        //Close the workbook
                        workbook.Close();

                        //Close the excelengine
                        excelEngine.Dispose();
                    }
                    catch (HqlConnectionException)
                    {
                        ErrorMessage = "Could not establish a connection to the HiveServer. Please run HiveServer2 from the Syncfusion service manager dashboard.";
                    }
                }

                return(View());
            }
            else
            {
                ErrorMessage = "";
                string          path      = new System.IO.DirectoryInfo(Request.PhysicalPath + "..\\..\\..\\..\\..\\..\\..\\Data\\AdventureWorks\\AdventureWorks_Person_Contact.csv").FullName;
                CheckFileStatus CheckFile = new CheckFileStatus();
                ErrorMessage = CheckFile.CheckFile(path);
                //A new document is created.
                if (ErrorMessage == "")
                {
                    try
                    {
                        WordDocument document = new WordDocument();

                        //Adding new table to the document
                        WTable doctable = new WTable(document);

                        //Adding a new section to the document.
                        WSection section = document.AddSection() as WSection;

                        //Set Margin of the section
                        section.PageSetup.Margins.All = 72;

                        //Set page size of the section
                        section.PageSetup.PageSize = new SizeF(800, 792);

                        //Create Paragraph styles
                        WParagraphStyle style = document.AddParagraphStyle("Normal") as WParagraphStyle;
                        style.CharacterFormat.FontName = "Calibri";
                        style.CharacterFormat.FontSize = 11f;

                        //Reading the data from the table
                        var result = CustomersData.list();
                        doctable.AddRow(true, false);

                        //creating new cell
                        WTableCell cell = new WTableCell(document);

                        //Create a character format for declaring font color and style for the text inside the cell
                        WCharacterFormat charFormat = new WCharacterFormat(document);
                        charFormat.TextColor = System.Drawing.Color.White;
                        charFormat.Bold      = true;

                        //Adding header text for the table
                        cell.AddParagraph().AppendText("Customer Id").ApplyCharacterFormat(charFormat);
                        cell.Width = 75;
                        cell.CellFormat.BackColor = System.Drawing.Color.FromArgb(51, 153, 51);
                        //Adding cell to rows
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Full Name").ApplyCharacterFormat(charFormat);
                        cell.Width = 90;
                        cell.CellFormat.BackColor = System.Drawing.Color.FromArgb(51, 153, 51);
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Age").ApplyCharacterFormat(charFormat);
                        cell.Width = 75;
                        cell.CellFormat.BackColor = System.Drawing.Color.FromArgb(51, 153, 51);
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Phone Number").ApplyCharacterFormat(charFormat);
                        cell.Width = 90;
                        cell.CellFormat.BackColor = System.Drawing.Color.FromArgb(51, 153, 51);
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Email Id").ApplyCharacterFormat(charFormat);
                        cell.Width = 180;
                        cell.CellFormat.BackColor = System.Drawing.Color.FromArgb(51, 153, 51);
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Modified Date").ApplyCharacterFormat(charFormat);
                        cell.Width = 125;
                        cell.CellFormat.BackColor = System.Drawing.Color.FromArgb(51, 153, 51);
                        doctable.Rows[0].Cells.Add(cell);

                        int i = 1;
                        //Reading each row from the fetched result
                        foreach (PersonDetail records in result)
                        {
                            doctable.AddRow(true, false);

                            //Assigning fetched result to the cell
                            cell = new WTableCell(document);
                            cell.AddParagraph().AppendText(records.ContactId.ToString());
                            cell.Width = 75;
                            doctable.Rows[i].Cells.Add(cell);
                            cell = new WTableCell(document);
                            cell.AddParagraph().AppendText(records.FullName.ToString());
                            cell.Width = 90;
                            doctable.Rows[i].Cells.Add(cell);
                            cell = new WTableCell(document);
                            cell.AddParagraph().AppendText(records.Age.ToString());
                            cell.Width = 75;
                            doctable.Rows[i].Cells.Add(cell);
                            cell = new WTableCell(document);
                            cell.AddParagraph().AppendText(records.PhoneNumber.ToString());
                            cell.Width = 90;
                            doctable.Rows[i].Cells.Add(cell);
                            cell = new WTableCell(document);
                            cell.AddParagraph().AppendText(records.EmailId.ToString());
                            cell.Width = 180;
                            doctable.Rows[i].Cells.Add(cell);
                            cell = new WTableCell(document);
                            cell.AddParagraph().AppendText(records.ModifiedDate.ToString());
                            cell.Width = 125;
                            doctable.Rows[i].Cells.Add(cell);

                            i++;
                        }
                        //Adding table to the section
                        section.Tables.Add(doctable);

                        #region saveOption
                        //Save as .doc Word 97-2003 format
                        if (SaveOption == "Word 97-2003")
                        {
                            return(document.ExportAsActionResult("Sample.doc", FormatType.Doc, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
                        }
                        //Save as .docx Word 2007 format
                        else if (SaveOption == "Word 2007")
                        {
                            return(document.ExportAsActionResult("Sample.docx", FormatType.Word2007, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
                        }
                        //Save as .docx Word 2010 format
                        else if (SaveOption == "Word 2010")
                        {
                            return(document.ExportAsActionResult("Sample.docx", FormatType.Word2010, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
                        }
                        //Save as .docx Word 2013 format
                        else if (SaveOption == "Word 2013")
                        {
                            return(document.ExportAsActionResult("Sample.docx", FormatType.Word2013, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
                        }

                        #endregion saveOption
                    }

                    catch (HqlConnectionException)
                    {
                        ErrorMessage = "Could not establish a connection to the HiveServer. Please run HiveServer2 from the Syncfusion service manager dashboard.";
                    }
                }
                return(View());
            }
        }
Exemplo n.º 20
0
        //Exporting data to word
        public void ExportToWord()
        {
            //A new document is created.
            WordDocument document = new WordDocument();

            //Adding new table to the document
            WTable doctable = new WTable(document);

            //Adding a new section to the document.
            WSection section = document.AddSection() as WSection;

            //Set Margin of the section
            section.PageSetup.Margins.All = 72;

            //Set page size of the section
            section.PageSetup.PageSize = new SizeF(800, 792);

            //Create Paragraph styles
            WParagraphStyle style = document.AddParagraphStyle("Normal") as WParagraphStyle;

            style.CharacterFormat.FontName = "Calibri";
            style.CharacterFormat.FontSize = 11f;

            WCharacterFormat charFormat = new WCharacterFormat(document);

            charFormat.TextColor = System.Drawing.Color.White;
            charFormat.Bold      = true;

            doctable.AddRow(true, false);
            WTableCell cell = new WTableCell(document);

            cell.AddParagraph().AppendText("Customer Id").ApplyCharacterFormat(charFormat);
            cell.Width = 90;
            doctable.Rows[0].Cells.Add(cell);
            cell = new WTableCell(document);
            cell.AddParagraph().AppendText("Full Name").ApplyCharacterFormat(charFormat);
            cell.Width = 90;
            doctable.Rows[0].Cells.Add(cell);
            cell = new WTableCell(document);
            cell.AddParagraph().AppendText("Age").ApplyCharacterFormat(charFormat);
            cell.Width = 90;
            doctable.Rows[0].Cells.Add(cell);
            cell = new WTableCell(document);
            cell.AddParagraph().AppendText("Email Id").ApplyCharacterFormat(charFormat);
            cell.Width = 180;
            doctable.Rows[0].Cells.Add(cell);
            cell = new WTableCell(document);
            cell.AddParagraph().AppendText("Phone Number").ApplyCharacterFormat(charFormat);
            cell.Width = 90;
            doctable.Rows[0].Cells.Add(cell);
            cell = new WTableCell(document);
            cell.AddParagraph().AppendText("Modified Date").ApplyCharacterFormat(charFormat);
            cell.Width = 90;
            doctable.Rows[0].Cells.Add(cell);

            //Reading each row from the fetched result
            for (int i = 0; i < result.Count(); i++)
            {
                HiveRecord records = result[i];
                doctable.AddRow(true, false);

                //Reading each field from the row
                for (int j = 0; j < records.Count; j++)
                {
                    Object fields = records[j];

                    //Adding new cell to the document
                    cell = new WTableCell(document);

                    //Adding each field to the cell
                    cell.AddParagraph().AppendText(fields.ToString());
                    if (j == 3)
                    {
                        cell.Width = 180;
                    }
                    else
                    {
                        cell.Width = 90;
                    }

                    //Adding cell to the table
                    doctable.Rows[i + 1].Cells.Add(cell);
                    doctable.Rows[0].Cells[j].CellFormat.BackColor = System.Drawing.Color.FromArgb(51, 153, 51);
                }
            }

            //Adding table to the section
            section.Tables.Add(doctable);
            //Save as word 2003 format
            if (rdbWord2003.IsChecked.Value)
            {
                //Saving the document to disk.
                document.Save("Sample.doc");

                //Message box confirmation to view the created document.
                if (MessageBox.Show("Do you want to view the MS Word document?", "Document has been created", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                    System.Diagnostics.Process.Start("Sample.doc");
                    //Exit
                    this.Close();
                }
            }
            //Save as word 2007 format
            else if (rdbWord2007.IsChecked.Value)
            {
                //Saving the document as .docx
                document.Save("Sample.docx", FormatType.Word2007);
                //Message box confirmation to view the created document.
                if (MessageBox.Show("Do you want to view the MS Word document?", "Document has been created", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    try
                    {
                        //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                        System.Diagnostics.Process.Start("Sample.docx");
                        //Exit
                        this.Close();
                    }
                    catch (Win32Exception ex)
                    {
                        MessageBox.Show("Word 2007 is not installed in this system");
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
            //Save as word 2010  format
            else if (rdbWord2010.IsChecked.Value)
            {
                //Saving the document as .docx
                document.Save("Sample.docx", FormatType.Word2010);
                //Message box confirmation to view the created document.
                if (MessageBox.Show("Do you want to view the MS Word document?", "Document has been created", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    try
                    {
                        //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                        System.Diagnostics.Process.Start("Sample.docx");
                        //Exit
                        this.Close();
                    }
                    catch (Win32Exception ex)
                    {
                        MessageBox.Show("Word 2010 is not installed in this system");
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
            //Save as word 2013  format
            else if (rdbWord2013.IsChecked.Value)
            {
                //Saving the document as .docx
                document.Save("Sample.docx", FormatType.Word2013);
                //Message box confirmation to view the created document.
                if (MessageBox.Show("Do you want to view the MS Word document?", "Document has been created", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    try
                    {
                        //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                        System.Diagnostics.Process.Start("Sample.docx");
                        //Exit
                        this.Close();
                    }
                    catch (Win32Exception ex)
                    {
                        MessageBox.Show("Word 2013 is not installed in this system");
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
            else
            {
                // Exit
                this.Close();
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates word document with built - in table styles
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                // Open the template document.
                WordDocument document = new WordDocument(fileName + "TemplateTableStyle.doc");

                // Get Data from the Database.
                OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataBase);
                conn.Open();
                DataSet          ds      = new DataSet();
                OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from Suppliers", conn);
                adapter.Fill(ds);
                ds.Tables[0].TableName = "Suppliers";
                adapter.Dispose();
                conn.Close();

                // Execute Mail Merge with groups.
                document.MailMerge.ExecuteGroup(ds.Tables[0]);

                #region Built-in table styles
                //Get table to apply style.
                WTable table = (WTable)document.LastSection.Tables[0];

                //Apply built-in table style to the table.
                table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent5);
                #endregion

                # region Save Document

                //Save as docx format
                if (wordDocxRadioBtn.Checked)
                {
                    //Saving the document as .docx
                    document.Save("Sample.docx", FormatType.Docx);
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                            System.Diagnostics.Process.Start("Sample.docx");
                            //Exit
                            this.Close();
                        }
                        catch (Win32Exception ex)
                        {
                            MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                //Save as pdf format
                else if (pdfRadioBtn.Checked)
                {
                    DocToPDFConverter converter = new DocToPDFConverter();
                    //Convert word document into PDF document
                    PdfDocument pdfDoc = converter.ConvertToPDF(document);
                    //Save the pdf file
                    pdfDoc.Save("Sample.pdf");
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            System.Diagnostics.Process.Start("Sample.pdf");
                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
                # endregion
            }
Exemplo n.º 22
0
        private async void FormattaTabellaWord2Async()
        {
            //Creates an instance of WordDocument class
            WordDocument document = new WordDocument();

            //Apre un documento word esistente nella istanza DocIO
            //document.Open("Table.docx", FormatType.Docx);
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile   storageFile;

            try
            {
                storageFile = await local.GetFileAsync("Table.docx");
            }
            catch (Exception)
            {
                return;
            }
            var streamFile = await storageFile.OpenStreamForReadAsync();

            document.Open(streamFile, FormatType.Docx);

            WSection section = document.Sections[0];

            WTable table = section.Tables[0] as WTable;

            //Accede all'istanza della prima riga della tabella
            WTableRow row = table.Rows[0];

            //Specifica l'altezza della riga
            row.Height = 20;

            //Specifica il tipo di atezza riga
            row.HeightType = TableRowHeightType.AtLeast;

            //Accede all'istanza della prima cella della riga
            WTableCell cell = row.Cells[0];

            //Specifica il back ground color della cella
            cell.CellFormat.BackColor = Color.FromArgb(192, 192, 192);

            //Specifica lo stesso padding della tabella come false per preservare il cell padding corrente
            cell.CellFormat.SamePaddingsAsTable = false;

            //Specifica il left, right, top e bottom padding della cella
            cell.CellFormat.Paddings.Left   = 5;
            cell.CellFormat.Paddings.Right  = 5;
            cell.CellFormat.Paddings.Top    = 5;
            cell.CellFormat.Paddings.Bottom = 5;

            //Specifica l'allineamento verticale del contenuto del testo
            cell.CellFormat.VerticalAlignment = Syncfusion.DocIO.DLS.VerticalAlignment.Middle;

            //Accede all'istanza della seconda cella della riga
            cell = row.Cells[1];

            cell.CellFormat.BackColor = Color.FromArgb(192, 192, 192);

            cell.CellFormat.SamePaddingsAsTable = false;

            //Specifica il left, right, top e bottom padding della cella
            cell.CellFormat.Paddings.All = 5;

            cell.CellFormat.VerticalAlignment = Syncfusion.DocIO.DLS.VerticalAlignment.Middle;

            //Salva il documento su memory stream
            MemoryStream stream = new MemoryStream();
            await document.SaveAsync(stream, FormatType.Docx);

            //Libera le risorse impegnate dall'istanza WordDocument
            document.Close();

            //Salva lo stream come file di documento Word nella macchina locale
            StorageFile stFile = await Save(stream, "TableCellFormatting.docx");

            DefaultLaunch("TableCellFormatting.docx");
        }
Exemplo n.º 23
0
        private void ManipulateBookmarkContents()
        {
            // Creating a new document.
            using (WordDocument document = new WordDocument())
            {
                #region Document Manipulations
                Assembly assembly = typeof(App).GetTypeInfo().Assembly;
                //Adds section with one empty paragraph to the Word document
                document.EnsureMinimal();
                //sets the page margins
                document.LastSection.PageSetup.Margins.All = 72f;
                //Appends bookmark to the paragraph
                document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
                document.LastParagraph.AppendText("Northwind database with relational data");
                document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
                // Open an existing template document with single section.
                WordDocument nwdInformation = new WordDocument();
                Stream       inputStream    = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Bookmark_Template.doc");
                // Open an existing template document.
                nwdInformation.Open(inputStream, FormatType.Doc);
                inputStream.Dispose();
                // Open an existing template document with multiple section.
                WordDocument templateDocument = new WordDocument();
                inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.BkmkDocumentPart_Template.doc");
                // Open an existing template document.
                templateDocument.Open(inputStream, FormatType.Doc);
                inputStream.Dispose();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the template document.
                BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
                // Move to the NorthWind bookmark in template document
                bk.MoveToBookmark("NorthWind");
                //Gets the bookmark content as WordDocumentPart
                WordDocumentPart documentPart = bk.GetContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the Northwind information document.
                bk = new BookmarksNavigator(nwdInformation);
                // Move to the information bookmark
                bk.MoveToBookmark("Information");
                // Get the content of information bookmark.
                TextBodyPart bodyPart = bk.GetBookmarkContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the destination document.
                bk = new BookmarksNavigator(document);
                // Move to the NorthWind database in the destination document
                bk.MoveToBookmark("NorthwindDatabase");
                //Replace the bookmark content using word document parts
                bk.ReplaceContent(documentPart);
                // Move to the Northwind_Information in the destination document
                bk.MoveToBookmark("Northwind_Information");
                // Replacing content of Northwind_Information bookmark.
                bk.ReplaceBookmarkContent(bodyPart);
                // Move to the text bookmark
                bk.MoveToBookmark("Text");
                //Deletes the bookmark content
                bk.DeleteBookmarkContent(true);
                // Inserting text inside the bookmark. This will preserve the source formatting
                bk.InsertText("Northwind Database contains the following table:");
                #region tableinsertion
                WTable tbl = new WTable(document);
                tbl.TableFormat.Borders.BorderType = BorderStyle.None;
                tbl.TableFormat.IsAutoResized      = true;
                tbl.ResetCells(8, 2);
                IWParagraph paragraph;
                tbl.Rows[0].IsHeader = true;
                paragraph            = tbl[0, 0].AddParagraph();
                paragraph.AppendText("Suppliers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[0, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 0].AddParagraph();
                paragraph.AppendText("Customers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 0].AddParagraph();
                paragraph.AppendText("Employees");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 0].AddParagraph();
                paragraph.AppendText("Products");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 0].AddParagraph();
                paragraph.AppendText("Inventory");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 1].AddParagraph();
                paragraph.AppendText("2");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 0].AddParagraph();
                paragraph.AppendText("Shippers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 0].AddParagraph();
                paragraph.AppendText("PO Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 0].AddParagraph();
                paragraph.AppendText("Sales Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 1].AddParagraph();
                paragraph.AppendText("7");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;


                bk.InsertTable(tbl);
                #endregion
                bk.MoveToBookmark("Image");
                bk.DeleteBookmarkContent(true);
                // Inserting image to the bookmark.
                IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
                inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Northwind.png");
                pic.LoadImage(inputStream);
                inputStream.Dispose();
                pic.WidthScale  = 50f; // It reduce the image size because it don't fit
                pic.HeightScale = 75f; // in document page.
                #endregion
                #region Saving Document
                //Save the word document to stream.
                MemoryStream stream = new MemoryStream();
                document.Save(stream, FormatType.Docx);
                //Save file in the disk based on specfic OS
                if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
                {
                    Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("BookMarkNavigation.docx", "application/msword", stream);
                }
                else
                {
                    Xamarin.Forms.DependencyService.Get <ISave>().Save("BookMarkNavigation.docx", "application/msword", stream);
                }
                #endregion
            }
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = typeof(App).GetTypeInfo().Assembly;
            // Creating a new document.
            WordDocument document = new WordDocument();
            //Adds section with one empty paragraph to the Word document
            document.EnsureMinimal();
            //sets the page margins
            document.LastSection.PageSetup.Margins.All = 72f;
            //Appends bookmark to the paragraph
            document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
            document.LastParagraph.AppendText("Northwind database with relational data");
            document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
            // Open an existing template document with single section.
            WordDocument nwdInformation = new WordDocument();
            Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Bookmark_Template.doc");
            // Open an existing template document.
            nwdInformation.Open(inputStream, FormatType.Doc);
            inputStream.Dispose();
            // Open an existing template document with multiple section.
            WordDocument templateDocument = new WordDocument();
            inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.BkmkDocumentPart_Template.doc");
            // Open an existing template document.
            templateDocument.Open(inputStream, FormatType.Doc);
            inputStream.Dispose();
            // Creating a bookmark navigator. Which help us to navigate through the 
            // bookmarks in the template document.
            BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
            // Move to the NorthWind bookmark in template document
            bk.MoveToBookmark("NorthWind");
            //Gets the bookmark content as WordDocumentPart
            WordDocumentPart documentPart = bk.GetContent();
            // Creating a bookmark navigator. Which help us to navigate through the 
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            // Move to the information bookmark 
            bk.MoveToBookmark("Information");
            // Get the content of information bookmark.
            TextBodyPart bodyPart = bk.GetBookmarkContent();
            // Creating a bookmark navigator. Which help us to navigate through the 
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            // Move to the NorthWind database in the destination document
            bk.MoveToBookmark("NorthwindDatabase");
            //Replace the bookmark content using word document parts
            bk.ReplaceContent(documentPart);
            // Move to the Northwind_Information in the destination document
            bk.MoveToBookmark("Northwind_Information");
            // Replacing content of Northwind_Information bookmark.
            bk.ReplaceBookmarkContent(bodyPart);
            // Move to the text bookmark
            bk.MoveToBookmark("Text");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting text inside the bookmark. This will preserve the source formatting
            bk.InsertText("Northwind Database contains the following table:");
            #region tableinsertion
            WTable tbl = new WTable(document);
            tbl.TableFormat.Borders.BorderType = BorderStyle.None;
            tbl.TableFormat.IsAutoResized = true;
            tbl.ResetCells(8, 2);
            IWParagraph paragraph;
            tbl.Rows[0].IsHeader = true;
            paragraph = tbl[0, 0].AddParagraph();
            paragraph.AppendText("Suppliers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[0, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 0].AddParagraph();
            paragraph.AppendText("Customers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 0].AddParagraph();
            paragraph.AppendText("Employees");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 0].AddParagraph();
            paragraph.AppendText("Products");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 0].AddParagraph();
            paragraph.AppendText("Inventory");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 1].AddParagraph();
            paragraph.AppendText("2");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 0].AddParagraph();
            paragraph.AppendText("Shippers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 0].AddParagraph();
            paragraph.AppendText("PO Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 0].AddParagraph();
            paragraph.AppendText("Sales Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 1].AddParagraph();
            paragraph.AppendText("7");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;


            bk.InsertTable(tbl);
            #endregion
            bk.MoveToBookmark("Image");
            bk.DeleteBookmarkContent(true);
            // Inserting image to the bookmark.
            IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
            inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Northwind.png");
            pic.LoadImage(inputStream);
            inputStream.Dispose();
            pic.WidthScale = 50f;  // It reduce the image size because it don't fit 
            pic.HeightScale = 75f; // in document page.


            #region Saving Document
            MemoryStream stream = new MemoryStream();
            document.Save(stream, FormatType.Word2013);
            document.Close();
            if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
                Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("BookMarkNavigation.docx", "application/msword", stream);
            else
                Xamarin.Forms.DependencyService.Get<ISave>().Save("BookMarkNavigation.docx", "application/msword", stream);
            #endregion
        }
Exemplo n.º 25
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            ErrorMessage.InnerText = "";
            if (hdnGroup.Value == "Word")
            {
                string path = string.Format("{0}\\..\\Data\\AdventureWorks\\AdventureWorks_Person_Contact.csv", Request.PhysicalPath.ToLower().Split(new string[] { "\\c# hbase samples" }, StringSplitOptions.None));
                try
                {
                    //Create a new document
                    WordDocument document = new WordDocument();

                    //Adding new table to the document
                    WTable doctable = new WTable(document);

                    //Adding a new section to the document.
                    WSection section = document.AddSection() as WSection;

                    //Set Margin of the section
                    section.PageSetup.Margins.All = 72;

                    //Set page size of the section
                    section.PageSetup.PageSize = new SizeF(800, 792);

                    //Create Paragraph styles
                    WParagraphStyle style = document.AddParagraphStyle("Normal") as WParagraphStyle;
                    style.CharacterFormat.FontName = "Calibri";
                    style.CharacterFormat.FontSize = 11f;

                    //Create a character format for declaring font color and style for the text inside the cell
                    WCharacterFormat charFormat = new WCharacterFormat(document);
                    charFormat.TextColor = System.Drawing.Color.White;
                    charFormat.Bold      = true;

                    #region creating connection
                    HBaseConnection con = new HBaseConnection("localhost", 10003);
                    con.Open();

                    #endregion creating connection

                    #region parsing csv input file

                    csv csvObj = new csv();
                    object[,] cells;
                    cells = null;

                    cells = csvObj.Table(path, false, ',');

                    #endregion parsing csv input file

                    #region creating table
                    String        tableName      = "AdventureWorks_Person_Contact";
                    List <string> columnFamilies = new List <string>();
                    columnFamilies.Add("info");
                    columnFamilies.Add("contact");
                    columnFamilies.Add("others");
                    if (!HBaseOperation.IsTableExists(tableName, con))
                    {
                        if (columnFamilies.Count > 0)
                        {
                            HBaseOperation.CreateTable(tableName, columnFamilies, con);
                        }
                        else
                        {
                            throw new HBaseException("ERROR: Table must have at least one column family");
                        }
                    }
                    # endregion

                    #region Inserting Values
                    string[] column = new string[] { "CONTACTID", "FULLNAME", "AGE", "EMAILID", "PHONE", "MODIFIEDDATE" };
                    Dictionary <string, IList <HMutation> > rowCollection = new Dictionary <string, IList <HMutation> >();
                    string rowKey;
                    for (int i = 0; i < cells.GetLength(0); i++)
                    {
                        List <HMutation> mutations = new List <HMutation>();
                        rowKey = cells[i, 0].ToString();
                        for (int j = 1; j < column.Length; j++)
                        {
                            HMutation mutation = new HMutation();
                            mutation.ColumnFamily = j < 3 ? "info" : j < 5 ? "contact" : "others";
                            mutation.ColumnName   = column[j];
                            mutation.Value        = cells[i, j].ToString();
                            mutations.Add(mutation);
                        }
                        rowCollection[rowKey] = mutations;
                    }
                    HBaseOperation.InsertRows(tableName, rowCollection, con);
                    #endregion Inserting Values

                    #region scan values

                    HBaseOperation.FetchSize = 100;
                    HBaseResultSet table = HBaseOperation.ScanTable(tableName, con);

                    //Adding headertext for the table
                    doctable.AddRow(true, false);
                    //Creating new cell
                    WTableCell cell = new WTableCell(document);
                    cell.AddParagraph().AppendText("ContactId").ApplyCharacterFormat(charFormat);
                    cell.Width = 100;
                    //Adding cell to the row
                    doctable.Rows[0].Cells.Add(cell);
                    cell = new WTableCell(document);
                    cell.AddParagraph().AppendText("contact:EmailId").ApplyCharacterFormat(charFormat);
                    cell.Width = 200;
                    doctable.Rows[0].Cells.Add(cell);
                    cell = new WTableCell(document);
                    cell.AddParagraph().AppendText("contact:PhoneNo").ApplyCharacterFormat(charFormat);
                    cell.Width = 150;
                    doctable.Rows[0].Cells.Add(cell);
                    cell = new WTableCell(document);
                    cell.AddParagraph().AppendText("info:Age").ApplyCharacterFormat(charFormat);
                    cell.Width = 100;
                    doctable.Rows[0].Cells.Add(cell);
                    cell = new WTableCell(document);
                    cell.AddParagraph().AppendText("info:FullName").ApplyCharacterFormat(charFormat);
                    cell.Width = 150;
                    doctable.Rows[0].Cells.Add(cell);
                    cell = new WTableCell(document);
                    cell.AddParagraph().AppendText("others:ModifiedDate").ApplyCharacterFormat(charFormat);
                    cell.Width = 200;
                    doctable.Rows[0].Cells.Add(cell);


                    //Reading each row from the fetched result
                    for (int i = 0; i < table.Count(); i++)
                    {
                        HBaseRecord records = table[i];
                        doctable.AddRow(true, false);

                        //Reading each data from the row
                        for (int j = 0; j < records.Count; j++)
                        {
                            Object fields = records[j];

                            //Adding new cell to the document
                            cell = new WTableCell(document);

                            //Adding each data to the cell
                            cell.AddParagraph().AppendText(fields.ToString());
                            if (j != 1 && j != 2 && j != 4 && j != 5)
                            {
                                cell.Width = 100;
                            }
                            else if (j == 2 || j == 4)
                            {
                                cell.Width = 150;
                            }
                            else
                            {
                                cell.Width = 200;
                            }

                            //Adding cell to the table
                            doctable.Rows[i + 1].Cells.Add(cell);
                            doctable.Rows[0].Cells[j].CellFormat.BackColor = Color.FromArgb(51, 153, 51);
                        }
                    }
                    //Adding table to the section
                    section.Tables.Add(doctable);
                    //Save as word 2007 format
                    if (rBtnWord2003.Checked == true)
                    {
                        document.Save("Sample.doc", FormatType.Doc, Response, HttpContentDisposition.Attachment);
                    }
                    else if (rBtnWord2007.Checked == true)
                    {
                        document.Save("Sample.docx", FormatType.Word2007, Response, HttpContentDisposition.Attachment);
                    }
                    //Save as word 2010 format
                    else if (rbtnWord2010.Checked == true)
                    {
                        document.Save("Sample.docx", FormatType.Word2010, Response, HttpContentDisposition.Attachment);
                    }
                    //Save as word 2013 format
                    else if (rbtnWord2013.Checked == true)
                    {
                        document.Save("Sample.docx", FormatType.Word2013, Response, HttpContentDisposition.Attachment);
                    }
                    #endregion scan values

                    #region close connection
                    //Closing the hive connection
                    con.Close();
                    #endregion close connection
                }
Exemplo n.º 26
0
        public ActionResult BookmarkNavigation(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }
            #region BookmarkNavigation
            // Creating a new document.
            WordDocument document = new WordDocument();
            //Adds section with one empty paragraph to the Word document
            document.EnsureMinimal();
            //sets the page margins
            document.LastSection.PageSetup.Margins.All = 72f;
            //Appends bookmark to the paragraph
            document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
            document.LastParagraph.AppendText("Northwind database with normalization concept");
            document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
            // Open an existing template document with single section to get Northwind.information
            WordDocument nwdInformation = new WordDocument(ResolveApplicationDataPath("Bookmark_Template.doc", "App_Data\\DocIO"));
            // Open an existing template document with multiple section to get Northwind data.
            WordDocument templateDocument = new WordDocument(ResolveApplicationDataPath("BkmkDocumentPart_Template.doc", "App_Data\\DocIO"));
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the template document.
            BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
            // Move to the NorthWind bookmark in template document
            bk.MoveToBookmark("NorthWind");
            //Gets the bookmark content as WordDocumentPart
            WordDocumentPart documentPart = bk.GetContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            // Move to the information bookmark
            bk.MoveToBookmark("Information");
            // Get the content of information bookmark.
            TextBodyPart bodyPart = bk.GetBookmarkContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            // Move to the NorthWind database in the destination document
            bk.MoveToBookmark("NorthwindDatabase");
            //Replace the bookmark content using word document parts
            bk.ReplaceContent(documentPart);
            // Move to the Northwind_Information in the destination document
            bk.MoveToBookmark("Northwind_Information");
            // Replacing content of Northwind_Information bookmark.
            bk.ReplaceBookmarkContent(bodyPart);
            // Move to the text bookmark
            bk.MoveToBookmark("Text");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting text inside the bookmark. This will preserve the source formatting
            bk.InsertText("Northwind Database contains the following table:");
            #region tableinsertion
            WTable tbl = new WTable(document);
            tbl.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
            tbl.TableFormat.IsAutoResized      = true;
            tbl.ResetCells(8, 2);
            IWParagraph paragraph;
            tbl.Rows[0].IsHeader = true;
            paragraph            = tbl[0, 0].AddParagraph();
            paragraph.AppendText("Suppliers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[0, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 0].AddParagraph();
            paragraph.AppendText("Customers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 0].AddParagraph();
            paragraph.AppendText("Employees");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 0].AddParagraph();
            paragraph.AppendText("Products");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 0].AddParagraph();
            paragraph.AppendText("Inventory");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 1].AddParagraph();
            paragraph.AppendText("2");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 0].AddParagraph();
            paragraph.AppendText("Shippers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 0].AddParagraph();
            paragraph.AppendText("PO Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 0].AddParagraph();
            paragraph.AppendText("Sales Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 1].AddParagraph();
            paragraph.AppendText("7");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            bk.InsertTable(tbl);
            #endregion tableinsertion
            //Move to image bookmark
            bk.MoveToBookmark("Image");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting image to the bookmark.
            IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
            pic.LoadImage(System.Drawing.Image.FromFile(ResolveApplicationDataPath("Northwind.png", "Content\\DocIO")));
            pic.WidthScale  = 50f; // It reduce the image size because it don't fit
            pic.HeightScale = 75f; // in document page.
            #endregion BookmarkNavigation

            #region Document SaveOption
            //Save as .doc format
            if (Group1 == "WordDoc")
            {
                return(document.ExportAsActionResult("Sample.doc", FormatType.Doc, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            //Save as .docx format
            else if (Group1 == "WordDocx")
            {
                return(document.ExportAsActionResult("Sample.docx", FormatType.Docx, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            // Save as WordML(.xml) format
            else if (Group1 == "WordML")
            {
                return(document.ExportAsActionResult("Sample.xml", FormatType.WordML, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            //Save as .pdf format
            else if (Group1 == "Pdf")
            {
                DocToPDFConverter converter = new DocToPDFConverter();
                PdfDocument       pdfDoc    = converter.ConvertToPDF(document);

                return(pdfDoc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
            #endregion Document SaveOption
            return(View());
        }
Exemplo n.º 27
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                string dataPath = @"..\..\..\..\..\..\..\Common\Data\DocIO\";
                // Creating a new document.
                WordDocument document = new WordDocument();
                //Adds section with one empty paragraph to the Word document
                document.EnsureMinimal();
                //sets the page margins
                document.LastSection.PageSetup.Margins.All = 72f;
                //Appends bookmark to the paragraph
                document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
                document.LastParagraph.AppendText("Northwind database with normalization concept");
                document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
                // Open an existing template document with single section to get Northwind.information
                WordDocument nwdInformation = new WordDocument(dataPath + "Bookmark_Template.doc");
                // Open an existing template document with multiple section to get Northwind data.
                WordDocument templateDocument = new WordDocument(dataPath + "BkmkDocumentPart_Template.doc");
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the template document.
                BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
                // Move to the NorthWind bookmark in template document
                bk.MoveToBookmark("NorthWind");
                //Gets the bookmark content as WordDocumentPart
                WordDocumentPart documentPart = bk.GetContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the Northwind information document.
                bk = new BookmarksNavigator(nwdInformation);
                // Move to the information bookmark
                bk.MoveToBookmark("Information");
                // Get the content of information bookmark.
                TextBodyPart bodyPart = bk.GetBookmarkContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the destination document.
                bk = new BookmarksNavigator(document);
                // Move to the NorthWind database in the destination document
                bk.MoveToBookmark("NorthwindDatabase");
                //Replace the bookmark content using word document parts
                bk.ReplaceContent(documentPart);
                // Move to the Northwind_Information in the destination document
                bk.MoveToBookmark("Northwind_Information");
                // Replacing content of Northwind_Information bookmark.
                bk.ReplaceBookmarkContent(bodyPart);
                // Move to the text bookmark
                bk.MoveToBookmark("Text");
                //Deletes the bookmark content
                bk.DeleteBookmarkContent(true);
                // Inserting text inside the bookmark. This will preserve the source formatting
                bk.InsertText("Northwind Database contains the following table:");
                #region tableinsertion
                WTable tbl = new WTable(document);
                tbl.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
                tbl.TableFormat.IsAutoResized      = true;
                tbl.ResetCells(8, 2);
                IWParagraph paragraph;
                tbl.Rows[0].IsHeader = true;
                paragraph            = tbl[0, 0].AddParagraph();
                paragraph.AppendText("Suppliers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[0, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 0].AddParagraph();
                paragraph.AppendText("Customers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 0].AddParagraph();
                paragraph.AppendText("Employees");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 0].AddParagraph();
                paragraph.AppendText("Products");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 0].AddParagraph();
                paragraph.AppendText("Inventory");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 1].AddParagraph();
                paragraph.AppendText("2");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 0].AddParagraph();
                paragraph.AppendText("Shippers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 0].AddParagraph();
                paragraph.AppendText("PO Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 0].AddParagraph();
                paragraph.AppendText("Sales Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 1].AddParagraph();
                paragraph.AppendText("7");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;


                bk.InsertTable(tbl);
                #endregion
                //Move to image bookmark
                bk.MoveToBookmark("Image");
                //Deletes the bookmark content
                bk.DeleteBookmarkContent(true);
                // Inserting image to the bookmark.
                IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
                pic.LoadImage(System.Drawing.Image.FromFile(@"..\..\..\..\..\..\..\Common\images\DocIO\Northwind.png"));
                pic.WidthScale  = 50f; // It reduces the image size because it doesnot fit
                pic.HeightScale = 75f; // in document page.
                bodyPart.Close();
                documentPart.Close();
                #region save document
                //Save as doc format
                if (wordDocRadioBtn.Checked)
                {
                    //Saving the document to disk.
                    document.Save("Sample.doc");

                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                        System.Diagnostics.Process.Start("Sample.doc");
                        //Exit
                        this.Close();
                    }
                }
                //Save as docx format
                else if (wordDocxRadioBtn.Checked)
                {
                    //Saving the document as .docx
                    document.Save("Sample.docx", FormatType.Docx);
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                            System.Diagnostics.Process.Start("Sample.docx");
                            //Exit
                            this.Close();
                        }
                        catch (Win32Exception ex)
                        {
                            MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                //Save as pdf format
                else if (pdfRadioBtn.Checked)
                {
                    DocToPDFConverter converter = new DocToPDFConverter();
                    //Convert word document into PDF document
                    PdfDocument pdfDoc = converter.ConvertToPDF(document);
                    //Save the pdf file
                    pdfDoc.Save("Sample.pdf");
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            System.Diagnostics.Process.Start("Sample.pdf");
                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                #endregion
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Exemplo n.º 28
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            ErrorMessage.InnerText = "";
            if (hdnGroup.Value == "Word")
            {
                CheckFileStatus FileStatus = new CheckFileStatus();
                string          path       = string.Format("{0}\\..\\Data\\AdventureWorks\\AdventureWorks_Person_Contact.csv", Request.PhysicalPath.ToLower().Split(new string[] { "\\c# hive samples" }, StringSplitOptions.None));
                ErrorMessage.InnerText = FileStatus.CheckFile(path);
                if (ErrorMessage.InnerText == "")
                {
                    try
                    {
                        //Create a new document
                        WordDocument document = new WordDocument();

                        //Adding new table to the document
                        WTable doctable = new WTable(document);

                        //Adding a new section to the document.
                        WSection section = document.AddSection() as WSection;

                        //Set Margin of the section
                        section.PageSetup.Margins.All = 72;

                        //Set page size of the section
                        section.PageSetup.PageSize = new SizeF(800, 792);

                        //Create Paragraph styles
                        WParagraphStyle style = document.AddParagraphStyle("Normal") as WParagraphStyle;
                        style.CharacterFormat.FontName = "Calibri";
                        style.CharacterFormat.FontSize = 11f;

                        //Create a character format for declaring font color and style for the text inside the cell
                        WCharacterFormat charFormat = new WCharacterFormat(document);
                        charFormat.TextColor = System.Drawing.Color.White;
                        charFormat.Bold      = true;

                        //Initializing the hive server connection
                        HqlConnection con = new HqlConnection("localhost", 10000, HiveServer.HiveServer2);

                        //To initialize a Hive server connection with secured cluster
                        //HqlConnection con = new HqlConnection("<Secured cluster Namenode IP>", 10000, HiveServer.HiveServer2,"<username>","<password>");

                        //To initialize a Hive server connection with Azure cluster
                        //HqlConnection con = new HqlConnection("<FQDN name of Azure cluster>", 8004, HiveServer.HiveServer2,"<username>","<password>");

                        con.Open();

                        //Create table for adventure person contacts
                        HqlCommand createCommand = new HqlCommand("CREATE EXTERNAL TABLE IF NOT EXISTS AdventureWorks_Person_Contact(ContactID int,FullName string,Age int,EmailAddress string,PhoneNo string,ModifiedDate string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LOCATION '/Data/AdventureWorks'", con);
                        createCommand.ExecuteNonQuery();
                        HqlCommand command = new HqlCommand("Select * from AdventureWorks_Person_Contact", con);

                        //Executing the query
                        HqlDataReader reader = command.ExecuteReader();
                        reader.FetchSize = 100;

                        //Fetches the result from the reader and store it in HiveResultSet
                        HiveResultSet result = reader.FetchResult();

                        //Adding headertext for the table
                        doctable.AddRow(true, false);
                        //Creating new cell
                        WTableCell cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Customer Id").ApplyCharacterFormat(charFormat);
                        cell.Width = 75;
                        //Adding cell to the row
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Full Name").ApplyCharacterFormat(charFormat);
                        cell.Width = 75;
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Age").ApplyCharacterFormat(charFormat);
                        cell.Width = 75;
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Email Id").ApplyCharacterFormat(charFormat);
                        cell.Width = 75;
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Phone Number").ApplyCharacterFormat(charFormat);
                        cell.Width = 75;
                        doctable.Rows[0].Cells.Add(cell);
                        cell = new WTableCell(document);
                        cell.AddParagraph().AppendText("Modified Date").ApplyCharacterFormat(charFormat);
                        cell.Width = 75;
                        doctable.Rows[0].Cells.Add(cell);

                        //Reading each row from the fetched result
                        for (int i = 0; i < result.Count(); i++)
                        {
                            HiveRecord records = result[i];
                            doctable.AddRow(true, false);

                            //Reading each data from the row
                            for (int j = 0; j < records.Count; j++)
                            {
                                Object fields = records[j];

                                //Adding new cell to the document
                                cell = new WTableCell(document);

                                //Adding each data to the cell
                                cell.AddParagraph().AppendText(fields.ToString());
                                cell.Width = 75;

                                //Adding cell to the table
                                doctable.Rows[i + 1].Cells.Add(cell);
                                doctable.Rows[0].Cells[j].CellFormat.BackColor = Color.FromArgb(51, 153, 51);
                            }
                        }
                        //Adding table to the section
                        section.Tables.Add(doctable);
                        //Save as word 2007 format
                        if (rBtnWord2003.Checked == true)
                        {
                            document.Save("Sample.doc", FormatType.Doc, Response, HttpContentDisposition.Attachment);
                        }
                        else if (rBtnWord2007.Checked == true)
                        {
                            document.Save("Sample.docx", FormatType.Word2007, Response, HttpContentDisposition.Attachment);
                        }
                        //Save as word 2010 format
                        else if (rbtnWord2010.Checked == true)
                        {
                            document.Save("Sample.docx", FormatType.Word2010, Response, HttpContentDisposition.Attachment);
                        }
                        //Save as word 2013 format
                        else if (rbtnWord2013.Checked == true)
                        {
                            document.Save("Sample.docx", FormatType.Word2013, Response, HttpContentDisposition.Attachment);
                        }

                        //Closing the hive connection
                        con.Close();
                    }
                    catch (HqlConnectionException)
                    {
                        ErrorMessage.InnerText = "Could not establish a connection to the HiveServer. Please run HiveServer2 from the Syncfusion service manager dashboard.";
                    }
                }
            }
            else if (hdnGroup.Value == "Excel")
            {
                ErrorMessage.InnerText = "";
                CheckFileStatus FileStatus = new CheckFileStatus();
                string          path       = string.Format("{0}\\..\\Data\\AdventureWorks\\AdventureWorks_Person_Contact.csv", Request.PhysicalPath.ToLower().Split(new string[] { "\\c# hive samples" }, StringSplitOptions.None));
                ErrorMessage.InnerText = FileStatus.CheckFile(path);
                if (ErrorMessage.InnerText == "")
                {
                    try
                    {
                        //Instantiate the spreadsheet creation engine.
                        ExcelEngine excelEngine = new ExcelEngine();

                        //Instantiate the excel application object.
                        IApplication application = excelEngine.Excel;

                        //A new workbook is created.[Equivalent to creating a new workbook in MS Excel]
                        //The new workbook will have 1 worksheets
                        IWorkbook workbook = application.Workbooks.Create(1);

                        //The first worksheet object in the worksheets collection is accessed.
                        IWorksheet worksheet = workbook.Worksheets[0];

                        //Adding header text for worksheet
                        worksheet[1, 1].Text = "ContactID";
                        worksheet[1, 2].Text = "FullName";
                        worksheet[1, 3].Text = "Age";
                        worksheet[1, 4].Text = "EmailAddress";
                        worksheet[1, 5].Text = "PhoneNo";
                        worksheet[1, 6].Text = "ModifiedDate";

                        //Initializing the hive server connection
                        HqlConnection con = new HqlConnection("localhost", 10000, HiveServer.HiveServer2);

                        //To initialize a Hive server connection with secured cluster
                        //HqlConnection con = new HqlConnection("<Secured cluster Namenode IP>", 10000, HiveServer.HiveServer2,"<username>","<password>");

                        con.Open();

                        //Create table for adventure person contacts
                        HqlCommand createCommand = new HqlCommand("CREATE EXTERNAL TABLE IF NOT EXISTS AdventureWorks_Person_Contact(ContactID int,FullName string,Age int,EmailAddress string,PhoneNo string,ModifiedDate string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LOCATION '/Data/AdventureWorks'", con);
                        createCommand.ExecuteNonQuery();

                        //Passing the hive query
                        HqlCommand command = new HqlCommand("Select * from AdventureWorks_Person_Contact", con);

                        //Executing the query
                        HqlDataReader reader = command.ExecuteReader();
                        reader.FetchSize = 100;

                        //Fetches the result from the reader and store it in a seperate set
                        HiveResultSet result = reader.FetchResult();

                        //Reading each row from the fetched result
                        for (int i = 0; i < result.Count(); i++)
                        {
                            HiveRecord records = result[i];

                            //Reading each field from the row
                            for (int j = 0; j < records.Count; j++)
                            {
                                Object fields = records[j];
                                //Assigning each field value to the worksheet based on index
                                worksheet[i + 2, j + 1].Text = fields.ToString();
                            }
                        }
                        worksheet.Range["A1:F1"].CellStyle.Font.Color = Syncfusion.XlsIO.ExcelKnownColors.White;
                        worksheet.Range["A1:F1"].CellStyle.Font.Bold  = true;
                        worksheet.Range["A1:F1"].CellStyle.Color      = System.Drawing.Color.FromArgb(51, 153, 51);
                        worksheet.UsedRange.AutofitColumns();

                        //Saving workbook on user relevant name
                        string fileName = "Sample.xlsx";

                        //conditions for selecting version
                        //Save as Excel 97to2003 format
                        if (rBtn2003.Checked == true)
                        {
                            workbook.Version = ExcelVersion.Excel97to2003;
                            workbook.SaveAs("Sample.xls", Response, ExcelDownloadType.PromptDialog);
                        }
                        //Save as Excel 2007 formt
                        else if (rBtn2007.Checked == true)
                        {
                            workbook.Version = ExcelVersion.Excel2007;
                            workbook.SaveAs("Sample.xlsx", Response, ExcelDownloadType.PromptDialog);
                        }
                        //Save as Excel 2010 format
                        else if (rbtn2010.Checked == true)
                        {
                            workbook.Version = ExcelVersion.Excel2010;
                            workbook.SaveAs("Sample.xlsx", Response, ExcelDownloadType.PromptDialog);
                        }
                        //Save as Excel 2013 format
                        else if (rbtn2013.Checked == true)
                        {
                            workbook.Version = ExcelVersion.Excel2013;
                            workbook.SaveAs("Sample.xlsx", Response, ExcelDownloadType.PromptDialog);
                        }

                        //closing the workwook
                        workbook.Close();

                        //Closing the excel engine
                        excelEngine.Dispose();


                        //Closing the hive connection
                        con.Close();
                    }
                    catch (HqlConnectionException)
                    {
                        ErrorMessage.InnerText = "Could not establish a connection to the HiveServer. Please run HiveServer2 from the Syncfusion service manager dashboard.";
                    }
                }
            }
        }
Exemplo n.º 29
0
        private static void IterateTable(WTable table)
        {
            List <DocViewModel> optionCheckList = new List <DocViewModel>();

            foreach (WTableRow row in table.Rows)
            {
                #region get key

                IEntity titleEntity = row.Cells[0].ChildEntities[0];
                string  key         = (titleEntity as WParagraph).Text;

                #endregion

                #region question content
                if (key.Contains("QN=") || key.Contains("QN ="))
                {
                    quesModel.Code = key.Replace("QN=", "").Replace("QN =", "").Trim();
                    //for (int i = 0; i < row.Cells[1].ChildEntities.Count; i++)
                    //{
                    //    IEntity bodyItemEntity = row.Cells[1].ChildEntities[i];
                    //    WParagraph wParagraph = bodyItemEntity as WParagraph;
                    //    if (wParagraph.ChildEntities.Count != 0)
                    //    {
                    //        ParagraphItem pItem = wParagraph.ChildEntities[0] as ParagraphItem;
                    //        switch (pItem.EntityType)
                    //        {
                    //            default:
                    //                if (!(wParagraph.Text.Contains("[file") || wParagraph.Text.Equals("")) && quesModel.QuestionContent == null)
                    //                {
                    //                    quesModel.QuestionContent = "[html] " + wParagraph.Text.Replace("\v", "<cbr>");
                    //                }
                    //                else if (!(wParagraph.Text.Contains("[file") || wParagraph.Text.Equals("")))
                    //                {
                    //                    WTextRange text = pItem as WTextRange;
                    //                    quesModel.QuestionContent = quesModel.QuestionContent + "<cbr>" + wParagraph.Text;
                    //                }
                    //                break;
                    //            case EntityType.Picture:
                    //                WPicture wPicture = pItem as WPicture;
                    //                Image iImage = wPicture.Image;

                    //                MemoryStream m = new MemoryStream();
                    //                iImage.Save(m, iImage.RawFormat);
                    //                byte[] imageBytes = m.ToArray();

                    //                quesModel.Image = Convert.ToBase64String(imageBytes);
                    //                break;
                    //        }
                    //    }
                    //    if (quesModel.Image != null)
                    //    {
                    //        break;
                    //    }
                    //}

                    for (int i = 0; i < row.Cells[1].ChildEntities.Count; i++)
                    {
                        bool       inputWholeParagraph = false;
                        IEntity    bodyItemEntity      = row.Cells[1].ChildEntities[i];
                        WParagraph wParagraph          = bodyItemEntity as WParagraph;
                        if (wParagraph.ChildEntities.Count != 0)
                        {
                            foreach (var pChild in wParagraph.ChildEntities)
                            {
                                var pItem = pChild as ParagraphItem;
                                switch (pItem.EntityType)
                                {
                                case EntityType.TextRange:
                                    if (!inputWholeParagraph)
                                    {
                                        if (!wParagraph.Text.Equals("") && quesModel.QuestionContent == null)
                                        {
                                            quesModel.QuestionContent = "[html] " + wParagraph.Text.Replace("\v", "<cbr>").Split(new string[] { "[file" }, StringSplitOptions.None)[0];
                                            inputWholeParagraph       = true;
                                        }
                                        else if (!wParagraph.Text.Equals(""))
                                        {
                                            quesModel.QuestionContent = quesModel.QuestionContent + "<cbr>" + wParagraph.Text.Split(new string[] { "[file" }, StringSplitOptions.None)[0];
                                            inputWholeParagraph       = true;
                                        }
                                    }
                                    break;

                                case EntityType.Picture:
                                    WPicture             wPicture = pItem as WPicture;
                                    System.Drawing.Image iImage   = wPicture.Image;

                                    MemoryStream m = new MemoryStream();
                                    iImage.Save(m, iImage.RawFormat);
                                    byte[] imageBytes = m.ToArray();

                                    ImageViewModel image = new ImageViewModel();
                                    image.Source = Convert.ToBase64String(imageBytes);
                                    images.Add(image);
                                    break;
                                }
                            }
                        }
                    }
                }
                #endregion
                #region option content
                else if (key.Contains("."))
                {
                    var optionImages = new List <ImageViewModel>();
                    var optionCheck  = new DocViewModel();
                    optionCheck.Code = key.Replace(".", "").ToLower();
                    //for (int i = 0; i < row.Cells[1].ChildEntities.Count; i++)
                    //{
                    //    IEntity bodyItemEntity = row.Cells[1].ChildEntities[i];
                    //    WParagraph wParagraph = bodyItemEntity as WParagraph;
                    //    if (wParagraph.Text != "")
                    //    {
                    //        ParagraphItem pItem = wParagraph.ChildEntities[0] as ParagraphItem;
                    //        switch (pItem.EntityType)
                    //        {
                    //            //case EntityType.TextRange:
                    //            default:
                    //                if (!wParagraph.Text.Equals("") && optionModel.OptionContent == null)
                    //                {
                    //                    optionModel.IsCorrect = false;
                    //                    optionModel.OptionContent = wParagraph.Text.Replace("\v", "<cbr>");
                    //                }
                    //                else if (!wParagraph.Text.Equals(""))
                    //                {
                    //                    optionModel.OptionContent = optionModel.OptionContent + "<cbr>" + wParagraph.Text.Replace("\v", "<cbr>");
                    //                }
                    //                break;
                    //            case EntityType.Picture:
                    //                //WPicture wPicture = pItem as WPicture;
                    //                //Image iImage = wPicture.Image;

                    //                //MemoryStream m = new MemoryStream();
                    //                //iImage.Save(m, iImage.RawFormat);
                    //                //byte[] imageBytes = m.ToArray();

                    //                //quesModel.Image = Convert.ToBase64String(imageBytes);
                    //                break;
                    //        }
                    //    }
                    //}


                    for (int i = 0; i < row.Cells[1].ChildEntities.Count; i++)
                    {
                        bool       inputWholeParagraph = false;
                        IEntity    bodyItemEntity      = row.Cells[1].ChildEntities[i];
                        WParagraph wParagraph          = bodyItemEntity as WParagraph;
                        if (wParagraph.ChildEntities.Count != 0)
                        {
                            foreach (var pChild in wParagraph.ChildEntities)
                            {
                                var pItem = pChild as ParagraphItem;
                                switch (pItem.EntityType)
                                {
                                case EntityType.TextRange:
                                    if (!inputWholeParagraph)
                                    {
                                        if (!wParagraph.Text.Equals("") && optionModel.OptionContent == null)
                                        {
                                            optionModel.IsCorrect     = false;
                                            optionModel.OptionContent = wParagraph.Text.Replace("\v", "<cbr>");
                                            inputWholeParagraph       = true;
                                        }
                                        else if (!wParagraph.Text.Equals(""))
                                        {
                                            optionModel.OptionContent = optionModel.OptionContent + "<cbr>" + wParagraph.Text;
                                        }
                                    }
                                    break;

                                case EntityType.Picture:

                                    WPicture             wPicture = pItem as WPicture;
                                    System.Drawing.Image iImage   = wPicture.Image;

                                    MemoryStream m = new MemoryStream();
                                    iImage.Save(m, iImage.RawFormat);
                                    byte[] imageBytes = m.ToArray();

                                    ImageViewModel image = new ImageViewModel();
                                    image.Source = Convert.ToBase64String(imageBytes);
                                    optionImages.Add(image);
                                    break;
                                }
                            }
                        }
                    }
                    optionCheck.Content = optionModel.OptionContent;
                    optionCheckList.Add(optionCheck);
                    optionModel.Images = optionImages;
                    if (optionModel.OptionContent != null || (optionModel.Images != null && optionModel.Images.Count() != 0))
                    {
                        options.Add(optionModel);
                    }
                    optionModel = new OptionViewModel();
                }
                #endregion
                else if (key.Contains("ANSWER:"))
                {
                    IEntity    bodyItemEntity = row.Cells[1].ChildEntities[0];
                    WParagraph paragraph      = bodyItemEntity as WParagraph;
                    if (!paragraph.Text.Equals(""))
                    {
                        var    trim    = paragraph.Text.Replace(" ", "").ToLower();
                        char[] answers = trim.ToCharArray();
                        foreach (var optionCheck in optionCheckList)
                        {
                            for (int i = 0; i < answers.Length; i++)
                            {
                                if (optionCheck.Code.Equals(answers[i].ToString()))
                                {
                                    foreach (var option in options)
                                    {
                                        if (option.OptionContent.Equals(optionCheck.Content))
                                        {
                                            option.IsCorrect = true;
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (key.Contains("UNIT:"))
                {
                    IEntity    bodyItemEntity = row.Cells[1].ChildEntities[0];
                    WParagraph paragraph      = bodyItemEntity as WParagraph;
                    if (!paragraph.Text.Equals(""))
                    {
                        var number = Regex.Match(paragraph.Text, @"\d+$").ToString();
                        if (globalPrefix == "")
                        {
                            quesModel.LearningOutcome = paragraph.Text;
                        }
                        else
                        {
                            quesModel.LearningOutcome = globalPrefix + " " + number;
                        }
                    }
                }
                else if (key.Contains("MARK:"))
                {
                    IEntity    bodyItemEntity = row.Cells[1].ChildEntities[0];
                    WParagraph paragraph      = bodyItemEntity as WParagraph;
                    switch (paragraph.Text)
                    {
                    //default:
                    //    quesModel.Level = "Easy";
                    //    break;
                    case "1":
                        quesModel.Level = "Easy";
                        break;

                    case "2":
                        quesModel.Level = "Medium";
                        break;

                    case "3":
                        quesModel.Level = "Hard";
                        break;
                    }
                }
                else if (key.Contains("CATEGORY:"))
                {
                    IEntity    bodyItemEntity = row.Cells[1].ChildEntities[0];
                    WParagraph paragraph      = bodyItemEntity as WParagraph;
                    if (paragraph != null && !paragraph.Text.Equals(""))
                    {
                        quesModel.Category = paragraph.Text;
                    }
                }
            }
            if (images != null)
            {
                quesModel.Images = images;
            }
            quesModel.Options = options;
            listQuestion.Add(quesModel);
            quesModel       = new QuestionTmpModel();
            images          = new List <ImageViewModel>();
            options         = new List <OptionViewModel>();
            optionCheckList = new List <DocViewModel>();
        }
        public ActionResult BookmarkNavigation(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }
            #region BookmarkNavigation
            // Creating a new document.
            WordDocument document = new WordDocument();
            //Adds section with one empty paragraph to the Word document
            document.EnsureMinimal();
            //sets the page margins
            document.LastSection.PageSetup.Margins.All = 72f;
            //Appends bookmark to the paragraph
            document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
            document.LastParagraph.AppendText("Northwind database with normalization concept");
            document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
            string basePath     = _hostingEnvironment.WebRootPath;
            string dataPath     = basePath + @"/DocIO/Bookmark_Template.doc";
            string dataPathTemp = basePath + @"/DocIO/BkmkDocumentPart_Template.doc";
            // Open an existing template document with single section to get Northwind.information
            WordDocument nwdInformation = new WordDocument();
            FileStream   fileStream     = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            nwdInformation.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            // Open an existing template document with multiple section to get Northwind data.
            WordDocument templateDocument = new WordDocument();
            fileStream = new FileStream(dataPathTemp, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            templateDocument.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the template document.
            BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
            // Move to the NorthWind bookmark in template document
            bk.MoveToBookmark("NorthWind");
            //Gets the bookmark content as WordDocumentPart
            WordDocumentPart documentPart = bk.GetContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            // Move to the information bookmark
            bk.MoveToBookmark("Information");
            // Get the content of information bookmark.
            TextBodyPart bodyPart = bk.GetBookmarkContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            // Move to the NorthWind database in the destination document
            bk.MoveToBookmark("NorthwindDatabase");
            //Replace the bookmark content using word document parts
            bk.ReplaceContent(documentPart);
            // Move to the Northwind_Information in the destination document
            bk.MoveToBookmark("Northwind_Information");
            // Replacing content of Northwind_Information bookmark.
            bk.ReplaceBookmarkContent(bodyPart);
            // Move to the text bookmark
            bk.MoveToBookmark("Text");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting text inside the bookmark. This will preserve the source formatting
            bk.InsertText("Northwind Database contains the following table:");
            #region tableinsertion
            WTable tbl = new WTable(document);
            tbl.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
            tbl.TableFormat.IsAutoResized      = true;
            tbl.ResetCells(8, 2);
            IWParagraph paragraph;
            tbl.Rows[0].IsHeader = true;
            paragraph            = tbl[0, 0].AddParagraph();
            paragraph.AppendText("Suppliers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[0, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 0].AddParagraph();
            paragraph.AppendText("Customers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 0].AddParagraph();
            paragraph.AppendText("Employees");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 0].AddParagraph();
            paragraph.AppendText("Products");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 0].AddParagraph();
            paragraph.AppendText("Inventory");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 1].AddParagraph();
            paragraph.AppendText("2");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 0].AddParagraph();
            paragraph.AppendText("Shippers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 0].AddParagraph();
            paragraph.AppendText("PO Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 0].AddParagraph();
            paragraph.AppendText("Sales Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 1].AddParagraph();
            paragraph.AppendText("7");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            bk.InsertTable(tbl);
            #endregion tableinsertion
            //Move to image bookmark
            bk.MoveToBookmark("Image");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting image to the bookmark.
            IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;

            FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Northwind.png", FileMode.Open, FileAccess.Read);
            pic.LoadImage(imageStream);
            pic.WidthScale  = 50f; // It reduce the image size because it don't fit
            pic.HeightScale = 75f; // in document page.
            #endregion BookmarkNavigation

            FormatType type        = FormatType.Docx;
            string     filename    = "Sample.docx";
            string     contenttype = "application/vnd.ms-word.document.12";
            #region Document SaveOption
            //Save as .doc format
            if (Group1 == "WordDoc")
            {
                type        = FormatType.Doc;
                filename    = "Sample.doc";
                contenttype = "application/msword";
            }
            //Save as .xml format
            else if (Group1 == "WordML")
            {
                type        = FormatType.WordML;
                filename    = "Sample.xml";
                contenttype = "application/msword";
            }
            #endregion Document SaveOption
            MemoryStream ms = new MemoryStream();
            document.Save(ms, type);
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }
        public ActionResult TableStyles(string Group1, string Group2)
        {
            if (Group1 == null)
            {
                return(View());
            }
            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;

            dataPath = basePath + @"/DocIO/TemplateTableStyle.doc";
            WordDocument document   = new WordDocument();
            FileStream   fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            document.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;

            //Create MailMergeDataTable
            MailMergeDataTable mailMergeDataTable = GetMailMergeDataTable();

            //Execute Mail Merge with groups.
            document.MailMerge.ExecuteGroup(mailMergeDataTable);

            #region Built-in Style
            if (Group1 == "Built-in")
            {
                //Get table to apply style.
                WTable table = (WTable)document.LastSection.Tables[0];
                //Apply built-in table style to the table.
                table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent5);
            }
            #endregion Built-in Style

            #region Custom Style
            else
            {
                #region Custom table styles
                //Get table to apply style
                WTable table = (WTable)document.LastSection.Tables[0];
                #region Apply Table style
                WTableStyle tableStyle = document.AddTableStyle("Tablestyle") as WTableStyle;
                Color       borderColor = Color.WhiteSmoke;
                Color       firstRowBackColor = Color.Blue;
                Color       backColor = Color.WhiteSmoke;
                ConditionalFormattingStyle firstRowStyle, lastRowStyle, firstColumnStyle, lastColumnStyle, oddColumnBandingStyle, oddRowBandingStyle, evenRowBandingStyle;

                #region Table Properties
                tableStyle.TableProperties.RowStripe    = 1;
                tableStyle.TableProperties.ColumnStripe = 1;
                tableStyle.TableProperties.LeftIndent   = 0;

                tableStyle.TableProperties.Paddings.Top    = 0;
                tableStyle.TableProperties.Paddings.Bottom = 0;
                tableStyle.TableProperties.Paddings.Left   = 5.4f;
                tableStyle.TableProperties.Paddings.Right  = 5.4f;

                tableStyle.TableProperties.Borders.Top.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Top.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Top.Color      = Color.AliceBlue;
                tableStyle.TableProperties.Borders.Top.Space      = 0;

                tableStyle.TableProperties.Borders.Bottom.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Bottom.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Bottom.Color      = borderColor;
                tableStyle.TableProperties.Borders.Bottom.Space      = 0;

                tableStyle.TableProperties.Borders.Left.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Left.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Left.Color      = borderColor;
                tableStyle.TableProperties.Borders.Left.Space      = 0;

                tableStyle.TableProperties.Borders.Right.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Right.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Right.Color      = borderColor;
                tableStyle.TableProperties.Borders.Right.Space      = 0;

                tableStyle.TableProperties.Borders.Horizontal.BorderType = BorderStyle.Single;
                tableStyle.TableProperties.Borders.Horizontal.LineWidth  = 1f;
                tableStyle.TableProperties.Borders.Horizontal.Color      = borderColor;
                tableStyle.TableProperties.Borders.Horizontal.Space      = 0;
                #endregion

                #region Conditional Formatting Properties
                #region First Row Conditional Formatting Style
                firstRowStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.FirstRow);

                #region Character format
                firstRowStyle.CharacterFormat.Bold      = true;
                firstRowStyle.CharacterFormat.BoldBidi  = true;
                firstRowStyle.CharacterFormat.TextColor = Color.FromArgb(255, 255, 255, 255);
                #endregion

                #region Table Cell Properties
                firstRowStyle.CellProperties.Borders.Top.BorderType = BorderStyle.Single;
                firstRowStyle.CellProperties.Borders.Top.LineWidth  = 1f;
                firstRowStyle.CellProperties.Borders.Top.Color      = borderColor;
                firstRowStyle.CellProperties.Borders.Top.Space      = 0;

                firstRowStyle.CellProperties.Borders.Bottom.BorderType = BorderStyle.Single;
                firstRowStyle.CellProperties.Borders.Bottom.LineWidth  = 1f;
                firstRowStyle.CellProperties.Borders.Bottom.Color      = borderColor;
                firstRowStyle.CellProperties.Borders.Bottom.Space      = 0;

                firstRowStyle.CellProperties.Borders.Left.BorderType = BorderStyle.Single;
                firstRowStyle.CellProperties.Borders.Left.LineWidth  = 1f;
                firstRowStyle.CellProperties.Borders.Left.Color      = borderColor;
                firstRowStyle.CellProperties.Borders.Left.Space      = 0;

                firstRowStyle.CellProperties.Borders.Right.BorderType = BorderStyle.Single;
                firstRowStyle.CellProperties.Borders.Right.LineWidth  = 1f;
                firstRowStyle.CellProperties.Borders.Right.Color      = borderColor;
                firstRowStyle.CellProperties.Borders.Right.Space      = 0;

                firstRowStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;

                firstRowStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;

                firstRowStyle.CellProperties.BackColor    = firstRowBackColor;
                firstRowStyle.CellProperties.ForeColor    = Color.FromArgb(0, 255, 255, 255);
                firstRowStyle.CellProperties.TextureStyle = TextureStyle.TextureNone;
                #endregion
                #endregion

                #region Last Row Conditional Formatting Style
                lastRowStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.LastRow);

                #region Character format
                lastRowStyle.CharacterFormat.Bold     = true;
                lastRowStyle.CharacterFormat.BoldBidi = true;
                #endregion

                #region Table Cell Properties
                lastRowStyle.CellProperties.Borders.Top.BorderType = BorderStyle.Double;
                lastRowStyle.CellProperties.Borders.Top.LineWidth  = .75f;
                lastRowStyle.CellProperties.Borders.Top.Color      = borderColor;
                lastRowStyle.CellProperties.Borders.Top.Space      = 0;

                lastRowStyle.CellProperties.Borders.Bottom.BorderType = BorderStyle.Single;
                lastRowStyle.CellProperties.Borders.Bottom.LineWidth  = 1f;
                lastRowStyle.CellProperties.Borders.Bottom.Color      = borderColor;
                lastRowStyle.CellProperties.Borders.Bottom.Space      = 0;

                lastRowStyle.CellProperties.Borders.Left.BorderType = BorderStyle.Single;
                lastRowStyle.CellProperties.Borders.Left.LineWidth  = 1f;
                lastRowStyle.CellProperties.Borders.Left.Color      = borderColor;
                lastRowStyle.CellProperties.Borders.Left.Space      = 0;

                lastRowStyle.CellProperties.Borders.Right.BorderType = BorderStyle.Single;
                lastRowStyle.CellProperties.Borders.Right.LineWidth  = 1f;
                lastRowStyle.CellProperties.Borders.Right.Color      = borderColor;
                lastRowStyle.CellProperties.Borders.Right.Space      = 0;

                lastRowStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;

                lastRowStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;
                #endregion
                #endregion

                #region First Column Conditional Formatting Style
                firstColumnStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.FirstColumn);
                #region Character format
                firstColumnStyle.CharacterFormat.Bold     = true;
                firstColumnStyle.CharacterFormat.BoldBidi = true;
                #endregion
                #endregion

                #region Last Column Conditional Formatting Style
                lastColumnStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.LastColumn);
                #region Character format
                lastColumnStyle.CharacterFormat.Bold     = true;
                lastColumnStyle.CharacterFormat.BoldBidi = true;
                #endregion
                #endregion

                #region Odd Column Banding Conditional Formatting Style
                oddColumnBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.OddColumnBanding);
                #region Table Cell Properties
                oddColumnBandingStyle.CellProperties.BackColor    = backColor;
                oddColumnBandingStyle.CellProperties.ForeColor    = Color.FromArgb(0, 255, 255, 255);
                oddColumnBandingStyle.CellProperties.TextureStyle = TextureStyle.TextureNone;
                #endregion
                #endregion

                #region Odd Row Banding Conditional Formatting Style
                oddRowBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.OddRowBanding);
                #region Table Cell Properties
                oddRowBandingStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;

                oddRowBandingStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;

                oddRowBandingStyle.CellProperties.BackColor    = backColor;
                oddRowBandingStyle.CellProperties.ForeColor    = Color.FromArgb(0, 255, 255, 255);
                oddRowBandingStyle.CellProperties.TextureStyle = TextureStyle.TextureNone;
                #endregion
                #endregion

                #region Even Row Banding Conditional Formatting Style
                evenRowBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.EvenRowBanding);
                #region Table Cell Properties
                evenRowBandingStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;
                evenRowBandingStyle.CellProperties.Borders.Vertical.BorderType   = BorderStyle.Cleared;
                #endregion
                #endregion
                #endregion
                #endregion
                table.ApplyStyle("Tablestyle");
                #endregion
            }
            #endregion Custom Style
            #endregion

            FormatType type        = FormatType.Docx;
            string     filename    = "Sample.docx";
            string     contenttype = "application/vnd.ms-word.document.12";
            #region Document SaveOption
            //Save as .xml format
            if (Group2 == "WordML")
            {
                type        = FormatType.WordML;
                filename    = "Sample.xml";
                contenttype = "application/msword";
            }
            #endregion Document SaveOption
            MemoryStream ms = new MemoryStream();
            document.Save(ms, type);
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }