Thursday, 03 March 2016 08:15

Create Word Table in WPF with C#

A table is a great way to display data into group, frequently used in our financial reports, academic reports and any other documents that contain a group of similar data. In this article, I am fusing on how to insert a table in Word, fill the table with data and how to format the cells using Spire.Doc for WPF with C#.

Code Snippets

Step 1: Initialize a new instance of Document class, add a section to it.

Document doc = new Document();
Spire.Doc.Section s = doc.AddSection();

Step 2: Define the data that will be filled with table.

String[] Header ={"Vendor No","Vendor Name", "Address","City","State","Zip"};  
String[][] data = {
                      new String[]{"3501","Cacor Corporation","161 Southfield Rd","Southfield","OH","60093"},
                      new String[]{"3502","Underwater","50 N3rd Street","Indianapolis","IN","46208"},
                      new String[]{"3503","J.W. Luscher Mfg.","65 Addams Street","Berkely","MA","02779"},
                      new String[]{"3504","Scuba Professionals","3105 East Brace","Rancho Dominguez","CA","90221"},
                      new String[]{"3505","Divers' Supply Shop", "5208 University Dr","Macon","GA","20865"},
                      new String[]{"3506","Techniques","52 Dolphin Drive","Redwood City","CA","94065-1086"},
                  };

Step 3: Add a table with border to section, set the rows and columns number based on the data length.

Spire.Doc.Table table = s.AddTable(true);
table.ResetCells(data.Length + 1, Header.Length);

Step 4: Fill the table with the predefined data and format the cells.

Spire.Doc.TableRow FRow= table.Rows[0];
FRow.IsHeader = true;
FRow.Height = 23;
FRow.RowFormat.BackColor = System.Drawing.Color.DarkBlue;
for (int i = 0; i < Header.Length; i++)
{
    //Cell Alignment
    Paragraph p = FRow.Cells[i].AddParagraph();
    FRow.Cells[i].CellFormat.VerticalAlignment = Spire.Doc.Documents.VerticalAlignment.Middle;
    p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
    //Fill Header data and Format the Cells
    TextRange TR = p.AppendText(Header[i]);
    TR.CharacterFormat.FontName = "Calibri";
    TR.CharacterFormat.FontSize = 12;
    TR.CharacterFormat.TextColor = System.Drawing.Color.White;
    TR.CharacterFormat.Bold = true;
}
for (int r = 0; r < data.Length; r++)
{
    TableRow DataRow = table.Rows[r + 1];
    //Row Height
    DataRow.Height = 15;
    //C Represents Column.
    for (int c = 0; c < data[r].Length; c++)
    {
        //Cell Alignment
        DataRow.Cells[c].CellFormat.VerticalAlignment = Spire.Doc.Documents.VerticalAlignment.Middle;
        //Fill Data in Rows
        Paragraph p2 =DataRow.Cells[c].AddParagraph();
        TextRange TR2=p2.AppendText(data[r][c]);
        //Format Cells
        p2.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
        TR2.CharacterFormat.FontName = "Calibri";
        TR2.CharacterFormat.FontSize = 10;
        TR2.CharacterFormat.TextColor = System.Drawing.Color.Black;
    }
}

Step 5: Call AutoFitBebavior() method to make the table AutoFit to Window.

table.AutoFitBehavior(AutoFitBehaviorType.wdAutoFitWindow);

Step 6: Save and launch the file.

doc.SaveToFile("WordTable.docx");
System.Diagnostics.Process.Start("WordTable.docx");

Output:

Create Word Table in WPF with C#

Full Code:

private void button1_Click(object sender, RoutedEventArgs e)
{
    Document doc = new Document();
    Spire.Doc.Section s = doc.AddSection();
    
    String[] Header ={"Vendor No","Vendor Name", "Address","City","State","Zip"};  
    String[][] data = {
                          new String[]{"3501","Cacor Corporation","161 Southfield Rd","Southfield","OH","60093"},
                          new String[]{"3502","Underwater","50 N3rd Street","Indianapolis","IN","46208"},
                          new String[]{"3503","J.W. Luscher Mfg.","65 Addams Street","Berkely","MA","02779"},
                          new String[]{"3504","Scuba Professionals","3105 East Brace","Rancho Dominguez","CA","90221"},
                          new String[]{"3505","Divers' Supply Shop", "5208 University Dr","Macon","GA","20865"},
                          new String[]{"3506","Techniques","52 Dolphin Drive","Redwood City","CA","94065-1086"},
                      };
    Spire.Doc.Table table = s.AddTable(true);
    table.ResetCells(data.Length + 1, Header.Length);   
    Spire.Doc.TableRow FRow= table.Rows[0];
    FRow.IsHeader = true;
    FRow.Height = 23;
    FRow.RowFormat.BackColor = System.Drawing.Color.DarkBlue;
    for (int i = 0; i < Header.Length; i++)
    {
        Paragraph p = FRow.Cells[i].AddParagraph();
        FRow.Cells[i].CellFormat.VerticalAlignment = Spire.Doc.Documents.VerticalAlignment.Middle;
        p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
        TextRange TR = p.AppendText(Header[i]);
        TR.CharacterFormat.FontName = "Calibri";
        TR.CharacterFormat.FontSize = 12;
        TR.CharacterFormat.TextColor = System.Drawing.Color.White;
        TR.CharacterFormat.Bold = true;
    }
    for (int r = 0; r < data.Length; r++)
    {
        TableRow DataRow = table.Rows[r + 1];
        DataRow.Height = 15;
        for (int c = 0; c < data[r].Length; c++)
        {
            DataRow.Cells[c].CellFormat.VerticalAlignment = Spire.Doc.Documents.VerticalAlignment.Middle;
            Paragraph p2 =DataRow.Cells[c].AddParagraph();
            TextRange TR2=p2.AppendText(data[r][c]);
            p2.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
            TR2.CharacterFormat.FontName = "Calibri";
            TR2.CharacterFormat.FontSize = 10;
            TR2.CharacterFormat.TextColor = System.Drawing.Color.Black;
        }
    }
    table.AutoFitBehavior(AutoFitBehaviorType.wdAutoFitWindow);
    doc.SaveToFile("WordTable.docx");
    System.Diagnostics.Process.Start("WordTable.docx");
}

With the help of Spire.Doc for WPF, developers can add word documents easily for their WPF applications. When we want to show opinions or additional information about words, phrases or paragraphs, we can add the comments to the word documents to give more information about the contents. Spire.Doc offers a class of Spire.Doc.Fields.Comments to enable developers to work with comments easily. This article will demonstrate how to add the comments to the word documents in C# for WPF applications.

Note: Before Start, please download the latest version of Spire.Doc and add Spire.Doc.Wpf.dll in the bin folder as the reference of Visual Studio.

Here comes to the steps of how to add comments to word documents in C#:

Step 1: Create a new word document and load the document from file.

Document document = new Document();
document.LoadFromFile("sample.docx");

Step 2: Get Paragraph to Insert Comment.

Section section = document.Sections[0];
Paragraph paragraph = section.Paragraphs[2];

Step 3: Insert the comment.

string str = "This is the first comment";
Comment comment = paragraph.AppendComment(str);
comment.Format.Author = "E-iceblue";
comment.Format.Initial = "CM";

Step 4: Save the document to file.

document.SaveToFile("Addcomment.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("Addcomment.docx");

Effective screenshot of adding the word comments in C#:

How to add comments to word documents in C# for WPF applications

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            {
                Document document = new Document();
                document.LoadFromFile("sample.docx");

                Section section = document.Sections[0];
                Paragraph paragraph = section.Paragraphs[2];

                string str = "This is the first comment";
                Comment comment = paragraph.AppendComment(str);
                comment.Format.Author = "E-iceblue";
                comment.Format.Initial = "CM";

                document.SaveToFile("Addcomment.docx", FileFormat.Docx);
                System.Diagnostics.Process.Start("Addcomment.docx");

            }



        }
    }
}
Friday, 26 February 2016 08:43

How to Find and Highlight Excel Data in WPF

In Microsoft Excel, we can easily find the data we want by using the find function. But how to achieve this programmatically? With Spire.XLS for WPF, not only can we find the specific data in excel with high-efficiency, but also we can highlight it with different color.

In this article, we’ll demonstrate how to find and highlight excel data using Spire.XLS for WPF in C# and VB.NET.

At first, please download Spire.XLS and install it correctly, then add Spire.XLS.Wpf.dll and Spire.License.dll from the installation folder as reference.

Below is the effective screenshot:

How to Find and Highlight Excel Data in WPF

Detail steps:

Use namespace:

using System.Windows;
using Spire.Xls;
using System.Drawing;

Step 1: Initialize a new Workbook instance and load the sample excel document from file.

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

Step 2: Get its first worksheet, then find and highlight the specific number 1502 in worksheet 1.

Worksheet sheet = workbook.Worksheets[0];
foreach (CellRange range in sheet.FindAllNumber(1502,true))
{
    range.Style.Color = Color.LawnGreen;
}

Apart from finding number, Spire.XLS also supports us to find string, datetime, bool, etc.

Step 3: Save and launch the file.

workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("result.xlsx");

Full codes:

[C#]
private void button1_Click(object sender, RoutedEventArgs e)
{
    //load the sample excel document from file
    Workbook workbook = new Workbook();
    workbook.LoadFromFile("Sample.xlsx");

    //find and highlight excel data
    Worksheet sheet = workbook.Worksheets[0];
    foreach (CellRange range in sheet.FindAllNumber(1502,true))
    {
        range.Style.Color = Color.LawnGreen;
    }
    //save and launch the file
    workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);
    System.Diagnostics.Process.Start("result.xlsx");
}
[VB.NET]
Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
	'load the sample excel document from file
	Dim workbook As New Workbook()
	workbook.LoadFromFile("Sample.xlsx")

	'find and highlight excel data
	Dim sheet As Worksheet = workbook.Worksheets(0)
	For Each range As CellRange In sheet.FindAllNumber(1502,True)
		range.Style.Color = Color.LawnGreen
	Next
	'save and launch the file
	workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010)
	System.Diagnostics.Process.Start("result.xlsx")
End Sub
Friday, 26 February 2016 07:46

Add formatted comments to Excel in WPF

Excel comments in individual cells are extra information that explain more about the data in these cells. The information can be notes for readers, reminders for yourself, and cross-references to other reports. In this article, I am going to introduce how to add and format Excel comments using Spire.XLS for WPF.

Before start, please download Spire.XLS Pack and add the Spire.XLS.Wpf.dll and Spire.License.dll from Bin folder to reference of your WPF project.

Code Snippets:

Step 1: Initialize a new Workbook, get the first worksheet from workbook.

Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

Step 2: Create a font style that will be used to format comment.

ExcelFont font = wb.CreateFont();
font.FontName = "Calibri";
font.Color = Color.Blue;
font.Size = 10;
font.IsBold = true;

Step 3: Add a comment to C4 and set the size of comment box, set the text and set font for specified range of characters.

ExcelComment comment = sheet.Range["C4"].Comment;
comment.Height = 80;
comment.Width = 200;
comment.RichText.Text = "This comment is made by Spire.XLS for WPF.";
comment.RichText.SetFont(23, 40, font);

Step 4: Save and launch the file.

wb.SaveToFile("result.xlsx", ExcelVersion.Version2013);
System.Diagnostics.Process.Start("result.xlsx");

Output:

Add formatted comments to Excel in WPF

Full Code:

[C#]
using Spire.Xls;
using System.Drawing;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Workbook wb = new Workbook();
            Worksheet sheet = wb.Worksheets[0];

            ExcelFont font = wb.CreateFont();
            font.FontName = "Calibri";
            font.Color = Color.Blue;
            font.Size = 10;
            font.IsBold = true;

            ExcelComment comment = sheet.Range["C4"].Comment;
            comment.Height = 80;
            comment.Width = 200;
            comment.RichText.Text = "This comment is made by Spire.XLS for WPF.";
            comment.RichText.SetFont(23, 40, font);

            wb.SaveToFile("result.xlsx", ExcelVersion.Version2013);
            System.Diagnostics.Process.Start("result.xlsx");

        }
    }
}
[VB.NET]
Imports Spire.Xls
Imports System.Drawing
Imports System.Windows

Namespace WpfApplication1
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub
		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
			Dim wb As New Workbook()
			Dim sheet As Worksheet = wb.Worksheets(0)

			Dim font As ExcelFont = wb.CreateFont()
			font.FontName = "Calibri"
			font.Color = Color.Blue
			font.Size = 10
			font.IsBold = True

			Dim comment As ExcelComment = sheet.Range("C4").Comment
			comment.Height = 80
			comment.Width = 200
			comment.RichText.Text = "This comment is made by Spire.XLS for WPF."
			comment.RichText.SetFont(23, 40, font)

			wb.SaveToFile("result.xlsx", ExcelVersion.Version2013)
			System.Diagnostics.Process.Start("result.xlsx")

		End Sub
	End Class
End Namespace

Word hyperlink gives a large amount of information of the original word and image. The text and image with hyperlinks can guides readers to a Web page, e-mail address, or the other files and documents. In this article, we’re focusing on how to insert hyperlink into the text in C# on WPF applications with the help of Spire.Doc for WPF.

Note: Before Start, please download the latest version of Spire.Doc and add Spire.Doc.Wpf.dll in the bin folder as the reference of Visual Studio.

Here comes to the code snippets:

Step 1: Create a word document and add a section and paragraph to it.

Document document = new Document();
Section Sec = document.AddSection();
Paragraph Para = Sec.AddParagraph();

Step 2: Set the styles for the text and hyperlinks on the paragraph.

ParagraphStyle txtStyle = new ParagraphStyle(document);
txtStyle.Name = "Style";
txtStyle.CharacterFormat.FontName = "Calibri";
txtStyle.CharacterFormat.FontSize = 16;
txtStyle.CharacterFormat.TextColor = System.Drawing.Color.RosyBrown;
document.Styles.Add(txtStyle);
ParagraphStyle hyperlinkstyle = new ParagraphStyle(document);
hyperlinkstyle.Name = "linkStyle";
hyperlinkstyle.CharacterFormat.FontName = "Calibri";
hyperlinkstyle.CharacterFormat.FontSize = 14;
document.Styles.Add(hyperlinkstyle);

Step 3: Add the text to the paragraph with style and link it to a web page.

Para = Sec.AddParagraph();
Para.AppendText("Home page");
Para.ApplyStyle(txtStyle.Name);
Para = Sec.AddParagraph();
Para.AppendHyperlink("HomePage", "www.e-iceblue.com",HyperlinkType.WebLink);
Para.ApplyStyle(hyperlinkstyle.Name);

Step 4: Add the text to the paragraph with style and link it to an email address.

Para = Sec.AddParagraph();
Para.AppendText("Contact US");
Para.ApplyStyle(txtStyle.Name);
Para = Sec.AddParagraph();
Para.AppendHyperlink("mailto:[email protected]", "[email protected]",HyperlinkType.EMailLink);
Para.ApplyStyle(hyperlinkstyle.Name);

Step 5: Save the document to file and launch to preview it.

document.SaveToFile("Hyperlink.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("Hyperlink.docx");

Effective screenshot of adding hyperlinks to the word document in C#:

How to create word hyperlinks in C# on WPF applications

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Document document = new Document();
            Section Sec = document.AddSection();
            Paragraph Para = Sec.AddParagraph();

            ParagraphStyle txtStyle = new ParagraphStyle(document);
            txtStyle.Name = "Style";
            txtStyle.CharacterFormat.FontName = "Calibri";
            txtStyle.CharacterFormat.FontSize = 16;
            txtStyle.CharacterFormat.TextColor = System.Drawing.Color.RosyBrown;
            document.Styles.Add(txtStyle);
            ParagraphStyle hyperlinkstyle = new ParagraphStyle(document);
            hyperlinkstyle.Name = "linkStyle";
            hyperlinkstyle.CharacterFormat.FontName = "Calibri";
            hyperlinkstyle.CharacterFormat.FontSize = 14;
            document.Styles.Add(hyperlinkstyle);

            Para = Sec.AddParagraph();
            Para.AppendText("Home page");
            Para.ApplyStyle(txtStyle.Name);

            Para = Sec.AddParagraph();
            Para.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink);
            Para.ApplyStyle(hyperlinkstyle.Name);

            Para = Sec.AddParagraph();
            Para.AppendText("Contact US");
            Para.ApplyStyle(txtStyle.Name);

            Para = Sec.AddParagraph();
            Para.AppendHyperlink("mailto:[email protected]", "[email protected]", HyperlinkType.EMailLink);
            Para.ApplyStyle(hyperlinkstyle.Name);

            document.SaveToFile("Hyperlink.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Hyperlink.docx");
        }


    }
}
Friday, 19 February 2016 03:30

How to Change Word Font Color in WPF

By default, the font color of a word document is black. To achieve a more distinctive visual effect, we can change it to red, green or any other colors we like.

This article describes how to change word font color with Spire.Doc for WPF in C#, VB.NET.

At first, please download Spire.Doc and install it correctly, then add Spire.Doc. Wpf.dll and Spire.License.dll from the installation folder as reference.

Below is the screenshot of the original word document:

How to Change Word Font Color in WPF

Detail steps:

Use namespace:

using System.Drawing;
using System.Windows;
using Spire.Doc;
using Spire.Doc.Documents;

Step 1: Initialize a new instance of Document class and load the sample document from file.

Document document = new Document();
document.LoadFromFile("Story.docx");

Step 2: Get its first section and first paragraph (the Title), then set text color for paragraph 1.

Section section = document.Sections[0];
Paragraph p1 = section.Paragraphs[0];
ParagraphStyle s1 = new ParagraphStyle(document);
s1.Name = "TitleTextColor";
s1.CharacterFormat.TextColor = Color.RosyBrown;
document.Styles.Add(s1);
p1.ApplyStyle(s1.Name);

Step 3: Get the second paragraph and set text color for paragraph 2.

Paragraph p2 = section.Paragraphs[1];
ParagraphStyle s2 = new ParagraphStyle(document);
s2.Name = "BodyTextColor";
s2.CharacterFormat.TextColor = Color.DarkBlue;
document.Styles.Add(s2);
p2.ApplyStyle(s2.Name);

Step 4: Save and launch the file.

document.SaveToFile("FontColor.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("FontColor.docx");

Output:

How to Change Word Font Color in WPF

Full codes:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile("Story.docx");

            //Set Text Color for Paragraph 1(the Title)
            Section section = document.Sections[0];
            Paragraph p1 = section.Paragraphs[0];
            ParagraphStyle s1 = new ParagraphStyle(document);
            s1.Name = "TitleTextColor";
            s1.CharacterFormat.TextColor = Color.RosyBrown;
            document.Styles.Add(s1);
            p1.ApplyStyle(s1.Name);

            //Set Text Color for Paragraph 2
            Paragraph p2 = section.Paragraphs[1];
            ParagraphStyle s2 = new ParagraphStyle(document);
            s2.Name = "BodyTextColor";
            s2.CharacterFormat.TextColor = Color.DarkBlue;
            document.Styles.Add(s2);
            p2.ApplyStyle(s2.Name);

            //Save and Launch
            document.SaveToFile("FontColor.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("FontColor.docx");
        }



    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Imports System.Windows

Namespace WpfApplication1
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub
		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
			'Load Document
			Dim document As New Document()
			document.LoadFromFile("Story.docx")

			'Set Text Color for Paragraph 1(the Title)
			Dim section As Section = document.Sections(0)
			Dim p1 As Paragraph = section.Paragraphs(0)
			Dim s1 As New ParagraphStyle(document)
			s1.Name = "TitleTextColor"
			s1.CharacterFormat.TextColor = Color.RosyBrown
			document.Styles.Add(s1)
			p1.ApplyStyle(s1.Name)

			'Set Text Color for Paragraph 2
			Dim p2 As Paragraph = section.Paragraphs(1)
			Dim s2 As New ParagraphStyle(document)
			s2.Name = "BodyTextColor"
			s2.CharacterFormat.TextColor = Color.DarkBlue
			document.Styles.Add(s2)
			p2.ApplyStyle(s2.Name)

			'Save and Launch
			document.SaveToFile("FontColor.docx", FileFormat.Docx)
			System.Diagnostics.Process.Start("FontColor.docx")
		End Sub



	End Class
End Namespace

By using Spire.XLS, developers can easily set the IconSetType of conditional formatting. This article will demonstrate how to set the traffic lights icons in C# with the help of Spire.XLS.

Note: Before Start, please download the latest version of Spire.XLS and add Spire.xls.dll in the bin folder as the reference of Visual Studio.

Here comes to the code snippets:

Step 1: Create a new excel document instance and get the first worksheet.

Workbook wb = new Workbook();
Worksheet sheet = book.Worksheets[0];

Step 2: Add some data to the Excel sheet cell range and set the format for them.

sheet.Range["A1"].Text = "Traffic Lights";
sheet.Range["A2"].NumberValue = 0.95;
sheet.Range["A2"].NumberFormat = "0%";
sheet.Range["A3"].NumberValue = 0.5;
sheet.Range["A3"].NumberFormat = "0%";
sheet.Range["A4"].NumberValue = 0.1;
sheet.Range["A4"].NumberFormat = "0%";
sheet.Range["A5"].NumberValue = 0.9;
sheet.Range["A5"].NumberFormat = "0%";
sheet.Range["A6"].NumberValue = 0.7;
sheet.Range["A6"].NumberFormat = "0%";
sheet.Range["A7"].NumberValue = 0.6;
sheet.Range["A7"].NumberFormat = "0%";

Step 3: Set the height of row and width of column for Excel cell range.

sheet.AllocatedRange.RowHeight = 20;
sheet.AllocatedRange.ColumnWidth = 25;

Step 4: Add a conditional formatting of cell range and set its type to CellValue.

ConditionalFormatWrapper format1 = sheet.Range.ConditionalFormats.AddCondition(); 
format1.FormatType = ConditionalFormatType.CellValue;
format1.FirstFormula = "300";
format1.Operator = ComparisonOperatorType.Less;
format1.FontColor = Color.Black;
format1.BackColor = Color.LightSkyBlue;

Step 5: Add a conditional formatting of cell range and set its type to IconSet.

ConditionalFormatWrapper format = sheet.AllocatedRange.ConditionalFormats.AddCondition();
format.FormatType = ConditionalFormatType.IconSet;
format.IconSet.IconSetType = IconSetType.ThreeTrafficLights1;

Step 6: Save the document to file.

wb.SaveToFile("Light.xlsx", ExcelVersion.Version2010);

Effective screenshots of the traffic lights icons set by Spire.XLS.

How to set the traffic lights icons in C# by Spire.XLS

Thursday, 04 February 2016 06:54

Set XMP Metadata of a PDF Document in C#/VB.NET

XMP is a file labeling technology that lets you embed metadata into files themselves during the content creation process. With an XMP enabled application, your workgroup can capture meaningful information about a project (such as titles and descriptions, searchable keywords, and up-to-date author and copyright information) in a format that is easily understood by your team as well as by software applications, hardware devices, and even file formats.

In the Spire.PDF Version 3.6.135 and above, we add a new feature to read, set and load an existing XMP data from XML documents. This article presents how to set XMP Metadata while creating a PDF document.

Code Snippet:

Step 1: Initialize a new instance of PdfDocument class.

PdfDocument doc = new PdfDocument();

Step 2: Get XMP metadata from PDF document.

XmpMetadata meta = doc.XmpMetaData;

Step 3: Set author, create data, creator, keywords and etc. to metadata.

meta.SetAuthor("E-iceblue");
meta.SetCreateDate(DateTime.Now);
meta.SetCreator("Spire.PDF");
meta.SetCustomProperty("Field", "NewValue");
meta.SetKeywords("XMP");
meta.SetProducer("E-icenlue Co,.Ltd");
meta.SetSubject("XMP Metadata");
meta.SetTitle("Set XMP Metadata in PDF");

Step 4: Save the file.

doc.SaveToFile("XMP.pdf", FileFormat.PDF);

Output:

To view metadata in a PDF document, open it with Acrobat or Acrobat Reader and select ‘Document Properties’ in the File menu.

Set XMP Matedata of a PDF Document in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Xmp;
using System;

namespace SetXMPMetadata
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            XmpMetadata meta = doc.XmpMetaData;

            meta.SetAuthor("E-iceblue");
            meta.SetCreateDate(DateTime.Now);
            meta.SetCreator("Spire.PDF");
            meta.SetCustomProperty("Field", "NewValue");
            meta.SetKeywords("XMP");
            meta.SetProducer("E-icenlue Co,.Ltd");
            meta.SetSubject("XMP Metadata");
            meta.SetTitle("Set XMP Metadata in PDF");

            doc.SaveToFile("XMP.pdf", FileFormat.PDF);
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Xmp

Namespace SetXMPMetadata
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
Dim meta As XmpMetadata = doc.XmpMetaData

meta.SetAuthor("E-iceblue")
meta.SetCreateDate(DateTime.Now)
meta.SetCreator("Spire.PDF")
meta.SetCustomProperty("Field", "NewValue")
meta.SetKeywords("XMP")
meta.SetProducer("E-icenlue Co,.Ltd")
meta.SetSubject("XMP Metadata")
meta.SetTitle("Set XMP Metadata in PDF")
doc.SaveToFile("XMP.pdf", FileFormat.PDF)	
	   End Sub
	End Class
End Namespace
Wednesday, 03 February 2016 08:10

How to delete layer in PDF

With the help of Spire.PDF, we can add several kinds of layers such as line, image, string, ellipse, rectangle and pie to any page of a new or an existing pdf document. At the same time, it also supports us to delete specific layer from a pdf document.

In this section, we're going to demonstrate how to delete layer in PDF using Spire.PDF for .NET. To add layer to PDF, please check this article: How to add layers to PDF file in C#.

Below is the screenshot of the original PDF document which contains three layers: a red line layer and two image layers.

How to delete layer in PDF

Before start, download Spire.PDF and install it correctly, next add the corresponding dll file from the installation folder as reference of your project.

Detail steps:

Step 1: Initialize a new instance of PdfDocument class and load the sample document from file.

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

Step 2: Get its first page and delete the specific layer by name from page one.

PdfPageBase page = doc.Pages[0];
page.PageLayers.DeleteOldLayer("red line");

Step 3: Save and launch the file.

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

Effective screenshot after deleting:

How to delete layer in PDF

Full codes:

using Spire.Pdf;

namespace Delete_page_layer_in_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("AddLayer.pdf");
            PdfPageBase page = doc.Pages[0];
            page.PageLayers.DeleteOldLayer("red line");
            doc.SaveToFile("delete.pdf");
            System.Diagnostics.Process.Start("delete.pdf");
        }
    }
}
Monday, 01 February 2016 01:01

Hide or Unhide Excel Row and Column in WPF

Sometimes, hide row and column can make the data processing job easier and more efficient when working with a large excel file. However, hidden rows and columns are always hidden and invisible, for this reason, you need to unhide them before showing the whole excel file.

Spire.XLS for WPF provides developers four methods: HideRow(), HideColumn(), ShowRow() and ShowColumn() to hide or unhide excel row and column in WPF.

Please check the screenshot of the original excel worksheet:

Hide or Unhide Excel Row and Column in WPF

Before using the code, make sure that Spire.XLS is installed on system correctly, next create a WPF application project and add the dll file from the installation folder as reference, after that use following namespace:

using System.Windows;
using Spire.Xls;

Code snippets:

Step 1: Initialize a new instance of Workbook class and load the original excel file.

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

Step 2: Get the first worksheet of the file.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Hide or unhide row and column.

Hide the 8th row and the 3rd column:

sheet.HideRow(8);
sheet.HideColumn(3);

Unhide:

sheet.ShowRow(8);
sheet.ShowColumn(3);

Step 4: Save and launch the file.

Effective screenshot after hiding:

Hide or Unhide Excel Row and Column in WPF

Full codes:

using Spire.Xls;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //initialize a new instance
            Workbook workbook = new Workbook();
            //load the sample excel file
            workbook.LoadFromFile("Excel.xlsx");
            //get its first worksheet 
            Worksheet sheet = workbook.Worksheets[0];

            //hide the 8th row and the 3rd column of the first worksheet
            sheet.HideRow(8);
            sheet.HideColumn(3);
            /*//unhide
            sheet.ShowRow(8);           
            sheet.ShowColumn(3);*/

            //save and launch the file
            workbook.SaveToFile("Sample.xlsx", ExcelVersion.Version2010);
            System.Diagnostics.Process.Start(workbook.FileName);
        }

    }
}