Knowledgebase (2311)
Children categories
C#/VB.NET: Alternate Row Colors in Excel Using Conditional Formatting
2022-09-08 08:20:00 Written by AdministratorA large worksheet can be made easier to scan and read by adding color to alternative rows or columns. Applying a built-in table style or using conditional formatting are two quick ways to alternate row colors. This article focuses on how to highlight alternative rows using conditional formatting in C# and VB.NET 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
Alternate Row Colors in Excel Using Conditional Formatting
The following are the steps to add color to alternative rows in Excel using Spire.XLS for .NET.
- Create a Workbook object.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet from the workbook through Workbook.Worsheets[index] property.
- Add a conditional formatting to the worksheet using Worksheet.ConditionalFormats.Add() method and return an object of XlsConditionalFormats class.
- Set the cell range where the conditional formatting will be applied using XlsConditionalFormats.AddRange() method.
- Add a condition using XlsConditionalFormats.AddCondition() method, then set the conditional formula and the cell color of even rows.
- Add another condition to change the format of the cells of odd rows.
- Save the workbook to an Excel file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls;
using Spire.Xls.Core;
using Spire.Xls.Core.Spreadsheet.Collections;
using System.Drawing;
namespace AlternateRowColors
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook object
Workbook workbook = new Workbook();
//Load an Excel file
workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Add a conditional format to the worksheet
XlsConditionalFormats format = sheet.ConditionalFormats.Add();
//Set the range where the conditional format will be applied
format.AddRange(sheet.Range[2, 1, sheet.LastRow, sheet.LastColumn]);
//Add a condition to change the format of the cells based on formula
IConditionalFormat condition1 = format.AddCondition();
condition1.FirstFormula = "=MOD(ROW(),2)=0";
condition1.FormatType = ConditionalFormatType.Formula;
condition1.BackColor = Color.Yellow;
//Add another condition to change the format of the cells based on formula
IConditionalFormat condition2 = format.AddCondition();
condition2.FirstFormula = "=MOD(ROW(),2)=1";
condition2.FormatType = ConditionalFormatType.Formula;
condition2.BackColor = Color.LightSeaGreen;
//Save the workbook to an Excel file
workbook.SaveToFile("AlternateRowColors.xlsx", ExcelVersion.Version2016);
}
}
}

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.
Excel print options (also called as sheet options) allow users to control how worksheet pages are printed, such as set print paper size, print area, print titles, page order and so on. This article mainly discusses how developers set print options in C# by using Spire.XLS.
Here comes to the details of how developers configure print options in C#:
- Download Spire.XLS for .NET (or Spire.Office for .NET) and install it on your system.
- Add Spire.XLS.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.XLS\Bin\NET4.0\ Spire.XLS.dll".
- You can use the class PageSetup to set the print options.
Set print paper size:
By default, the paper size is A4; you can set the PaperSize property of the worksheet to set the print paper size you desired.
//set print paper size as A3 sheet.PageSetup.PaperSize = PaperSizeType.PaperA3;
Set Print Area:
By default, the print area means all areas of the worksheet that contain data. You can set the PrintArea property of the worksheet to set the print area you want.
//set print area from cell "B2" to cell "F8" sheet.PageSetup.PrintArea = "B2:F8";
Set Print Titles:
Spire.XLS allows you to designate row and column headers to repeat on all pages of a printed worksheet. To do so, use the PageSetup class' PrintTitleColumns and PrintTitleRows properties.
//Set column numbers A & B as title columns sheet.PageSetup.PrintTitleColumns = "$A:$B"; //Set row numbers 1 & 2 as title rows sheet.PageSetup.PrintTitleRows = "$1:$2";
Set Page Order:
The PageSetup class provides the Order property that is used to order multiple pages of your worksheet to be printed. There are two possibilities to order the pages as follows:
//set page order from down then over sheet.PageSetup.Order = OrderType.DownThenOver; //set page order from over then down sheet.PageSetup.Order = OrderType.OverThenDown;
Below picture shows the Microsoft Excel's page print options:
In document-centric workflows, combining multiple PDF files into a single document is a critical functionality in many .NET applications, ranging from enterprise document management systems to customer-facing invoicing platforms. While many tools exist for this PDF merging task, Spire.PDF for .NET stands out with its balance of simplicity, performance, and cost-effectiveness.

This guide explores how to merge PDF in C# using Spire.PDF, covering basic merging to advanced techniques with practical code examples.
- Why Programmatic PDF Merging Matters
- How to Merge PDFs in C#: Step-by-Step Guide
- Practical Example: Merge Selected Pages from Different PDFs
- Memory Efficient Solution: Merge PDF Files using Streams
- Conclusion
- FAQs
Why Programmatic PDF Merging Matters
In enterprise applications, PDF merging is crucial for:
- Consolidating financial reports
- Combining scanned document batches
- Assembling legal documentation packages
- Automated archiving systems
Spire.PDF for .NET stands out with:
- ✅ Pure .NET solution (no Acrobat dependencies)
- ✅ Cross-platform support (.NET framework, .NET Core, .NET 5+)
- ✅ Flexible page manipulation capabilities
How to Merge PDFs in C#: Step-by-Step Guide
Step 1. Install Spire.PDF
Before diving into the C# code to combine PDF files, it’s necessary to install the .NET PDF library via NuGet Package Manager.
- In Visual Studio, right-click your project in Solution Explorer
- Select Manage NuGet Packages
- Search for Spire.PDF and install
Or in Package Manager Console, run the following:
PM> Install-Package Spire.PDF
Step 2: Basic PDF Merging - C# / ASP.NET Sample
Spire.PDF provides a direct method PdfDocument.MergeFiles() method to merge multiple PDFs into a single file. The below C# code example defines three PDF file paths, merges them, and saves the result as a new PDF.
using Spire.Pdf;
namespace MergePDFs
{
class Program
{
static void Main(string[] args)
{
// Specify the PDF files to be merged
string[] files = new string[] {"sample0.pdf", "sample1.pdf", "sample2.pdf"};
// Merge PDF files
PdfDocumentBase pdf = PdfDocument.MergeFiles(files);
// Save the result file
pdf.Save("MergePDF.pdf", FileFormat.PDF);
}
}
}
Result: Combine three PDF files (total of 7 pages) into one PDF file.

Practical Example: Merge Selected Pages from Different PDFs
Merging selected pages involves combining specific pages from multiple PDFs into a new PDF document. Here’s how to achieve the task:
- Define the PDF files to be merged.
- Load PDFs into an array:
- Create an array of PdfDocument objects.
- Loops through to load each PDF into the array.
- Create a new PDF: Initializes a new PDF document to hold the merged pages.
- Insert specific pages into the new PDF:
- InsertPage(): Insert a specified page to the new PDF (Page index starts at 0).
- InsertPageRange(): Insert a range of pages to the new PDF.
- Save the merged PDF: Save the new document to a PDF file.
Code Example:
using Spire.Pdf;
namespace MergePDFs
{
class Program
{
static void Main(string[] args)
{
// Specify the PDF files to be merged
string[] files = new string[] {"sample0.pdf", "sample1.pdf", "sample2.pdf"};
// Create an array of PdfDocument
PdfDocument[] pdfs = new PdfDocument[files.Length];
// Loop through each PDF file
for (int i = 0; i < files.Length; i++)
{
pdfs[i] = new PdfDocument(files[i]);
}
// Create a new PdfDocument object
PdfDocument newPDF = new PdfDocument();
// Insert the selected pages from different PDFs to the new PDF file
newPDF.InsertPageRange(pdfs[0], 1, 2);
newPDF.InsertPage(pdfs[1], 0);
newPDF.InsertPage(pdfs[2], 1);
// Save the new PDF file
newPDF.SaveToFile("SelectivePageMerging.pdf");
}
}
}
Result: Combine selected pages from three separate PDF files into a new PDF.

Memory Efficient Solution: Merge PDF Files using Streams
For stream-based merging, refer to the C# code below:
using System.IO;
using Spire.Pdf;
namespace MergePDFsByStream
{
class Program
{
static void Main(string[] args)
{
// Specify the PDF files to be merged
string[] pdfFiles = {
"MergePdfsTemplate_1.pdf",
"MergePdfsTemplate_2.pdf",
"MergePdfsTemplate_3.pdf"
};
// Initialize a MemoryStream array
MemoryStream[] ms = new MemoryStream[pdfFiles.Length];
// Read all PDF files to the MemoryStream
for (int i = 0; i < pdfFiles.Length; i++)
{
byte[] fileBytes = File.ReadAllBytes(pdfFiles[i]);
ms[i] = new MemoryStream(fileBytes);
}
// Merge PDF files using streams
PdfDocumentBase pdf = PdfDocument.MergeFiles(ms);
// Save the merged PDF file
pdf.Save("MergePDFByStream.pdf", FileFormat.PDF);
}
}
}
Pro Tip: Learn more stream-based PDF handling techniques via the article: Load and Save PDF Files in Streams Using C#
Conclusion
Spire.PDF simplifies PDF merging in C# with its intuitive API and robust feature set. Whether you need to combine entire documents or specific pages, this library provides a reliable solution. By following the steps outlined in this guide, you can efficiently merge PDFs in your .NET applications while maintaining high quality and performance.
FAQs
Q1: Is Spire.PDF free to use?
A: Spire.PDF offers a free Community Edition with limitations (max 10 pages per document). To evaluate the commercial version without any limitations, request a free trial license here.
Q2: Can I merge PDFs from different sources?
A: Yes. Spire.PDF supports merging PDFs from various sources:
- Local Files: Use LoadFromFile() method.
- Streams: Use LoadFromStream() method.
- Base64: Convert Base64 to a byte array first, then use LoadFromBytes() method.
- URLs: Download the PDF to a stream or file first, then load it.
Q3: Can I add page numbers during merging?
A: After merging, you can add page numbers by following this guide: Add Page Numbers to a PDF in C#.
Q4. Where can I get support for Spire.PDF?
A: Check below resources: