Wednesday, 06 July 2022 08:28

C#/VB.NET: Create a Pivot Table in Excel

Pivot table is a kind of interactive table that is capable of quickly calculating, summarizing and analyzing large amounts of data. As one of the most powerful tools in Excel, it enables users to view static data from different perspectives, and also makes the comparisons between data more intuitive. In this article, you will learn how to programmatically create a pivot table in Excel using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Create a Pivot Table in Excel

The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[] property.
  • Select the data source range using Worksheet.Range[] property, and then create a PivotCache to save the data information using Workbook.PivotCaches.Add (CellRange) method.
  • Add a pivot table to the specified worksheet and set the location and cache of it using Worksheet.PivotTables.Add(String, CellRange, PivotCache) method.
  • Define row labels of the pivot table and then add fields to the data area to calculate data using PivotTable.DataFields.Add(IPivotField, String, SubtotalTypes) method.
  • Set the pivot table style using PivotTable.BuiltInStyle property.
  • Save the result document using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace createPivotTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

            //Load a sample Excel document
            workbook.LoadFromFile(@"E:\Files\sample.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Select the data source range
            CellRange dataRange = sheet.Range["B1:F11"];
            PivotCache cache = workbook.PivotCaches.Add(dataRange);

            //Add a PivotTable to the worksheet and set the location and cache of it
            PivotTable pt = sheet.PivotTables.Add("Pivot Table", sheet.Range["H3"], cache);

            //Define row labels
            PivotField r1 = pt.PivotFields["Country"] as PivotField;
            r1.Axis = AxisTypes.Row;
            pt.Options.RowHeaderCaption = "Country";

            PivotField r2 = pt.PivotFields["Product"] as PivotField;
            r2.Axis = AxisTypes.Row;

            //Add data fields to calculate data
            pt.DataFields.Add(pt.PivotFields["Quantity"], "SUM of Quantity", SubtotalTypes.Sum);
            pt.DataFields.Add(pt.PivotFields["Total Amount"], "SUM of Total Amount", SubtotalTypes.Sum);

            //Set pivot table style
            pt.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium10;

            //Save the document
            workbook.SaveToFile("CreatePivotTable.xlsx", ExcelVersion.Version2010);
    
        }
    }
}

C#/VB.NET: Create a Pivot Table in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Tuesday, 15 May 2012 02:07

Privacy Policy

This web site is maintained by E-iceblue Ltd. By accessing or using www.e-iceblue.com, you need to agree to terms of E-iceblue Online Privacy Policy, as outlined below. If you do not agree to these terms, please do not access or use this site.

Overview

E-iceblue has established this Onine Privacy Policy to help you understand how we intend to treat your Personal Information.

E-iceblue is committed to protecting your privacy. For accessing service from E-iceblue, we may ask for personal identification information (“Personal Information”), including your name (first and last), your e-mail address or some other contact information. The personal information can be provided by yourself or any other party. In general, you may visit our website without disclosing to us who you are and without revealing any Personal Information about yourself.

Also, you should be aware though, that if you choose to provide us with Personal Information, we may transfer such information, within E-iceblue or E-iceblue’s third party service providers, across borders and from your country or jurisdiction to other countries or jurisdictions around the world, subject to the limitations of this Privacy Policy.

E-iceblue Strives to comply with all applicable laws around the globe that are designed to protect your privacy. Although legal requirements may vary from country to country, E-iceblue intends to adhere to the principles set forth in this Online Privacy Policy.

Cookies and Other Tracking Technologies

When you visit www.e-iceblue.com, you may surf the site anonymously and access important information without revealing your identity. In order to analyze and improve our site, we use “cookies” to track your visit. A cookie is small amount of data that is transferred to your browser by a Web server and can only be read by the server that give it to you. “Cookies” cannot be executed as code or deliver viruses.

Most browsers are initially set to accept cookies. You can set your browser to notify you when you receive a cookie, therefore allowing you to decide whether or not to accept it. (For some Web pages that require an authorization, cookies are not optional. Users choosing not to accept cookies will not be able to access such pages.)

While E-iceblue uses cookies to track your visit to www.e-iceblue.com, and our Web servers automatically log the IP/Internet address of your computer. This information does not identify you personally and you remain anonymous unless you have otherwise provided e-iceblue with Personal Information.

Principles

The following principles we adopted to protect your privacy.

Choice

You may choose whether or not to provide Personal Information to E-iceblue. However, when you engage in certain activities on this site, such as ordering products, downloading software, or entering contests, E-iceblue may require that you provide certain information about yourself by filling out and submitting an online form. It is entirely optional for you to engage in these activities. If you elect to engage in these activities, E-iceblue may require that you provide certain personal information, such as your name, mailing address, e-mail address, and other personal identifying information.

Security

Wherever your Personal Information may be held by E-iceblue or a third party on E-iceblue’s behalf, reasonable and appropriate precautions, such as encryption, firewalls and like technologies, are and will be implemented to protect such Personal Information from loss, misuse or unauthorized access.

Access/Accuracy

To the extent that you do provide us with Personal Information, E-iceblue wishes to maintain it accurately and updated. Where we collect Personal Information from you, our goal is to provide a means of contacting E-iceblue should you need to access, update or correct that Information. If for any reason you desire to review such information, please contact us and we will make reasonable efforts to promptly provide you with such information. Further, if you notify us that such information is incorrect, or you wish to have such information removed, we will correct, amend, or delete your Personal Information as soon as practicable.

Third Party Services

In the interest of providing better service to its customers, E-iceblue is represented in the United States and in some foreign countries by authorized distributors and resellers who provide marketing, sales, and support services to E-iceblue customers. When you submit personal information to E-iceblue, you understand and agree that E-iceblue may allow E-iceblue’s authorized distributors and resellers access to your customer profile for the exclusive purpose of providing you with marketing, sales, and support services for E-iceblue products.

Your personal information will not be leased, sold, rented or otherwise made available to any other third party except to the extent necessary to comply with applicable laws, police investigations, or in legal proceedings where such information is relevant. Occasionally, E-iceblue allows access to database information to bonded mailing houses only for the purpose of allowing for the printing of mailing labels that are used for E-iceblue 's own direct mail and promotional purposes. In those instances, the third party is strictly bound by these terms.

Notwithstanding the foregoing, you hereby agree that E-iceblue may assign, sell, license, or otherwise transfer to a third party, your name, address, email address, member name and any other personal information in connection with an assignment, sale, joint venture, or other transfer or disposition of a material portion or essentially all of the assets or stock of E-iceblue or its affiliated entities.

Children's Privacy

www.e-iceblue.com is not designed nor structured to attract children. Accordingly, we do not intend to collect Personal Information from anyone we know to be under 13 years of age. If we are made aware that information is or has been submitted by or collected from a child under the age of thirteen, we will promptly delete this information.

Sensitive Information

We do not collect Sensitive Information such as medical, health, racial, ethnic, political, religious, philosophic, union membership or sexual orientation information. If we are made aware that we have received such information, we will promptly proceed to its deletion.

Notice

E-iceblue collects Personal Information on its Web site in order to record and support your participation in the activities you select. If you order a product, for example, the information is used to register your license and rights, if any, to ensure your eligibility to receive technical support, upgrade discounts, or other benefits that may be made available to registered users. If you enter a contest, information is collected to qualify the entry and contact you regarding the contest or prize awards. E-iceblue also uses information that you provide as part of our effort to keep you informed about the status of your subscription, product upgrades, special offers, and other E-iceblue products and services.

We will only collect Personal Information where it is relevant for the purposes for which we are collecting it. We will not process any Personal Information for any purposes that are incompatible with the purposes for which it has been collected or subsequently authorized by you.

Commitment

We, at E-iceblue, are committed to your right to privacy and we support current industry initiatives to preserve the integrity of individual privacy rights on the Internet. Protecting your privacy on-line is a rapidly evolving area, and E-iceblue's Web sites are continually evolving to meet these demands.

Your Consent

By using this Web site, you consent to the terms of our Online Privacy Policy and to E-iceblue's processing of Personal Information for the purposes outlined above. Should the Online Privacy Policy change, we will take reasonable steps to ensure that these changes are brought to your attention by posting all changes prominently on our Web site for a reasonable period of time.

Contact

If you have any comments or questions regarding our Online Privacy Policy, please contact us at comments@e-iceblue.com.

Tuesday, 15 May 2012 01:52

Renew Policy

Why Renew Subscription?

When you purchase a license from E-iceblue, you will get a full 1 year’s subscription software updates. We will send you an email to remind you if your subscription nears its subscription. However, without a subscription you can still use the product and get FREE support, but you are not allowed to get new features of hot fixes. If you have a problem that requires a hot fix but do not have a current subscription, you will have to renew before you can benefit from the fix.

When Should I Renew Subscription?

You can renew your subscription before its expiry date or after that. If your first time purchase is on September 12, the expiry date is on September 11 in the next year. We will send you an email to remind you around August 11.

What Does a Subscription Cost?

Renewing an existing subscription is cheaper than renewing an expired subscription. While your subscription is still running, adding a year to the subscription costs 60% of the current product price. To re-activate an expired subscription costs 75% of the current product price. Renewal adds twelve months to your subscription from the expiry date. However, if your expiry date is September 11, and you renew your license on October 10, then, the expiry data will be changed to October 9 in the next year.

How to Renew Subscription?

Log in to the purchase system with your account information. You can find the renewal discount coupon code in the purchase page. Use the coupon code to purchase the renewal. Leave a Note to offer us your registered license information including your email address, register name so that our technical support can send you renewal correctly.


If you bought the product from one of our resellers you can contact them when you need to renew your subscription. Our resellers can help you purchase a new subscription.

Contact Our Sales Team for other questions

Tuesday, 15 May 2012 01:34

License Upgrade

If you purchased the license of Spire.Doc Developer Subscription and a few days later you found you need Spire.Doc Developer OEM Subscription, you can ask to Upgrade Your License.

When Can I Upgrade License?

After you purchase our product and receive license, you can only upgrade your license during the first 3 months. After 3 months, you need purchase what you want. However, you can get 10% OFF discount as a return customer.

How Much I Should Pay?

When you upgrade license, you just need pay the price difference. For example, if you purchased Spire.Doc Pro Edition Developer Subscription ($799) on May 1, 2012 and you want to upgrade to Spire.Office Developer Subscription ($1899) on May 10, 2012, you just need pay $1100. And the register date will be May 10, 2012.

Can I Upgrade My Spire.PDF to Spire.Doc?

No, you can’t. You can convert Spire.PDF to Spire.Office. Or you can convert Spire.PDF Developer Subscription to Spire.PDF OEM Subscription, Spire.PDF Site Enterprise or Spire.PDF Site OEM.

How to Upgrade?

When you found you need upgrade your license, please send email to sales@e-iceblue.com. You need offer us the old license information (Product Name, License Registered Name, Purchasing Date, Purchasing email address and what product license you want to upgrade to). Then, we will generate upgrade coupon code for you.

If you need more help, please contact our sales team.

Word Page Border is one part of page background to beautify document appearance. Solution in this guide introduces how to insert and format Word page border in C# and VB.NET.

MS Word enables users to decorate Word pages to have a better layout or appearance. All the formats of page borders can be customized, including style, color, width, margin etc. This guide demonstrates how to add page borders for Word document and format them in C# and VB.NET via Spire.Doc for .NET. The following screenshot presents Word with page borders after programming.

Word Page Borders

Spire.Doc for .NET offers Section class to allow you to create new section instance or manipulate existing section. Borders is one property of PageSetup of Section class. You can directly set BorderType property of Borders to add page borders and set Color, Space of Left/Right properties to format borders. The border types Spire.Doc for .NET offers include None, Single, Thick, Double, Hairline, Dot, DashLargeGap, DotDash, DotDotDash, Triple, ThinkThickSmallGap, ThinThinSampllGap, ThinThickThinSamllGap, ThinThickMediumGap, ThickThinMediumGap, ThickThickThinMediumGap, ThinThickLargeGap, ThickThinLargeGap, ThinThickThinLargeGap, Wave, DoubleWave, DashSamllGap, DashDotStroker, Emboss3D, Engrave3D, Outset, Inset, TwistedLines1, Cleared. In this example, the border type is set as DoubleWave.

Download and install Spire.Doc for .NET and follow the code:

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

namespace WordBorder
{
    class PageBorders
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\Microsoft Word 2013 Preview.docx");
            Section section = document.Sections[0];

            //Add Page Borders with Special Style and Color
            section.PageSetup.Borders.BorderType = BorderStyle.DoubleWave;
            section.PageSetup.Borders.Color = Color.LightSeaGreen;
            //Space between Border and Text
            section.PageSetup.Borders.Left.Space = 50;
            section.PageSetup.Borders.Right.Space = 50;

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

Namespace WordBorder
    Friend Class PageBorders
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\Microsoft Word 2013 Preview.docx")
            Dim section As Section = document.Sections(0)

            'Add Page Borders with Special Style and Color
            section.PageSetup.Borders.BorderType = BorderStyle.DoubleWave
            section.PageSetup.Borders.Color = Color.LightSeaGreen
            'Space between Border and Text
            section.PageSetup.Borders.Left.Space = 50
            section.PageSetup.Borders.Right.Space = 50

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

Spire.Doc is a stand-alone component, enabling developers/programmers to generate, open, write, edit and save Word document in WPF, .NET and Silverlight without Microsoft Word installed on system.

Thursday, 26 April 2012 06:44

Remove Word Section in C#, VB.NET

In Word document, users can add new sections or remove existing sections. This guide demonstrates how to remove Word section in C# and VB.NET.

Section, important part to form a Word document, can be easily added and removed. In MS Word, users can operation section by section break, adding new section by inserting a break and deleting existing section by removing section break. In this guide, a solution will be presented to remove Word section in C# and VB.NET via Spire.Doc for .NET.

Spire.Doc for .NET enables developers to access SectionCollection property of Document class to get specified section in Word document and then remove the unnecessary one or more. There are two methods to remove Word section.

Remove one Specified Section

Invoke Remove(Spire.Doc.Interface.IDocumentObject entity) method to remove specified object of document. In this solution, entity is the first section of document which has gotten at first.

[C#]
            Section section = document.Sections[0];
            document.Sections.Remove(section);
[VB.NET]
            Dim section As Section = document.Sections(0)
            document.Sections.Remove(section)

Invoke RemoveAt(int index) method to remove document object at the specified index from the collection.

[C#]
            document.Sections.RemoveAt(0);
[VB.NET]
	    document.Sections.RemoveAt(0)

Remove All Sections

Invoke Clear() method to clear all objects of document.

[C#]
            document.Sections.Clear();
[VB.NET]
            document.Sections.Clear()

Note: Because a Word document must include at least one section, so the document cannot be saved if all the sections are removed.

Spire.Doc, the professional stand-alone component to manipulate MS Word document without automation, enables developers to generate, read, write, modify Word document on their .NET, WPF and Silverlight application.

Wednesday, 26 October 2022 06:12

C#/VB.NET: Create Tables in PDF

A table provides fast and efficient access to data displayed in rows and columns in a visually appealing manner. When presented in a table, data has a greater impact than when just used as words and enables readers to easily compare and understand relationships between them. In this article, you will learn how to create a table in PDF in C# and VB.NET using Spire.PDF for .NET.

Spire.PDF for .NET offers the PdfTable and the PdfGrid class to work with the tables in a PDF document. The PdfTable class is used to quickly create simple, regular tables without too much formatting, while the PdfGrid class is used to create more complex tables.

The table below lists the differences between these two classes.

PdfTable PdfGrid
Formatting
Row Can be set through events. No API support. Can be set through API.
Column Can be set through API (StringFormat). Can be set through API (StringFormat).
Cell Can be set through events. No API support. Can be set through API.
Others
Column span Not support. Can be set through API.
Row span Can be set through events. No API support. Can be set through API.
Nested table Can be set through events. No API support. Can be set through API.
Events BeginCellLayout,  EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. BeginPageLayout, EndPageLayout.

The following sections demonstrate how to create a table in PDF using the PdfTable class and the PdfGrid class, respectively.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Create a Table Using PdfTable Class

The following are the steps to create a table using the PdfTable class.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create a Pdftable object.
  • Set the table style through PdfTable.Style property.
  • Insert data to table through PdfTable.DataSource property.
  • Set row height and row color through BeginRowLayout event.
  • Draw table on the PDF page using PdfTable.Draw() method.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using System.Data;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;

namespace CreateTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(40));

            //Create a PdfTable object
            PdfTable table = new PdfTable();

            //Set font for header and the rest cells
            table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Times New Roman", 12f, FontStyle.Regular), true);
            table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Times New Roman", 12f, FontStyle.Bold), true);

            //Crate a DataTable
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("ID");
            dataTable.Columns.Add("Name");
            dataTable.Columns.Add("Department");
            dataTable.Columns.Add("Position");
            dataTable.Columns.Add("Level");
            dataTable.Rows.Add(new string[] { "1", "David", "IT", "Manager", "1" });
            dataTable.Rows.Add(new string[] { "3", "Julia", "HR", "Manager", "1" });
            dataTable.Rows.Add(new string[] { "4", "Sophie", "Marketing", "Manager", "1" });
            dataTable.Rows.Add(new string[] { "7", "Wickey", "Marketing", "Sales Rep", "2" });
            dataTable.Rows.Add(new string[] { "9", "Wayne", "HR", "HR Supervisor", "2" });
            dataTable.Rows.Add(new string[] { "11", "Mia", "Dev", "Developer", "2" });

            //Set the datatable as the data source of table
            table.DataSource = dataTable;

            //Show header(the header is hidden by default)
            table.Style.ShowHeader = true;

            //Set font color and backgroud color of header row
            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Gray;
            table.Style.HeaderStyle.TextBrush = PdfBrushes.White;

            //Set text alignment in header row
            table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);

            //Set text alignment in other cells
            for (int i = 0; i < table.Columns.Count; i++)
            {
                table.Columns[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            }

            //Register with BeginRowLayout event
            table.BeginRowLayout += Table_BeginRowLayout;

            //Draw table on the page
            table.Draw(page, new PointF(0, 30));

            //Save the document to a PDF file 
            doc.SaveToFile("PdfTable.pdf");
        }

        //Event handler
        private static void Table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
        {
            //Set row height
            args.MinimalHeight = 20f;

            //Alternate row color
            if (args.RowIndex < 0)
            {
                return;
            }
            if (args.RowIndex % 2 == 1)
            {
                args.CellStyle.BackgroundBrush = PdfBrushes.LightGray;
            }
            else
            {
                args.CellStyle.BackgroundBrush = PdfBrushes.White;
            }
        }
    }
}

C#/VB.NET: Create Tables in PDF

Create a Table Using PdfGrid Class

Below are the steps to create a table using the PdfGrid class.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create a PdfGrid object.
  • Set the table style through PdfGrid.Style property.
  • Add rows to the table using PdfGrid.Rows.Add() method.
  • Insert data to specific cells through PdfGridRow.Cells[index].Value property.
  • Span cells across columns or rows through PdfGridRow.RowSpan or PdfGridRow.ColumnSpan property.
  • Set the formatting of a specific cell through PdfGridRow.Cells[index].StringFormat and PdfGridRow.Cells[index].Style properties.
  • Draw table on the PDF page using PdfGrid.Draw() method.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
using System.Drawing;

namespace CreateGrid
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Add a page 
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4,new PdfMargins(40));

            //Create a PdfGrid
            PdfGrid grid = new PdfGrid();

            //Set cell padding
            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);

            //Set font
            grid.Style.Font = new PdfTrueTypeFont(new Font("Times New Roman", 13f, FontStyle.Regular), true);

            //Add rows
            PdfGridRow row1 = grid.Rows.Add();
            PdfGridRow row2 = grid.Rows.Add();
            PdfGridRow row3 = grid.Rows.Add();
            PdfGridRow row4 = grid.Rows.Add();
            grid.Columns.Add(4);

            //Set column width
            foreach (PdfGridColumn col in grid.Columns)
            {
                col.Width = 110f;
            }

            //Write data into specific cells
            row1.Cells[0].Value = "Order and Payment Status";
            row2.Cells[0].Value = "Order number";
            row2.Cells[1].Value = "Date";
            row2.Cells[2].Value = "Customer";
            row2.Cells[3].Value = "Paid or not";
            row3.Cells[0].Value = "00223";
            row3.Cells[1].Value = "2022/06/02";
            row3.Cells[2].Value = "Brick Lane Realty";
            row3.Cells[3].Value = "Yes";
            row4.Cells[0].Value = "00224";
            row4.Cells[1].Value = "2022/06/03";
            row4.Cells[3].Value = "No";

            //Span cell across columns
            row1.Cells[0].ColumnSpan = 4;

            //Span cell across rows
            row3.Cells[2].RowSpan = 2;

            //Set text alignment of specific cells
            row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            row3.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);

            //Set background color of specific cells
            row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Orange;
            row4.Cells[3].Style.BackgroundBrush = PdfBrushes.LightGray;

            //Format cell border
            PdfBorders borders = new PdfBorders();
            borders.All = new PdfPen(Color.Orange, 0.8f);
            foreach (PdfGridRow pgr in grid.Rows)
            {
                foreach (PdfGridCell pgc in pgr.Cells)
                {
                    pgc.Style.Borders = borders;
                }
            }

            //Draw table on the page
            grid.Draw(page, new PointF(0, 30));

            //Save the document to a PDF file
            doc.SaveToFile("PdfGrid.pdf");
        }
    }
}

C#/VB.NET: Create Tables in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Thursday, 18 August 2022 03:48

C#/VB.NET: Extract Text and Images from Word

When receiving or downloading a Word document from the Internet, you may sometimes need to extract content from the document for other purposes. In this article, you will learn how to programmatically extract text and images from a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Extract Text from a Word Document

Below are detailed steps on how to extract text from a Word document and save in a TXT file.

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Create a StringBuilder instance.
  • Get each paragraph of each section in the document.
  • Get the text of a specified paragraph using Paragraph.Text property, and then append the extracted text to the StringBuilder instance using StringBuilder.AppendLine() method.
  • Create a new txt file and write the extracted text to the file using File.WriteAllText() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Text;
using System.IO;

namespace ExtractTextfromWord
{
    class ExtractText
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();

            //Load a sample Word document 
            document.LoadFromFile("input.docx");

            //Create a StringBuilder instance
            StringBuilder sb = new StringBuilder();

            //Extract text from Word and save to StringBuilder instance
            foreach (Section section in document.Sections)
            {
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    sb.AppendLine(paragraph.Text);
                }
            }

            //Create a new txt file to save the extracted text
            File.WriteAllText("Extract.txt", sb.ToString());
        }
    }
}

C#/VB.NET: Extract Text and Images from Word

Extract Images from a Word Document

Below are detailed steps on how to extract all images from a Word document.

  • Create a Document instance and load a sample Word document.
  • Get each paragraph of each section in the document.
  • Get each document object of a specific paragraph.
  • Determine whether the document object type is picture. If yes, save the image out of the document using DocPicture.Image.Save(String, ImageFormat) method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;

namespace ExtractImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a Word document
            Document document = new Document("input.docx");
            int index = 0;

            //Get each section of document
            foreach (Section section in document.Sections)
            {
                //Get each paragraph of section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    //Get each document object of a specific paragraph
                    foreach (DocumentObject docObject in paragraph.ChildObjects)
                    {
                        //If the DocumentObjectType is picture, save it out of the document
                        if (docObject.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            DocPicture picture = docObject as DocPicture;
                            picture.Image.Save(string.Format("image_{0}.png", index), System.Drawing.Imaging.ImageFormat.Png);
                            index++;
                        }
                    }
                }
            }
        }
    }
}

C#/VB.NET: Extract Text and Images from Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Friday, 18 November 2022 08:37

C#/VB.NET: Insert Page Breaks in Excel

In Excel, a page break is a separator that divides a worksheet into several different pages/segments for the purpose of better printing. By inserting page breaks where necessary, you can avoid misalignment of data and ensure a desired print result, which is especially useful when working with a large data set. This article will demonstrate how to programmatically insert horizontal or vertical page breaks in Excel using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Insert Horizontal Page Breaks in an Excel Worksheet

A horizontal page break is inserted between a selected row and the row above it. After insertion, the selected row will become the top row of the new page. With Spire.XLS for .NET, developers are allowed to use the Worksheet.HPageBreaks.Add(CellRange) method to insert horizontal page breaks. The detailed steps are as follows.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Add horizontal page break to a specified cell range using Worksheet.HPageBreaks.Add(CellRange) method.
  • Set view mode to Preview mode using Worksheet.ViewMode property.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace EditExcelComment
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();

            //Load a sample Excel document
            workbook.LoadFromFile("input.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Set Excel page break horizontally
            sheet.HPageBreaks.Add(sheet.Range["A7"]);
            sheet.HPageBreaks.Add(sheet.Range["A18"]);

            //Set view mode to Preview mode
            sheet.ViewMode = ViewMode.Preview;

            //Save the result document
            workbook.SaveToFile("SetHorizontalPageBreak.xlsx");
        }
    }
}

C#/VB.NET: Insert Page Breaks in Excel

Insert Vertical Page Breaks in an Excel Worksheet

A vertical page break is inserted between a selected column and the column to its left. After insertion, the selected column will become the left most column of the new page. To insert vertical page breaks, developers can use the Worksheet.VPageBreaks.Add(CellRange) method offered by Spire.XLS for .NET offers. The detailed steps are as follows.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Add vertical page break to a specified cell range using Worksheet.VPageBreaks.Add(CellRange) method.
  • Set view mode to Preview mode using Worksheet.ViewMode property.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace EditExcelComment
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();

            //Load a sample Excel document
            workbook.LoadFromFile("input.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Set Excel page break vertically
            sheet.VPageBreaks.Add(sheet.Range["B1"]);

            //Set view mode to Preview mode
            sheet.ViewMode = ViewMode.Preview;

            //Save the result document
            workbook.SaveToFile("SetVerticalPageBreak.xlsx");
        }
    }
}

C#/VB.NET: Insert Page Breaks in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Thursday, 10 March 2022 06:15

C#/VB.NET: Convert HTML to Images

A common use of HTML is to display data and information on websites, web applications, and a variety of platforms. It is sometimes necessary to convert HTML to images like JPG, PNG, TIFF, BMP etc. since images are difficult to modify and can be accessed by virtually anyone. This article will show you how to perform the HTML to images conversion programmatically in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Convert HTML to Images

Spire.Doc for .NET offers the Document.SaveToImages() method to convert HTML to Images. Here are detailed steps.

  • Create a Document instance.
  • Load an HTML sample document using Document.LoadFromFile() method.
  • Save the document as an image using Document.SaveToImages() method.
  • C#
  • VB.NET
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing.Imaging;

namespace HTMLToImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document mydoc = new Document();
           
            //Load an HTML sample document
            mydoc.LoadFromFile(@"sample.html", FileFormat.Html, XHTMLValidationType.None);
           
            //Save to image. You can convert HTML to BMP, JPEG, PNG, GIF, Tiff etc
            Image image = mydoc.SaveToImages(0, ImageType.Bitmap);
            image.Save("HTMLToImage.png", ImageFormat.Png);
        }
    }
}

C#/VB.NET: Convert HTML to Images

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.