Friday, 14 November 2014 06:05

Convert Excel Worksheet to Image in WPF

Since Excel spreadsheets or diagrams are difficult to distribute, it is reasonable that we frequently convert our Excel files to a web-friendly format, such as image. Plus, if we convert Excel to image, the data cannot be formatted and modified directly. In this article, I’ll introduce how to save each worksheet in an Excel file as an image to local folder in WPF using Spire.XLS for WPF.

The sample file for test contains three worksheets, sheet 1 and sheet 2 have some contents in them. What we need is to convert each worksheet that contains contents to image respectively.

Convert Excel Worksheet to Image in WPF

Detailed Steps:

Step 1: Create a new project by choosing WPF Application in Visual Studio, add a button in MainWindow, double click the button to write code.

Step 2: Create a new instance of Spire.Xls.Workbook class and load the sample Excel file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("sample.xlsx", ExcelVersion.Version2010);

Step 3: Use for sentence to traverse each worksheet in the Excel. Call Worksheet.SaveToImage() to save worksheet as image, set image format as png.

for (int i = 0; i < workbook.Worksheets.Count; i++)
{
    workbook.Worksheets[i].SaveToImage(string.Format("result-{0}.png", i));
}

Result:

Image 1

Convert Excel Worksheet to Image in WPF

Image 2

Convert Excel Worksheet to Image in WPF

Full Code:

using Spire.Xls;

namespace WpfApplication
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("sample.xlsx", ExcelVersion.Version2010);
            for (int i = 0; i < workbook.Worksheets.Count; i++)
            {
                workbook.Worksheets[i].SaveToImage(string.Format("result-{0}.png", i));
            }
        }
    }
}
Tuesday, 11 November 2014 07:56

Set all fields on a form to read only

Form field has been widely used by developers to display, catch and edit data. Developers may create a form to let others to fill the data and then save the form as a non-fillable file and set it to read only. Spire.PDF supports to create and fill form field; this article will focus on show you how to change the field's value and set all the fields on a form to read only.

By using the PdfFormWidget class, we can get the PDF field collection on the form and then update the values on it. Here comes to the code snippet of how to change the form field's value and set it to read only:

Step 1: Create PDFDocument and load from file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("FormField.pdf");

Step 2: Get the PDF field collection on the Form.

PdfFormWidget widget = doc.Form as PdfFormWidget;

Step 3: Traverse each PDF field in pdf field collection.

for (int i = 0; i < widget.FieldsWidget.List.Count; i++)
  {
    PdfField f = widget.FieldsWidget.List[i] as PdfField;

Step 4: Find a PDF field named username and set the value for it.

if (f.Name == "username")
{
  //Convert the pdf field to PdfTextBoxFieldWidget
PdfTextBoxFieldWidget textboxField = f as PdfTextBoxFieldWidget;
  //Change its text
textboxField.Text = "Sky.Luo";
                }

Step 5: Set the field to read-only.

f.Flatten = true;
f.ReadOnly = true;

Step 6: Save the document to file and launch to view it.

doc.SaveToFile("FormFieldEdit.pdf");
System.Diagnostics.Process.Start("FormFieldEdit.pdf");

Effective screenshot of the read only form field:

How to set all fields on a form to read only

Full codes:

using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;

namespace ReadOnlyField
{
    class Program
    {
        static void Main(string []args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("FormField.pdf");

            PdfFormWidget widget = doc.Form as PdfFormWidget;

            for (int i = 0; i < widget.FieldsWidget.List.Count; i++)
            {
                PdfField f = widget.FieldsWidget.List[i] as PdfField;
                if (f.Name == "username")
                {
                    PdfTextBoxFieldWidget textboxField = f as PdfTextBoxFieldWidget;
                    textboxField.Text = "Sky.Luo";
                }
                f.Flatten = true;
                f.ReadOnly = true;
            }
            doc.SaveToFile("FormFieldEdit.pdf");
            System.Diagnostics.Process.Start("FormFieldEdit.pdf");
            
        }
    }
}

Some time back, one of registered members on our Forum had a requirement to display the value of HTML code in Excel cell. This article is aimed to provide a fine way to manage this issue using Spire.Doc and Spire.XLS.

Main Method:

At present, we have to use Document.LoadHTML() method which is available in Spire.Doc.Document class to load HTML string to a Word document, this way, HTML formatted text will be save in specific paragraphs. Then, get the paragraph with rich text style and return a RichTextString object, save RichText to a specified CellRange. Besides, the paragraph text style must be applied to this CellRange.

Detailed Steps:

Step 1: Create a new Workbook and Word document.

Workbook workbook = new Workbook();
Document doc = new Document();

Step 2: Save the HTML code to StringReader and load the HTML string to Word document.

StringReader sr = new StringReader("<span style=\"border-width:thin;border-color:#FFFFFF;\"><font color=#000000 size=8><b>U = Unchanged rate</b></font></span>");
doc.LoadHTML(sr, XHTMLValidationType.None);

Step 3: Get the formatted text from Word document and save to cell 'A4' in the first worksheet.

foreach (Section section in doc.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        if (paragraph.Items.Count > 0)
        {
           workbook.Worksheets[0].Range["A4"].RichText.Text += paragraph.Text;
        }   
     }
}

Step 4: Apply text style including font color and font size to cell 'A4'.

int index = 0;

foreach (var item in paragraph.Items)
{
    if (item is Spire.Doc.Fields.TextRange)
    {
        for (int i = index; i < (item as Spire.Doc.Fields.TextRange).Text.Length + index; i++)
        {
            ExcelFont excelFont = workbook.CreateFont();
            excelFont.FontName = (item as Spire.Doc.Fields.TextRange).CharacterFormat.FontName;
            excelFont.Size = (item as Spire.Doc.Fields.TextRange).CharacterFormat.FontSize;
            excelFont.IsBold = (item as Spire.Doc.Fields.TextRange).CharacterFormat.Bold;
            excelFont.IsItalic = (item as Spire.Doc.Fields.TextRange).CharacterFormat.Italic;
            excelFont.Underline = (FontUnderlineType)(item as Spire.Doc.Fields.TextRange).CharacterFormat.UnderlineStyle; excelFont.Color = (item as Spire.Doc.Fields.TextRange).CharacterFormat.TextColor;
            workbook.Worksheets[0].Range["A4"].RichText.SetFont(i, i, excelFont);
        }
    }
    index += (item as Spire.Doc.Fields.TextRange).Text.Length;

}

Step 5: Change the width and height of the row to achieve the best fit.

workbook.Worksheets[0].Range["A4"].AutoFitRows();

Step 6: Save changes to the workbook in a new file.

workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);

HTML-Formatted Text in Excel would be shown as:

Insert HTML-Formatted RichText into Excel Cell in C#

Full Code:

Workbook workbook = new Workbook();
Document doc = new Document();

StringReader sr = new StringReader("<span style=\"border-width:thin;border-color:#FFFFFF;\"><font color=#000000 size=8><b>U = Unchanged rate</b></font></span>");
doc.LoadHTML(sr, XHTMLValidationType.None);

int index = 0;

foreach (Section section in doc.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        if (paragraph.Items.Count > 0)
        {
            workbook.Worksheets[0].Range["A4"].RichText.Text += paragraph.Text;
            foreach (var item in paragraph.Items)
            {
                if (item is Spire.Doc.Fields.TextRange)
                {
for (int i = index; i < (item as Spire.Doc.Fields.TextRange).Text.Length + index; i++)
{
    ExcelFont excelFont = workbook.CreateFont();
    excelFont.FontName = (item as Spire.Doc.Fields.TextRange).CharacterFormat.FontName;
    excelFont.Size = (item as Spire.Doc.Fields.TextRange).CharacterFormat.FontSize;
    excelFont.IsBold = (item as Spire.Doc.Fields.TextRange).CharacterFormat.Bold;
    excelFont.IsItalic = (item as Spire.Doc.Fields.TextRange).CharacterFormat.Italic;
    excelFont.Underline = (FontUnderlineType)(item as Spire.Doc.Fields.TextRange).CharacterFormat.UnderlineStyle;
    excelFont.Color = (item as Spire.Doc.Fields.TextRange).CharacterFormat.TextColor;
    workbook.Worksheets[0].Range["A4"].RichText.SetFont(i, i, excelFont);
}
                }
                index += (item as Spire.Doc.Fields.TextRange).Text.Length;
            }
        }
    }
}
workbook.Worksheets[0].Range["A4"].AutoFitRows();
workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);

In our daily work, we may have the requirement to add custom properties with fields to a Word document. As is shown in the following Word document, I have created three custom property fields for easily inserting or updating information.

How to Remove Custom Property Fields in C#, VB.NET

However, a custom property field may lose its value if we don’t want to use it any more, or a custom field might be created with wrong information, in such cases, we can choose to delete these fields manually and programmatically. In this article, I’ll introduce a C# and VB.NET solution to remove custom property fields using Spire.Doc.

Detailed Steps

Step 1: Create a new instance of Spire.Doc.Document class and load the sample file with specified path.

Document doc = new Document();
doc.LoadFromFile("FieldSample.docx", FileFormat.Docx);

Step 2: Get custom document properties object.

CustomDocumentProperties cdp = doc.CustomDocumentProperties;

Step 3: Use a for sentence and CustomDocumentProperties.Remove(string name) method to remove all custom property fields in the document.

for (int i = 0; i < cdp.Count; )
{
  cdp.Remove(cdp[i].Name);
}
doc.IsUpdateFields = true;

Step 4: Save the file.

doc.SaveToFile("Result.docx", FileFormat.Docx);

Output:

How to Remove Custom Property Fields in C#, VB.NET

Full Code:

C#
using Spire.Doc;
namespace RemoveProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("FieldSample.docx", FileFormat.Docx);
            CustomDocumentProperties cdp = doc.CustomDocumentProperties;
            for (int i = 0; i < cdp.Count; )
            {
                cdp.Remove(cdp[i].Name);
            }
            doc.IsUpdateFields = true;
            doc.SaveToFile("Result.docx", FileFormat.Docx);
        }
    }
}
VB.NET
Imports Spire.Doc
Namespace RemoveProperties
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("FieldSample.docx", FileFormat.Docx)
			Dim cdp As CustomDocumentProperties = doc.CustomDocumentProperties
			Dim i As Integer = 0
			While i < cdp.Count
				cdp.Remove(cdp(i).Name)
			End While
			doc.IsUpdateFields = True
			doc.SaveToFile("Result.docx", FileFormat.Docx)
		End Sub
	End Class
End Namespace
Wednesday, 05 November 2014 07:06

How to create gradient shape in PowerPoint in C#

A gradient is a smooth transition from one color to another, and the gradient backgrounds make your presentation very cool. This article will show you how to create a shape with gradient effects by using Spire.Presentation. With the help of Spire.Presentation, you can not only insert gradient shapes into the slides, but also insert solid shapes in PowerPoint in C# easily.

The following steps will give you clear information of how to fill a shape with gradient effects. We will use rectangle shape in this example.

Step 1: Create an instance of presentation.

Presentation ppt = new Presentation();

Step 2: Add a rectangle to the slide.

IAutoShape GradientShape = (IAutoShape)ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(200, 100, 287, 100));

Step 3: Set the Fill Type of the Shape to Gradient.

GradientShape.Fill.FillType = FillFormatType.Gradient;

Step 4: Set the start and end color for the gradient effects.

GradientShape.Fill.Gradient.GradientStops.Append(0, Color.Purple);
GradientShape.Fill.Gradient.GradientStops.Append(1, Color.Red);

Step 5: Save and Launch to view the resulted PPTX file.

ppt.SaveToFile("CreateGradientShape.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("CreateGradientShape.pptx");

Effective screenshot of the resulted gradient shape:

How to create gradient shape in PowerPoint in C#

Full codes:

using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;

namespace createGradientshape
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            IAutoShape GradientShape = (IAutoShape)ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(200, 100, 287, 100));

            GradientShape.Fill.FillType = FillFormatType.Gradient;
            GradientShape.Fill.Gradient.GradientStops.Append(0, Color.Purple);
            GradientShape.Fill.Gradient.GradientStops.Append(1, Color.Red);
            ppt.SaveToFile("CreateGradientShape.pptx", FileFormat.Pptx2010);
            System.Diagnostics.Process.Start("CreateGradientShape.pptx");
        }
    }
}
Wednesday, 05 November 2014 05:58

How to Set TopText of Barcode in WinForm

A barcode is a small image of lines and spaces that is often used in a store to reflect the description and price of a product, moreover, barcodes can be used in many other aspects in our daily life, such as tickets, medicine prescriptions, library books. In this article, I'll introduce you a way to add extra information in TopText of a barcode using Spire.Barcode in WinForm.

By default, 'E-iceblue' will be shown as TopText in a barcode if you don't request a key to remove it. Click here to see how to remove 'E-iceblue' logo in barcode. In this sample, more than one line of text will be added in TopText to replace 'E-iceblue'. Let's see detailed steps.

Step 1: Add Spire.Barcode controls to Visual Studio Toolbox.

Step 2: Create a Windows Forms project. Drag 'BarCodeControl' to your Form1. Here I changed the barcode type as EAN13.

How to Set TopText of Barcode in WinForm

Step 3: Double click 'button1' to write code. Customized TopText can be saved in BarCodeControl.TopText string.

string title = "Title: xxx" + Environment.NewLine;
string subject = "Subject: Information Technology" + Environment.NewLine;
string date = "Date: " + DateTime.Now.ToString() + Environment.NewLine;
string isbn = "ISBN: 1234567890005";
this.barCodeControl1.TopText = title + date + subject + isbn;

Step 4: Run the sample code and click 'button1' to get the new barcode. In addition, you can call BarCodeControl.SaveToFile() method to save the barcode as an image.

How to Set TopText of Barcode in WinForm

Full Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace SetTopText
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string title = "Title: xxx" + Environment.NewLine;
            string date = "Date: " + DateTime.Now.ToString() + Environment.NewLine;
            string subject = "Subject: Information Technology" + Environment.NewLine;
            string isbn = "ISBN: 1234567890005";
            this.barCodeControl1.TopText = title + date + subject + isbn;

        }
    }
}
Tuesday, 04 November 2014 09:08

Insert an existing Table by cloning in C#

In some case, we need make some modifications in an existing table but don't want destroy the original data, so we would like to copy the existing table then make some changes in the new table. How could we get the copied table? The easiest method is clone. There would introduce a solution to copy table and modify some data then insert the new table after original table via Spire.Doc.

Spire.Doc for .NET, a stand-alone .NET Word component, provides a method, Table.clone() to allow users to copy an existing table.

The main steps of the solution:

Firstly: load the word document with a table.

Document doc = new Document();
doc.LoadFromFile(@"CopyTable.doc");

The original document effect screenshot:

Insert an existing Table by cloning

Secondly: extract the existing table and call the table.clone () method to copy it.

Section se = doc.Sections[0];
Table original_Table =(Table) se.Tables[0];
Table copied_Table = original_Table.Clone();

Thirdly: extract the last row then traversal its cells to modify data.

string[] st = new string[] { "Guyana", "Georgetown", "South America", "214969", "800000" };
//get the last row of copied table
TableRow lastRow = copied_Table.Rows[copied_Table.Rows.Count - 1];
//change lastRow data.
lastRow.RowFormat.BackColor = Color.Gray;
for (int i = 0; i < lastRow.Cells.Count; i++)
    {
    lastRow.Cells[i].Paragraphs[0].Text = st[i];       
     }

Finally: call Section. tables.add() method to add the copied table in section and save this document.

se.Tables.Add(copied_Table);
doc.SaveToFile("result.doc", FileFormat.Doc);
The result document effect screenshot:

Insert an existing Table by cloning

Full code:

using Spire.Doc;
using System.Drawing;

namespace InsertingaAnExistingTable
{
    class Program
    {
        static void Main(string[] args)
        { 
//load a word document
            Document doc = new Document();
            doc.LoadFromFile(@"CopyTable.doc");

// extract the existing table
            Section se = doc.Sections[0];
            Table original_Table =(Table) se.Tables[0];

// copy the existing table to copied_Table via Table.clone()
            Table copied_Table = original_Table.Clone();
string[] st = new string[] { "Guyana", "Georgetown", "South America", "214969", "800000" };
            //get the last row of table
            TableRow lastRow = copied_Table.Rows[copied_Table.Rows.Count - 1];
            //change last row data.
            lastRow.RowFormat.BackColor = Color.Gray;
            for (int i = 0; i < lastRow.Cells.Count; i++)
            {
                lastRow.Cells[i].Paragraphs[0].Text = st[i];
            }
// add copied_Table in section
            se.Tables.Add(copied_Table);
            doc.SaveToFile("result.doc", FileFormat.Doc);     
        }
    }
}
Friday, 31 October 2014 06:13

Convert Word to Image in WPF

In some circumstances, we may need to convert or save Word documents as pictures. For one reason, a picture is difficult to edit; for another, compared with Word, pictures are much easier to be published for browsing. This article is aimed to explore how we can convert .doc/.docx to popular image formats such as Jpg, Png, Gif and Bmp in WPF using Spire.Doc.

Spire.Doc for WPF, as a professional Word component, provides a plenty of useful methods to manipulate Word documents in your WPF applications. Using Spire.Doc, developers are able to export Word documents as images with high quality. Here comes the method:

Step 1: Create a new project by choosing WPF Application in Visual Studio, add a button in MainWindow, double click the button to write code.

public partial class MainWindow : Window
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            
        }

Step 2: Initialize a new instance of Spire.Doc.Document class and load the sample Word file.

       Document doc = new Document("sample.docx", FileFormat.Docx2010);

Step 3: To convert Word to image in WPF, we need firstly save Word as BitmapSource by calling the method Document.SaveAsImage(ImageType type), then convert BitmapSource to Bitmap, then save the Bitmap as image with a specified format using Image.Save(). Here, I saved Bitmap as .Png.

       BitmapSource[] bss = doc.SaveToImages(ImageType.Bitmap);
            for (int i = 0; i < bss.Length; i++)
            {
                SourceToBitmap(bss[i]).Save(string.Format("img-{0}.png", i));
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {        

            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                bmp = new Bitmap(ms);
            }
            return bmp;
        }

Output of the first page:

Convert Word to Image in WPF

Entire Code:

using Spire.Doc;
using Spire.Doc.Documents;

namespace Word2Image
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Document doc = new Document("sample.docx", FileFormat.Docx2010);
            BitmapSource[] bss = doc.SaveToImages(ImageType.Bitmap);
            for (int i = 0; i < bss.Length; i++)
            {
                SourceToBitmap(bss[i]).Save(string.Format("img-{0}.png", i));
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {        

            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                bmp = new Bitmap(ms);
            }
            return bmp;
        }
    }
}

Excel header and footer give additional information of an Excel sheet, such as the page number, author name, topic name and date etc. With the help of Spire.XLS, developers can easily add text header and footer into an excel spreadsheet. Sometimes, the font and size of the header and footer may be different with the font in the excel documents, and it makes the document in disorder. This article will demonstrate how to change the font and size for the text on excel header and footer.

Firstly, check the original font and size on Excel header and footer:

How to change the font and size for Excel header and footer in C#

By using Spire.XLS, we can easily set the new size and font for the header and footer text. Here comes to the steps of how to change the font and size for excel header and footer:

Step 1: Create an excel document and load the Excel with header and footer from file:

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Gets the first worksheet in the Excel file

Worksheet sheet = workbook.Worksheets[0];

Step 3: Set the new font and size for the header and footer

string text = sheet.PageSetup.LeftHeader;
//"Arial Unicode MS" is font name, "18" is font size
text = "&\"Arial Unicode MS\"&18 Header Footer Sample by Spire.XLS ";
sheet.PageSetup.LeftHeader = text;
sheet.PageSetup.RightFooter = text;

Step 4: Save the document to file and preview it

workbook.SaveToFile(@"..\Result.xlsx",ExcelVersion.Version2010);
System.Diagnostics.Process.Start(@"..\Result.xlsx");

Effective screenshot after changing the font and size for the header:

How to change the font and size for Excel header and footer in C#

Full codes:

using Spire.Xls;
namespace Changefontforheaderfooter
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            string text = sheet.PageSetup.LeftHeader;
            //"Arial Unicode MS" is font name, "18" is font size
            text = "&\"Arial Unicode MS\"&18 Header Footer Sample by Spire.XLS ";
            sheet.PageSetup.LeftHeader = text;
            sheet.PageSetup.RightFooter = text;
            //Save workbook and preview it
            workbook.SaveToFile(@"..\Result.xlsx",ExcelVersion.Version2010);
            System.Diagnostics.Process.Start(@"..\Result.xlsx");
        }
    }
}

Every time we create a plain table in a Word document, we may want to change the style of the table so as to make it more vivid and attractive. In our previous article, we have demonstrated how to set Word table formatting with custom style. However, if we do not have much time to do so, we can apply built-in table styles to own a better appearance within a few minutes. This article focuses on how to apply built-in table styles to existing Word tables using Spire.Doc with C#, VB.NET.

In the class of Spire.Doc.Table, it provides Table.ApplyStyle() method which enable us to easily change the layout of tables with default styles. As is shown below, here is a Word document that contains two plain tables in the first page. Let us see how we can format the table style with several lines of code.

Test File:

Apply Built-In Table Styles to Existing Word Tables in C#, VB.NET

Code Snippet:

Step 1: Create a new Word document and load the test file.

Document doc = new Document("table.docx", FileFormat.Docx2010);

Step 2: Get the two tables from document.

Section section = doc.Sections[0];
Table table1 = section.Tables[0] as Table;
Table table2 = section.Tables[1] as Table;

Step 3: Apply tables with built-in table styles separately.

table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2);
table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1);

Step 4: Save the file.

doc.SaveToFile("result.docx", FileFormat.Docx);

Output:

Apply Built-In Table Styles to Existing Word Tables in C#, VB.NET

Entire Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
namespace ApplyTableStyles
{
    class Program
    {

        static void Main(string[] args)
        {

            Document doc = new Document("table.docx", FileFormat.Docx2010);
            Section section = doc.Sections[0];
            Table table1 = section.Tables[0] as Table;
            Table table2 = section.Tables[1] as Table;

            table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2);
            table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1);
            doc.SaveToFile("result.docx", FileFormat.Docx);

        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Namespace ApplyTableStyles
	Class Program

		Private Shared Sub Main(args As String())

			Dim doc As New Document("table.docx", FileFormat.Docx2010)
			Dim section As Section = doc.Sections(0)
			Dim table1 As Table = TryCast(section.Tables(0), Table)
			Dim table2 As Table = TryCast(section.Tables(1), Table)

			table1.ApplyStyle(DefaultTableStyle.MediumShading1Accent2)
			table2.ApplyStyle(DefaultTableStyle.MediumShading2Accent1)
			doc.SaveToFile("result.docx", FileFormat.Docx)

		End Sub
	End Class
End Namespace