PDF Table plays a significant role of clearly displaying data information in PDF document, which cannot be replaced by words. It provides great convenience for its users. For example, a product list can be more easily recognized and checked than numerous words. Thus, it is very necessary to learn how to generate table in PDF document.

In this article, I will not only introduce users how to generate table in PDF document, but also tell you how to set table style such as font, background color and data size by using Spire.PDF for WPF.

Spire.PDF for WPF enables you to quickly realize the task of drawing a PDF table by the below steps.

Step 1: Create a new project

  • Create a new project in WPF Application
  • Add a button in MainWindow, and set the button Content to be "Run"

Step 2: Add references and namespaces

  • Add System.Drawing and Spire.Pdf.Wpf.dll as references
  • Add below namespaces at the top of the method
[C#]
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Graphics.Fonts;
using Spire.Pdf.Tables;
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Graphics.Fonts
Imports Spire.Pdf.Tables

Step 3: Draw table in PDF document and set the table style

Create a new PDF document and set its margin

[C#]
             //create a new PDF document
            PdfDocument doc = new PdfDocument();

            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;

            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
            float y = 20;
[VB.NET]
           'create a new PDF document
	 Dim doc As New PdfDocument()

	 Dim unitCvtr As New PdfUnitConvertor()
	 Dim margin As New PdfMargins()
	  margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	  margin.Bottom = margin.Top
	  margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	  margin.Right = margin.Left

	  Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin)
	  Dim y As Single = 20

Set table title and then, add data information in PDF document

[C#]
           //add PDF title
            PdfBrush brush1 = PdfBrushes.Black;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Verdana", 14f, System.Drawing.FontStyle.Bold));
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Part Sales Information", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Part Sales Information", format1).Height;
            y = y + 10;

            //add data information
            String[] data
         = {
        "PartNo;Description;OnHand;OnOrder;Cost;ListPrice",
        "900;Dive kayak;24;16;1356.75;3999.95",
        "912;Underwater Diver Vehicle;5;3;504;1680",
        "1313;Regulator System;165;216;117.5;250",
        "1314;Second Stage Regulator;98;88;124.1;365",
        "1316;Regulator System;75;70;119.35;341",
        "1320;Second Stage Regulator;37;35;73.53;171",
        "1328;Regulator System;166;100;154.8;430",
        "1330;Alternate Inflation Regulator;47;43;85.8;260",
        "1364;Second Stage Regulator;128;135;99.9;270",
        "1390;First Stage Regulator;146;140;64.6;170",
        "1946;Second Stage Regulator;13;10;95.79;309",
        "1986;Depth/Pressure Gauge Console;25;24;73.32;188",
        "2314;Electronic Console;13;12;120.9;390",
        "2341;Depth/Pressure Gauge;226;225;48.3;105",
        "2343;Personal Dive Sonar;46;45;72.85;235",
        "2350;Compass Console Mount;211;300;10.15;29"
            }; 

            String[][] dataSource
                = new String[data.Length][];
            for (int i = 0; i < data.Length; i++)
            {
                dataSource[i] = data[i].Split(';');
            }
[VB.NET]
	'add PDF title
	Dim brush1 As PdfBrush = PdfBrushes.Black
	Dim font1 As New PdfTrueTypeFont(New Font("Verdana", 14F, System.Drawing.FontStyle.Bold))
	Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
	page.Canvas.DrawString("Part Sales Information", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1)
	y = y + font1.MeasureString("Part Sales Information", format1).Height
	y = y + 10

	'add data information
	Dim data As [String]() = {"PartNo;Description;OnHand;OnOrder;Cost;ListPrice", 
"900;Dive kayak;24;16;1356.75;3999.95", 
"912;Underwater Diver Vehicle;5;3;504;1680",
       "1313;Regulator System;165;216;117.5;250", 
       "1314;Second Stage Regulator;98;88;124.1;365", 
       "1316;Regulator System;75;70;119.35;341",
       "1320;Second Stage Regulator;37;35;73.53;171",
       "1328;Regulator System;166;100;154.8;430", 
       "1330;Alternate Inflation Regulator;47;43;85.8;260",
       "1364;Second Stage Regulator;128;135;99.9;270",
       "1390;First Stage Regulator;146;140;64.6;170", 
       "1946;Second Stage Regulator;13;10;95.79;309",
       "1986;Depth/Pressure Gauge Console;25;24;73.32;188", 
       "2314;Electronic Console;13;12;120.9;390",
       "2341;Depth/Pressure Gauge;226;225;48.3;105", 
       "2343;Personal Dive Sonar;46;45;72.85;235", 
       "2350;Compass Console Mount;211;300;10.15;29"}

	Dim dataSource As [String]()() = New [String](data.Length - 1)() {}
	For i As Integer = 0 To data.Length - 1
		dataSource(i) = data(i).Split(";"C)
	Next

Set PDF table style and data format

[C#]
            //Set table header
            PdfTable table = new PdfTable();
            table.Style.CellPadding = 3;
            table.Style.HeaderSource = PdfHeaderSource.Rows;
            table.Style.HeaderRowCount = 1;
            table.DataSource = dataSource;
            table.Style.ShowHeader = true;

            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.LightSeaGreen;
            table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Verdana", 9f, System.Drawing.FontStyle.Bold));
            table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            table.Style.HeaderStyle.TextBrush = PdfBrushes.White;

            //Set table style and data format
            table.Style.BorderPen = new PdfPen(PdfBrushes.LightBlue, 0.5f);
            table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.LightYellow;
            table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Verdana", 8.5f));
            table.Style.AlternateStyle = new PdfCellStyle();
            table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.AliceBlue;
            table.Style.AlternateStyle.Font = new PdfTrueTypeFont(new Font("Verdana", 8.5f));

            float width
                = page.Canvas.ClientSize.Width
                - (table.Columns.Count + 1) * table.Style.BorderPen.Width;
            table.Columns[0].Width = width * 0.1f * width;
            table.Columns[0].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
         
            table.Columns[1].Width = width * 0.28f * width;
            table.Columns[1].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[2].Width = width * 0.1f * width;
            table.Columns[2].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[3].Width = width * 0.1f * width;
            table.Columns[3].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[4].Width = width * 0.12f * width;
            table.Columns[4].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[5].Width = width * 0.12f * width;
            table.Columns[5].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);

            PdfLayoutResult result = table.Draw(page, new PointF(0, y));
[VB.NET]
	'Set table header
	Dim table As New PdfTable()
	table.Style.CellPadding = 3
	table.Style.HeaderSource = PdfHeaderSource.Rows
	table.Style.HeaderRowCount = 1
	table.DataSource = dataSource
	table.Style.ShowHeader = True

	table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.LightSeaGreen
	table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("Verdana", 9F, System.Drawing.FontStyle.Bold))
	table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
	table.Style.HeaderStyle.TextBrush = PdfBrushes.White

	'Set table style and data format
	table.Style.BorderPen = New PdfPen(PdfBrushes.LightBlue, 0.5F)
	table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.LightYellow
	table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("Verdana", 8.5F))
	table.Style.AlternateStyle = New PdfCellStyle()
	table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.AliceBlue
	table.Style.AlternateStyle.Font = New PdfTrueTypeFont(New Font("Verdana", 8.5F))

	Dim width As Single = page.Canvas.ClientSize.Width - (table.Columns.Count + 1) * table.Style.BorderPen.Width
	table.Columns(0).Width = width * 0.1F * width
	table.Columns(0).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)

	table.Columns(1).Width = width * 0.28F * width
	table.Columns(1).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
	table.Columns(2).Width = width * 0.1F * width
	table.Columns(2).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
	table.Columns(3).Width = width * 0.1F * width
	table.Columns(3).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
	table.Columns(4).Width = width * 0.12F * width
	table.Columns(4).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
	table.Columns(5).Width = width * 0.12F * width
	table.Columns(5).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)

	Dim result As PdfLayoutResult = table.Draw(page, New PointF(0, y))

Step 4: Save and Launch

[C#]
            // save and launch the file
            doc.SaveToFile("SimpleTable.pdf");
            doc.Close();
            System.Diagnostics.Process.Start("SimpleTable.pdf");
[VB.NET]
	' save and launch the file
	doc.SaveToFile("SimpleTable.pdf")
	doc.Close()
	System.Diagnostics.Process.Start("SimpleTable.pdf")

Effective Screeshot:

Generate PDF Table

There are two types of hyperlinks: one is URL type, which linked to any web protocol; the other is file path type, which usually point to a file in a folder. Before we have discussed how to manage URL hyperlinks in Excel via C#/VB.NET, thus this section will demonstrate how to manage Excel hyperlinks, which target at a file path.

Spire.Xls for .NET provides Hyperlink type property in its class design, which makes the operation related to Excel hyperlinks in C#/VB.NET quite simple and smooth for developers and programmers.

Spire.XLS for .NET is always welcome to any kind of trial and evaluation. So now please feel free to download Spire.Xls for .NET. And then follow our guide to add Excel hyperlinks in C#/VB.NET or try other function of Spire.Xls for .NET.

Step 1: Create new project and add reference

In this step, we create a new project and add spire.xls dll as its reference. The following operations relate to Excel hyperlinks are all preceded within this project.

Step 2: Import namespace

Spire.Xls is a namespace which must be used during our procedure of adding Excel hyperlinks via C#/VB.NET, so please use the code below to import it.

[C#]
using Spire.Xls;
[VB.NET]
Imports Spire.Xls

Step 3: Add an Excel hyperlink to a cell

In this step, we will load an Excel file from a folder and then add a hyperlink to a cell in C#/VB.NET. This hyperlink will link to a Excel file by setting its type. Have a check of the code sample.

[C#]
//load Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"..\..\hyperlink.xlsx", ExcelVersion.Version2010);
// add hyperlink and make setting 
Worksheet sheet1 = workbook.Worksheets[0];
CellRange range = sheet1.Range["C3"];
HyperLink hyperlink1 = sheet1.HyperLinks.Add(range);
hyperlink1.Type = HyperLinkType.File;
hyperlink1.TextToDisplay = "This is a hyperlink to a target file”
hyperlink1.Address = "employee2.xlsx";
[VB.NET]
'load Excel file
Dim workbook As New Workbook()
workbook.LoadFromFile("..\..\hyperlink.xlsx", ExcelVersion.Version2010)
' add hyperlink
Dim sheet1 As Worksheet = workbook.Worksheets(0)
Dim range As CellRange = sheet1.Range("C3")
Dim hyperlink1 As HyperLink = sheet1.HyperLinks.Add(range)
hyperlink1.Type = HyperLinkType.File
hyperlink1.TextToDisplay = "This is a hyperlink"
hyperlink1.Address = "employee2.xlsx"

Finally, we can save our work and run it to preview the effect. The effect before we add Excel hyperlink in C#/VB.NET:

Add Excel Hyperlink to a File

The effect after we add Excel hyperlink in C#/VB.NET:

Add Excel Hyperlink to a File

You can see a hyperlink has been added in Excel, and if you click on the hyperlink, it will lead you to a new Excel file named employee2.xlsx.

Footnote is one kind of annotations to explain one word or sentence in contents. It is often put on the bottom of one page. Because of footnote, users can learn some complicated words more clearly and the completeness can be preserved.

So, this guide will show how to add footnote in a Word document with C#/VB.NET by using Spire.Doc for .NET.

Friendly Reminder: Make Sure Spire.Doc and Visual Studio are correctly installed on system.

Step 1: Declare a new document and use document.LoadFromFile() to get Word document which you want to add footnote. Then, get the second paragraph for which the footnote will be given from the first section.

[C#]
            Document document = new Document();
            document.LoadFromFile(@"E:\work\documents\Antarctic.docx");
            Section section = document.Sections[0];
            Paragraph paragraph = section.Paragraphs[1];
[VB.NET]
            Dim document As New Document()
            document.LoadFromFile("E:\work\documents\Antarctic.docx")
            Dim section As Section = document.Sections(0)
            Dim paragraph As Paragraph = section.Paragraphs(1)

Step 2: Use paragraph.AppendFootnote() method to add footnote. The parameter passed to this method is FootnotType. Then, add footnote contents by using footnote.TextBody.AddParagraph().AppendText() method. Finally, set contents format, including font style, size and color.

[C#]
            Footnote footnote=paragraph.AppendFootnote(FootnoteType.Footnote);
            TextRange text = footnote.TextBody.AddParagraph().AppendText("Check Wiki to get more information");
            text.CharacterFormat.FontName = "Arial Black";
            text.CharacterFormat.FontSize = 12;
            text.CharacterFormat.TextColor = Color.SlateGray;
[VB.NET]
            Dim footnote As Footnote = paragraph.AppendFootnote(FootnoteType.Footnote)
            Dim text As TextRange = footnote.TextBody.AddParagraph().AppendText("Check Wiki to get more information")
            text.CharacterFormat.FontName = "Arial Black"
            text.CharacterFormat.FontSize = 12
            text.CharacterFormat.TextColor = Color.SlateGray

Step 3: As is known, there is a marker to be shown on the location where you want to add footnote. So this step is used to set marker format. Assign values for footnote.MarkerCharacterFormat.FontName/Fontsize/Bold/TextColor.

[C#]
            footnote.MarkerCharacterFormat.FontName = "Calibri";
            footnote.MarkerCharacterFormat.FontSize = 15;
            footnote.MarkerCharacterFormat.Bold = true;
            footnote.MarkerCharacterFormat.TextColor = Color.DarkCyan;
[VB.NET]
            footnote.MarkerCharacterFormat.FontName = "Calibri"
            footnote.MarkerCharacterFormat.FontSize = 15
            footnote.MarkerCharacterFormat.Bold = True
            footnote.MarkerCharacterFormat.TextColor = Color.DarkCyan

Step 4: Save this document by using document.SaveToFile() method. There are two parameters passed: file name string and file format. Then, launch this file for viewing.

[C#]
            document.SaveToFile("FootNote.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("FootNote.docx");
[VB.NET]
            document.SaveToFile("FootNote.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("FootNote.docx")

Insert Word Footnote

Insert Word Footnote

Spire.Doc is an MS Word component which enables user to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document for .NET. Click to learn more

Thursday, 14 June 2012 01:56

Export Data from Database to Excel in WPF

This section will introduce a solution to export data from database to Excel for WPF. The whole solution is easily performed by this WPF Excel component Spire.XLS for WPF.

database to excel

In the task of database to Excel, first we need to connect with database by this class provided by Microsoft: System.Data.Oledb.OledbConnection. Here we use an MS access database. Then, OleDbCommand can help us specify a datatable from database in order to save the data in Dataset later. Finally fill the data into dataset table. After all the connection, we can see the key source code provided by Spire.XLS to export data columns from datatable to Excel: Spire.Xls.Worksheet.InsertDataTable(System.Data.DataTable dataTable, bool columnHeaders, int firstRow, int firstColumn).

There are four parameters passed.

  • dataTable: The first parameter is to export the data column;
  • columnHeaders: the second is to indicate whether to import field names;
  • firstRow, firstColumn: the third and fourth parameters are index of first row and first column.

Here we can download Spire.XLS for WPF. After installing it on system, and start our database to excel task as below code:

[C#]
//export datatable to excel
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];
sheet.InsertDataTable(t, true, 1, 1);
book.SaveToFile("insertTableToExcel.xls");
System.Diagnostics.Process.Start("insertTableToExcel.xls");
[VB.NET]
//export datatable to excel
Dim book As New Workbook()
Dim sheet As Worksheet = book.Worksheets(0)
sheet.InsertDataTable(t, True, 1, 1)
book.SaveToFile("insertTableToExcel.xls")
System.Diagnostics.Process.Start("insertTableToExcel.xls")
End Sub
End Class
End Namespace

In people's daily life, we can open a PDF document by right clicking the open option as well as using C#, VB.NET or other programming languages. Both methods are available as long as you have a PDF Document, but for PDF itself, it has no viewing function, thus, we need to use PDF Viewer to help us view it. This article is designed to open a PDF Document with C#, VB.NET via PDF Viewer by two methods.

Spire. PDFViewer is designed for viewing PDF files from .NET application. It does NOT require Adobe Read or any other 3rd party software/library installed on system. By using Spire.PDFViewer, we can do this job easily. Please just follow the below procedure.

Step 1: Create a new project

  • Freely Download Spire.PDFViewer
  • Create a new project in Visual Studio and add a toolScript in Form1
  • Set its target Framework to be .NET Framework 4
  • Add Spire.PdfViewer. Forms as reference in Project. And add using at the top of the method. Please see below:
[C#]
using System.IO; 
using Spire.PdfViewer.Forms;
[VB.NET]
Imports Sytem. IO
Imports Spire.PdfViewer.Forms

Step 2: Open a PDF Document with C#, VB.NET via Spire.PDFViewer

Method one: This method is to directly load a PDF file from system, then open it.

[C#]
        public partial class Form1 : Form
    {
       
        public Form1()
        {
            InitializeComponent();
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
         
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            string pdfDoc = @"D:\michelle\e-iceblue\Spire.Office.pdf";
            if (File.Exists(pdfDoc))
            {
                this.pdfDocumentViewer1.LoadFromFile(pdfDoc);
            }

        }
    }
 }
[VB.NET]
Public Partial Class Form1
		Inherits Form

		Public Sub New()

			InitializeComponent()
		End Sub

		Private Sub Form1_Load(sender As Object, e As EventArgs)

		End Sub

		Private Sub toolStripButton1_Click(sender As Object, e As EventArgs)
			Dim pdfDoc As String = "D:\michelle\e-iceblue\Spire.Office.pdf"
			If File.Exists(pdfDoc) Then
				Me.pdfDocumentViewer1.LoadFromFile(pdfDoc)
			End If

		End Sub
	End Class
End Namespace

Method Two: This method allows you to choose the PDF file you want to open in a dialog box from your computer.

[C#]
public partial class Form1 : Form
 {
       
        public Form1()
        {
            InitializeComponent();
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
         
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "PDF document (*.pdf)|*.pdf";
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    string pdfFile = dialog.FileName;
                    this.pdfDocumentViewer1.LoadFromFile(pdfFile);
                }
                catch (Exception exe)
                {
                    MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }

        }
   }
[VB.NET]
Public Partial Class Form1
	Inherits Form

	Public Sub New()

		InitializeComponent()
	End Sub

	Private Sub Form1_Load(sender As Object, e As EventArgs)

	End Sub

	Private Sub toolStripButton1_Click(sender As Object, e As EventArgs)
		Dim dialog As New OpenFileDialog()
		dialog.Filter = "PDF document (*.pdf)|*.pdf"
		Dim result As DialogResult = dialog.ShowDialog()
		If result = DialogResult.OK Then
			Try
				Dim pdfFile As String = dialog.FileName
				Me.pdfDocumentViewer1.LoadFromFile(pdfFile)
			Catch exe As Exception
				MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.[Error])

			End Try
		End If

	End Sub
End Class

Step 3: Launch the file

Press F5, you can see Form1 display itself as picture below:

Then click "open" in the Form. When you use method one, you can see the PDF document content shows in the Form1. Also you can set the size of the form according to your own preference. When you use method two, you can choose the PDF Document by yourself in a dialog box. And then preview it in Form1.

Note: I set the default name of toolScript to be "open".

Effective Screenshot:

Tuesday, 12 June 2012 08:25

Add Excel Worksheet in C#, VB.NET

It is as easy as ABC to add Excel worksheet in C#/VB.NET. In this section, we will demonstrate multiple choices to easily add Excel worksheet in C#/VB.NET by using Spire.Xls for .NET

Spire.Xls for .NET provides a class-Workbook that represents an Excel file. Workbook class contains an Excel worksheet collection that allows accessing each worksheet in the Excel workbook. A worksheet is represented by the Worksheet class. Worksheet class provides a wide range of properties and methods to manage a worksheet.

Spire.Xls for .NET is always welcome to any kind of trial and evaluation. So now please feel free to download Spire.Xls for .NET and then follow our guide to add Excel worksheet in C#/VB.NET or try other function of Spire.Xls for .NET.

Click Project → Add Reference → Browse → Choose the folder contains Spire.XLS for .NET → Bin → .NET 4.0 → Spire.XLS.dll. Next we will demonstrate the following choices for adding Excel worksheet.

Step 1: Add worksheets to a new Excel file

In this choice, we will create a new workbook and then add Excel worksheet to it. Please check the code examples below.
[C#]
using Spire.Xls;
namespace add_worksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();            
            workbook.Worksheets.Add("Sample of New Excel");
            workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);
            System.Diagnostics.Process.Start("Sample.xls");
        }
    }
}
[VB.NET]
Imports Spire.Xls
Namespace add_worksheet
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.Worksheets.Add("Sample of New Excel")
			workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003)
			System.Diagnostics.Process.Start("Sample.xls")
		End Sub
	End Class
End Namespace

Adding Excel worksheet to new Excel file:

Add Excel Worksheet

Step 2: Add worksheet to designer spreadsheets

The process of adding worksheets to a designer spreadsheet is entirely the same as that of the above approach except that the Excel file is already created and we need to load that Excel file first before adding worksheet to it. A designer spreadsheet can be loaded with Spire.Xls for .NET. Please check the following code examples.

[C#]
using Spire.Xls;
namespace add_worksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"..\test.xls");
            workbook.Worksheets.Add("Sample of Designer Excel");
            workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);
            System.Diagnostics.Process.Start("Sample.xls");
        }
    }
}
[VB.NET]
Imports Spire.Xls
Namespace add_worksheet
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("..\test.xls")
			workbook.Worksheets.Add("Sample of Designer Excel")
			workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003)
			System.Diagnostics.Process.Start("Sample.xls")
		End Sub
	End Class
End Namespace

Adding Excel worksheet to designer Excel file:

Add Excel Worksheet

Step 3: Create multiple worksheet at one time

Spire.Xls for .NET also holds the ability to create multiple Excel worksheet at one time by calling the method of CreateEmptySheets(int sheetCount). Please check the code samples for that.

[C#]
using Spire.Xls;
namespace add_worksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.CreateEmptySheets(6);
            workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);
            System.Diagnostics.Process.Start("Sample.xls");
        }
    }
}
[VB.NET]
Imports Spire.Xls
Namespace add_worksheet
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.CreateEmptySheets(6)
			workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003)
			System.Diagnostics.Process.Start("Sample.xls")
		End Sub
	End Class
End Namespace

Adding multiple Excel worksheets to Excel file:

Add Excel Worksheet

It is a little bothered to find specified text, phrase or sentence in a Word document with a large amount of contents. Therefore, the function, which enables users to find text in Word document quickly, is import and necessary. What's more, the found texts will be highlighted with a background color so that users can confirm the location more conveniently.

Spire.Doc for .NET, a professional .NET Word component, enables developers to find and highlight text in Word on their .NET applications. This guide focuses on showing the solution to find and highlight text in Word by using C#, VB.NET. Please have a look at the following screenshot, which presents the result you can get.

Find and Highlight Word Text

Download and install Spire.Doc for .NET. Load document which you want to find and highlight text. Then, invoke document.FindAllString(string, bool caseSensitive, bool wholeWord) method to find text “forming” in document. Next, save the found string in a TextSelection array. Use foreach sentence to set HighlightColor property for each selection in TextSelection array. Code as following

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

namespace WordImage
{
    class ImageinWord
    {
        static void Main(string[] args)
        {
            //Create Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\References.docx");

            TextSelection[] text = document.FindAllString("forming", false, true);
            foreach (TextSelection seletion in text)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            document.SaveToFile("FindHighlight.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("FindHighlight.docx");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordImage
    Friend Class ImageinWord
        Shared Sub Main(ByVal args() As String)
            'Create Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\References.docx")

            Dim text() As TextSelection = document.FindAllString("forming", False, True)
            For Each seletion As TextSelection In text
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow
            Next seletion

            document.SaveToFile("FindHighlight.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("FindHighlight.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, a stand-alone Word component, which enables users to perform a wide range of Word document processing tasks with a fast speed such as generate, read, write and modify Word document in WPF, .NET and Silverlight without MS Word automation.

Word Heading can be taken as title of each part in Word document. This guide demonstrates solution to manage these Word headings and form them as a catalogue in C# and VB.NET.

In Word document, users can set some contents, for example, phrases of summary of the following paragraphs, as headings. These Word headings can be displayed in the first page of whole document and form as catalogue after arrangement so that readers can get outline of whole document. Solution in this guide presents how to manage Word headings with numbered style in a new created document in C# and VB.NET via Spire.Doc for .NET and screenshot below shows results of managing Word headings.

Word Paragraph Headings

Heading is one of kind of styles for paragraphs and Spire.Doc for .NET provides several BuiltinStyle types for paragraphs. In this example, three BuiltinStyle types will be applied: Heading1, Heading2 and Heading3. Following, details will be presented step by step.

Firstly, initialize a Document instance and add section, paragraph for this instance. Secondly, invoke AppendText method with parameter string text and ApplyStyle(BuiltinStyle.Heading1) method of Paragraph class to add text and set heading style for new added paragraph. Then, invoke ListFromat.ApplyNumberedStyle() method of Paragraph class to set number list for it. Thirdly, add new paragraph and set Heading2 style for it as the previous step. Initialize a ListStyle instance for document with Numbered ListType. Then, initialize a ListLevel instance from ListStyle and set UsePrevLevelPattern and NumberPrefix properties for this instance. After that, invoke ListStyleCollection.Add(ListStyle) method of Document class and ListFormat.ApplyStyle method of Paragraph class with parameter string styleName to add ListStyle for Heading2. Fourthly, add a new paragraph and set BuiltinStyle as Heading3 and apply ListStyle for this paragraph as the previous step. Finally, invoke SaveToFile method of Document class with parameter string fileName and FileFormat to save this document. Refer the code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordHeading
{
    class Heading
    {
        static void Main(string[] args)
        {
            //Create Document
            Document document = new Document();
            Section section = document.AddSection();
            Paragraph paragraph
                = section.Paragraphs.Count > 0 ? section.Paragraphs[0] : section.AddParagraph();

            //Add Heading 1
            paragraph = section.AddParagraph();
            paragraph.AppendText(BuiltinStyle.Heading1.ToString());
            paragraph.ApplyStyle(BuiltinStyle.Heading1);
            paragraph.ListFormat.ApplyNumberedStyle();

            //Add Heading 2
            paragraph = section.AddParagraph();
            paragraph.AppendText(BuiltinStyle.Heading2.ToString());
            paragraph.ApplyStyle(BuiltinStyle.Heading2);

            //List Style for Headings 2
            ListStyle listSty2 = new ListStyle(document, ListType.Numbered);
            foreach (ListLevel listLev in listSty2.Levels)
            {
                listLev.UsePrevLevelPattern = true;
                listLev.NumberPrefix = "1.";
            }
            listSty2.Name = "MyStyle2";
            document.ListStyles.Add(listSty2);
            paragraph.ListFormat.ApplyStyle(listSty2.Name);
            
            //Add List Style 3
            ListStyle listSty3 = new ListStyle(document, ListType.Numbered);
            foreach (ListLevel listLev in listSty3.Levels)
            {
                listLev.UsePrevLevelPattern = true;
                listLev.NumberPrefix = "1.1.";
            }
            listSty3.Name = "MyStyle3";
            document.ListStyles.Add(listSty3);

            //Add Heading 3
            for (int i = 0; i < 4; i++)
            {
                paragraph = section.AddParagraph();

                //Append Text
                paragraph.AppendText(BuiltinStyle.Heading3.ToString());

                //Apply List Style 3 for Heading 3
                paragraph.ApplyStyle(BuiltinStyle.Heading3);
                paragraph.ListFormat.ApplyStyle(listSty3.Name);
            }

            //Save and Launch
            document.SaveToFile("Word Headings.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Word Headings.docx");   
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordHeading
    Friend Class Heading
        Shared Sub Main(ByVal args() As String)
            'Create Document
            Dim document As New Document()
            Dim section As Section = document.AddSection()
            Dim paragraph As Paragraph = If(section.Paragraphs.Count > 0, section.Paragraphs(0), section.AddParagraph())

            'Add Heading 1
            paragraph = section.AddParagraph()
            paragraph.AppendText(BuiltinStyle.Heading1.ToString())
            paragraph.ApplyStyle(BuiltinStyle.Heading1)
            paragraph.ListFormat.ApplyNumberedStyle()

            'Add Heading 2
            paragraph = section.AddParagraph()
            paragraph.AppendText(BuiltinStyle.Heading2.ToString())
            paragraph.ApplyStyle(BuiltinStyle.Heading2)

            'List Style for Headings 2
            Dim listSty2 As New ListStyle(document, ListType.Numbered)
            For Each listLev As ListLevel In listSty2.Levels
                listLev.UsePrevLevelPattern = True
                listLev.NumberPrefix = "1."
            Next listLev
            listSty2.Name = "MyStyle2"
            document.ListStyles.Add(listSty2)
            paragraph.ListFormat.ApplyStyle(listSty2.Name)

            'Add List Style 3
            Dim listSty3 As New ListStyle(document, ListType.Numbered)
            For Each listLev As ListLevel In listSty3.Levels
                listLev.UsePrevLevelPattern = True
                listLev.NumberPrefix = "1.1."
            Next listLev
            listSty3.Name = "MyStyle3"
            document.ListStyles.Add(listSty3)

            'Add Heading 3
            For i As Integer = 0 To 3
                paragraph = section.AddParagraph()

                'Append Text
                paragraph.AppendText(BuiltinStyle.Heading3.ToString())

                'Apply List Style 3 for Heading 3
                paragraph.ApplyStyle(BuiltinStyle.Heading3)
                paragraph.ListFormat.ApplyStyle(listSty3.Name)
            Next i

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

Spire.Doc, as professional Word component, is very powerful on fast generating, loading, writing, modifying and saving Word documents in .NET, WPF, Silverlight without Word automation and any third party tools.

Tuesday, 12 June 2012 06:13

PDF Properties Setting in C#, VB.NET

PDF Properties demonstrate a summary of one document, including Description, Security, Fonts, Custom and Advance. Users can set part of description according to document contents. This guide introduces a solution to set PDF properties in C# and VB.NET via Spire.PDF for .NET. The following screenshot shows result after setting properties.

Set PDF Properties

Spire.PDF for .NET, professional .NET PDF component, provides a DocumentInformation class. Users can set PDF properties through setting properties of this class. In this example, the set PDF properties include Author, Title, Producer and Keywords. So, assign appropriate values (string) for these properties according to document contents to set document properties. Download and install Spire.PDF for .NET and follow the code.

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

namespace PDFProperties
{
    class Properties
    {
        static void Main(string[] args)
        {
            PdfDocument document = new PdfDocument();
            document.LoadFromFile(@"E:\Work\Documents\PDF\Spire.PDF for .NET.pdf");

            document.DocumentInformation.Author = "E-iceblue";
            document.DocumentInformation.Title = "Spire.PDF for .NET Introduction";
            document.DocumentInformation.Producer = "Spire.PDF";
            document.DocumentInformation.Keywords = ".NET PDF, Spire.PDF for .NET";

            document.SaveToFile("properties.pdf");
            System.Diagnostics.Process.Start("properties.pdf");
        }
    }
}
[VB.NET]
Imports System
Imports Spire.Pdf

Namespace PDFProperties
    Friend Class Properties
        Shared Sub Main(ByVal args() As String)
            Dim document As New PdfDocument()
            document.LoadFromFile("E:\Work\Documents\PDF\Spire.PDF for .NET.pdf")

            document.DocumentInformation.Author = "E-iceblue"
            document.DocumentInformation.Title = "Spire.PDF for .NET Introduction"
            document.DocumentInformation.Producer = "Spire.PDF"
            document.DocumentInformation.Keywords = ".NET PDF, Spire.PDF for .NET"

            document.SaveToFile("properties.pdf")
            System.Diagnostics.Process.Start("properties.pdf")
        End Sub
    End Class
End Namespace

Spire.PDF, an easy-to-use PDF component, enables developers/programmers to generate, draw, modify and save PDF document for their .NET, Silverlight and WPF applications with C# and VB.NET.

Tuesday, 12 June 2012 05:59

How to Draw PDF Table in C#, VB.NET

PDF table is one of the best ways to display data information. Using it, all the data can be quickly and clearly read. This section will introduce a solution to draw PDF table via a .NET PDF component in C#, VB.NET.

Using Spire.PDF for .NET (a .NET PDF library for manipulating PDF files), you can draw PDF table through two simple steps. One is to draw all the data by a string array. Another step is to split these string array by string[] Split(params char[] separator); Thus, a PDF table has been drawn. From below picture, you can see the effect of the task:

Here, you can download Spire.PDF for .NET and install it on your system. After adding the Spire.Pdf dll from your Bin folder, you can follow below key code to draw your PDF table in C#, VB.NET.

[C#]
  //Create a pdf document.
        PdfDocument doc = new PdfDocument();
        PdfSection sec = doc.Sections.Add();
        sec.PageSettings.Width = PdfPageSize.A4.Width;
        PdfPageBase page = sec.Pages.Add();
        float y = 10;
        //title
        PdfBrush brush1 = PdfBrushes.Black;
        PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
        PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
        page.Canvas.DrawString("Part Sales Information", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
        y = y + font1.MeasureString("Country List", format1).Height;
        y = y + 5;

        String[] data
     = {
     "PartNo;Description;OnHand;OnOrder;Cost;ListPrice",
     "900;Dive kayak;24;16;1356.75;3999.95",
     "912;Underwater Diver Vehicle;5;3;504;1680",
     "1313;Regulator System;165;216;117.5;250",
     "1314;Second Stage Regulator;98;88;124.1;365",
     "1316;Regulator System;75;70;119.35;341",
     "1320;Second Stage Regulator;37;35;73.53;171",
     "1328;Regulator System;166;100;154.8;430",
     "1330;Alternate Inflation Regulator;47;43;85.8;260",
     "1364;Second Stage Regulator;128;135;99.9;270",
     "1390;First Stage Regulator;146;140;64.6;170",
     "1946;Second Stage Regulator;13;10;95.79;309",
     "1986;Depth/Pressure Gauge Console;25;24;73.32;188",
     "2314;Electronic Console;13;12;120.9;390",
     "2341;Depth/Pressure Gauge;226;225;48.3;105",
     "2343;Personal Dive Sonar;46;45;72.85;235",
     "2350;Compass Console Mount;211;300;10.15;29"
         };
        String[][] dataSource
            = new String[data.Length][];
        for (int i = 0; i < data.Length; i++)
        {
            dataSource[i] = data[i].Split(';');
        }

        PdfTable table = new PdfTable();
        table.Style.CellPadding = 2;
        table.Style.BorderPen = new PdfPen(brush1, 0.75f);
        table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
        table.Style.HeaderSource = PdfHeaderSource.Rows;
        table.Style.HeaderRowCount = 1;
        table.Style.ShowHeader = true;
        table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue;
        table.DataSource = dataSource;
        foreach(PdfColumn column in table.Columns)
        {
            column.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
        }
        table.Draw(page, new PointF(0, y));

        doc.SaveToFile("SimpleTable.pdf");
[VB.NET]
 'Create a pdf document.
        Dim doc As New PdfDocument()
        Dim sec As PdfSection = doc.Sections.Add()
        sec.PageSettings.Width = PdfPageSize.A4.Width
        Dim page As PdfPageBase = sec.Pages.Add()
        Dim y As Single = 10
        'title
        Dim brush1 As PdfBrush = PdfBrushes.Black
        Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold))
        Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
        page.Canvas.DrawString("Part Sales Information", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1)
        y = y + font1.MeasureString("Country List", format1).Height
        y = y + 5

        Dim data As [String]() = {
        "PartNo;Description;OnHand;OnOrder;Cost;ListPrice",
        "900;Dive kayak;24;16;1356.75;3999.95",
        "912;Underwater Diver Vehicle;5;3;504;1680",
        "1313;Regulator System;165;216;117.5;250",
        "1314;Second Stage Regulator;98;88;124.1;365",
        "1316;Regulator System;75;70;119.35;341",
        "1320;Second Stage Regulator;37;35;73.53;171",
        "1328;Regulator System;166;100;154.8;430",
        "1330;Alternate Inflation Regulator;47;43;85.8;260",
        "1364;Second Stage Regulator;128;135;99.9;270",
        "1390;First Stage Regulator;146;140;64.6;170",
        "1946;Second Stage Regulator;13;10;95.79;309",
        "1986;Depth/Pressure Gauge Console;25;24;73.32;188",
        "2314;Electronic Console;13;12;120.9;390",
        "2341;Depth/Pressure Gauge;226;225;48.3;105",
        "2343;Personal Dive Sonar;46;45;72.85;235",
        "2350;Compass Console Mount;211;300;10.15;29"

        Dim dataSource As [String]()() = New [String](data.Length - 1)() {}
        For i As Integer = 0 To data.Length - 1
            dataSource(i) = data(i).Split(";"c)
        Next

        Dim table As New PdfTable()
        table.Style.CellPadding = 2
        table.Style.BorderPen = New PdfPen(brush1, 0.75F)
        table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
        table.Style.HeaderSource = PdfHeaderSource.Rows
        table.Style.HeaderRowCount = 1
        table.Style.ShowHeader = True
        table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue
        table.DataSource = dataSource
        For Each column As PdfColumn In table.Columns
            column.StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
        Next
        table.Draw(page, New PointF(0, y))

        doc.SaveToFile("SimpleTable.pdf")

Spire.PDF for .NET is a professional .NET PDF component which enables you to create, edit and handle PDF files in C#, VB.NET.