.NET (1316)
Children categories
Generate Excel File in C# – Create and Export in .NET & ASP.NET
2025-07-09 09:37:39 Written by zaki zou
Generating Excel files in C# is a common task for developers building reporting systems, exporting structured data, or automating Excel-based workflows. Whether you're building desktop tools, web APIs with ASP.NET Core, or cross-platform apps using .NET, the ability to generate .xlsx files programmatically can simplify many data exchange scenarios.
In this guide, you'll learn how to generate Excel files in C# using Spire.XLS for .NET — a standalone Excel library that works seamlessly across different types of .NET applications — from desktop tools to web services and background jobs. We’ll cover use cases such as creating spreadsheets from scratch, exporting data from a DataTable, generating files on the server side, and applying formatting or formulas, all with practical code examples.
Table of Contents
- Set Up the Environment
- Create Excel Files from Scratch in C#
- Export DataTable to Excel in C#
- Apply Formatting and Formulas in Excel
- Generate Excel Files in ASP.NET Core
- Generate Excel Files in ASP.NET Web Forms
- FAQ
- Conclusion
Set Up the Environment
Spire.XLS for .NET is a lightweight Excel library that allows you to create .xlsx/.xls files entirely through code — without installing Microsoft Office or using COM Interop. This makes it an ideal solution for web servers, microservices, and cloud-hosted applications.
You can install the library via NuGet:
Install-Package Spire.XLS
For smaller tasks, Free Spire.XLS for .NET is also a good choice:
Install-Package FreeSpire.XLS
Create Excel Files from Scratch in C#
For simple tasks like configuration files, small datasets, or template generation, creating an Excel file from scratch in C# provides full control over content and layout.
The example below shows how to generate a basic worksheet with text and numeric data:
using Spire.Xls;
// Create a new workbook and worksheet
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Summary";
// Fill in headers and data
// Access cells by name
sheet.Range["A1"].Text = "Employee";
sheet.Range["B1"].Text = "Department";
sheet.Range["C1"].Text = "Salary";
// Access cells by row and column
sheet.Range[2, 1].Text = "Alice";
sheet.Range[2, 2].Text = "HR";
sheet.Range[2, 3].NumberValue = 6500;
sheet.Range[3, 1].Text = "Bob";
sheet.Range[3, 2].Text = "IT";
sheet.Range[3, 3].NumberValue = 7200;
// Apply styles
CellStyle headerStyle = workbook.Styles.Add("Header");
headerStyle.Font.IsBold = true;
sheet.Range["A1:C1"].Style = headerStyle;
// sheet.Range[1, 1, 1, 3].Style = headerStyle;
// Auto-fit columns
sheet.AllocatedRange.AutoFitColumns();
// Save the file
workbook.SaveToFile("BasicExcel.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
Example output: A basic Excel file with employee names, departments, and salaries created in C#.

This approach works entirely without Excel installed, and is ideal for lightweight, structured exports.
Export DataTable to Excel in C#
When working with databases or APIs, exporting a DataTable directly to Excel in C# is often necessary. Instead of looping through rows manually, Spire.XLS provides an efficient way to load structured data in one line.
Here’s how you can convert a DataTable into a worksheet, including headers:
using System.Data;
using Spire.Xls;
// Create a simulated data table
DataTable dt = new DataTable("Products");
dt.Columns.Add("Product Name", typeof(string));
dt.Columns.Add("Price", typeof(double));
dt.Columns.Add("Stock", typeof(int));
dt.Rows.Add("Laptop", 1299.99, 20);
dt.Rows.Add("Monitor", 199.5, 50);
dt.Rows.Add("Mouse", 25.75, 150);
// Import into Excel
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Inventory";
sheet.InsertDataTable(dt, true, 1, 1);
// Auto-fit column widths
sheet.AllocatedRange.AutoFitColumns();
// Save the file
workbook.SaveToFile("InventoryReport.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
Example output: Excel spreadsheet generated from a DataTable containing product details, prices, and stock levels.

This is a common approach for exporting reports, inventory lists, and analytics — with no Excel or Interop automation required.
Related article: Convert Data Between Excel Files and DataTable in C#
Apply Formatting and Formulas in Excel Using C#
In addition to exporting raw data, you can generate professional Excel files in C# by applying formatting, styling, and formulas — improving readability and enabling automatic calculations.
Below is an example that demonstrates basic styling and formula use:
using Spire.Xls;
using System.Drawing;
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Sales Report";
// Set header labels
sheet.Range["A1"].Text = "Item";
sheet.Range["B1"].Text = "Price";
sheet.Range["C1"].Text = "Quantity";
sheet.Range["D1"].Text = "Total";
// Add sample data
string[,] items = {
{ "Pen", "1.5", "10" },
{ "Notebook", "3.75", "5" },
{ "Eraser", "0.99", "20" }
};
for (int i = 0; i < items.GetLength(0); i++)
{
int row = i + 2;
sheet.Range[$"A{row}"].Text = items[i, 0];
sheet.Range[$"B{row}"].NumberValue = double.Parse(items[i, 1]);
sheet.Range[$"C{row}"].NumberValue = double.Parse(items[i, 2]);
sheet.Range[$"D{row}"].Formula = $"=B{row}*C{row}";
}
// Style: Header row
CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
headerStyle.Font.IsBold = true;
headerStyle.Font.Color = Color.White;
headerStyle.Font.Size = 12;
headerStyle.KnownColor = ExcelColors.DarkBlue;
headerStyle.HorizontalAlignment = HorizontalAlignType.Center;
headerStyle.VerticalAlignment = VerticalAlignType.Center;
headerStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thick;
headerStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thick;
sheet.Range["A1:D1"].Style = headerStyle;
sheet.Range["A1:D1"].RowHeight = 22;
// Style: Data cells
CellStyle dataStyle = workbook.Styles.Add("DataStyle");
dataStyle.NumberFormat = "\"$\"#,##0.00";
dataStyle.HorizontalAlignment = HorizontalAlignType.Right;
dataStyle.VerticalAlignment = VerticalAlignType.Center;
dataStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
dataStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
// Apply data style to Price, Quantity, Total
sheet.Range["B2:D4"].Style = dataStyle;
// Optional: Alternating row colors for readability
for (int r = 2; r <= 4; r++)
{
if (r % 2 == 0)
sheet.Range[$"A{r}:D{r}"].Style.KnownColor = ExcelColors.LightYellow;
}
// Adjust widths and heights
sheet.AllocatedRange.AutoFitColumns();
sheet.AllocatedRange.RowHeight = 20;
// Save file
workbook.SaveToFile("styled.xlsx", FileFormat.Version2016);
workbook.Dispose();
Example output: A styled Excel sheet with headers, formulas, alternating row colors, and formatted currency values.

By using C# and Spire.XLS, you can apply styles, borders, colors, alignments, and Excel-compatible formulas to generate clean, automated, and user-friendly Excel reports.
To further enhance your Excel reports, you can also apply number formats such as currency, percentage, or custom formats. Learn more about setting number formats in C#
Generate Excel Files in ASP.NET Core
In modern ASP.NET Core applications (e.g., .NET 6/7/8), generating Excel files is a common requirement for admin dashboards, data exports, and reporting features. The example below shows how to generate an Excel file on the server and return it as a downloadable file from a Razor Page handler.
Here’s how you can implement it in a Razor Pages project:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Spire.Xls;
using System.Data;
public class ExportModel : PageModel
{
public IActionResult OnGet()
{
// Simulated data
DataTable dt = new DataTable("Sales");
dt.Columns.Add("Date", typeof(DateTime));
dt.Columns.Add("Product", typeof(string));
dt.Columns.Add("Revenue", typeof(double));
dt.Rows.Add(DateTime.Today.AddDays(-2), "Laptop", 1250.00);
dt.Rows.Add(DateTime.Today.AddDays(-1), "Monitor", 320.50);
dt.Rows.Add(DateTime.Today, "Mouse", 25.99);
// Create Excel workbook and sheet
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "DailySales";
// Insert data
sheet.InsertDataTable(dt, true, 1, 1);
// Apply simple header style
CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
headerStyle.Font.IsBold = true;
sheet.Rows[0].Style = headerStyle;
sheet.AllocatedRange.AutoFitColumns();
// Save to memory stream
using var stream = new MemoryStream();
workbook.SaveToStream(stream, FileFormat.Version2016);
stream.Position = 0;
// Return file to browser
return File(stream.ToArray(),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"SalesReport.xlsx");
}
}
Example output: Daily sales report generated in a .NET 8 console app with date, product, and revenue columns.

This method is ideal for web-based reporting tools, internal portals, and admin dashboards that require dynamic Excel downloads.
- ✅ Works in ASP.NET Core 3.1, .NET 5, .NET 6, .NET 7, .NET 8
- ✅ Suitable for: Razor Pages, MVC, and API endpoints with file download support
Generate Excel Files in ASP.NET Web Forms
If you're building an internal admin panel or classic ASP.NET Web Forms application, you may want to allow users to download Excel files directly from the browser. The example below demonstrates how to create an Excel file entirely in memory and return it in the HTTP response for immediate download — without saving it to disk.
using Spire.Xls;
using System;
using System.IO;
namespace YourNamespace
{
public partial class Default : System.Web.UI.Page
{
protected void btnExport_Click(object sender, EventArgs e)
{
// Create Excel file and output for download
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Users";
// Headers
string[] headers = { "ID", "Name", "Department", "Join Date" };
for (int i = 0; i < headers.Length; i++)
{
sheet.Range[1, i + 1].Text = headers[i];
sheet.Range[1, i + 1].Style.Font.IsBold = true;
}
// Sample data
string[,] data = {
{ "U001", "Gemma", "HR", "2023-01-15" },
{ "U002", "Bill", "IT", "2022-11-03" }
};
// Fill data
for (int r = 0; r < data.GetLength(0); r++)
for (int c = 0; c < data.GetLength(1); c++)
sheet.Range[r + 2, c + 1].Text = data[r, c];
// Auto-fit column widths
sheet.AllocatedRange.AutoFitColumns();
// Export for browser download
using (MemoryStream ms = new MemoryStream())
{
workbook.SaveToStream(ms, FileFormat.Version2016);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename=Users.xlsx");
Response.BinaryWrite(bytes);
Response.End();
}
}
}
}
Example output: Excel file created and streamed to browser in ASP.NET containing employee records.

This pattern allows Excel files to be generated and downloaded dynamically, without writing to disk or requiring Office installed on the server.
FAQ
How to create an Excel file from C#?
You can use a library like Spire.XLS to create a new workbook, write data to worksheets, and save it as an Excel file — all without Office installed.
How to export an Excel file in C#?
If you want to export data (e.g. from a DataTable), you can load it into a worksheet and save the file using Spire.XLS. It supports automatic column headers and formatting.
How to generate Excel files in ASP.NET using C#?
You can generate Excel files in both ASP.NET Web Forms and ASP.NET Core using Spire.XLS. In ASP.NET Core, create the file in memory and return it in the HTTP response. In Web Forms, use a similar approach with Response.BinaryWrite() to stream the file to the browser.
Is Spire.XLS compatible with .NET Core?
Yes. It supports .NET Core 3.1+, .NET 5, .NET 6, .NET 7, and .NET 8, making it suitable for cross-platform Excel generation.
Conclusion
With Spire.XLS for .NET, you can easily generate Excel files in C# for any scenario — including desktop, ASP.NET Core, and classic Web Forms applications. Whether you need to export a DataTable, generate formatted reports, or automate Excel output, this guide helps you build Excel files in C# with zero dependencies.
Apply for a Free Temporary License to unlock all features and remove evaluation warnings.

Sending emails from a C# application is a common task in business and enterprise development. Whether you're delivering a project update, sending alerts, or automating reporting workflows, reliable email functionality is essential.
In this article, we’ll walk through how to send emails in C# using Spire.Email for .NET, a powerful component that simplifies SMTP communication and email formatting. We'll explore SMTP configuration, Gmail integration, HTML and plain-text content, file attachments, and multiple recipients.
Table of Contents
- 1. Project Setup
- 2. Send a Plain-Text Email via SMTP
- 3. Send HTML Email with Attachments via Gmail SMTP
- 4. Advanced Email Features with Spire.Email
- 5. Common Errors and Troubleshooting
- 6. Use Cases for Spire.Email
- 7. Free License
- 8. FAQ
1. Project Setup
To begin, create a .NET project (Console App or ASP.NET) and add the Spire.Email for .NET package.
Install via NuGet:
Install-Package Spire.Email
Or manually download the Spire.Email package and reference the Spire.Email.dll from your local installation package.
2. Send a Basic Email via SMTP in C#
The example below shows how to use Spire.Email to send a plain-text email through an SMTP server.
using Spire.Email;
using Spire.Email.Smtp;
// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.example.com";
smtp.Port = 587;
smtp.Username = "your@example.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Create maill addresses
MailAddress sender = new MailAddress("your@example.com", "Sender Name");
MailAddress recipient = new MailAddress("recipient@example.com", "Recipient Name");
MailMessage message = new MailMessage(sender, recipient);
// Set the email content
message.Subject = "Test Email";
message.BodyText = "This is a plain-text test email.";
// Send the email
smtp.SendOne(message);
Explanation:
- Uses MailAddress and MailMessage from Spire.Email
- Establishes a secure SMTP connection using ConnectionProtocols.StartTls
The screenshot below shows the actual email received using the above SMTP code.

3. Send HTML Email with Attachments via Gmail SMTP in C#
The following C# code example demonstrates how to send an HTML-formatted email using Gmail SMTP, including multiple recipients, a file attachment, and plain-text fallback for clients that do not support HTML.
using Spire.Email;
using Spire.Email.Smtp;
// Create MailAddress objects
MailAddress from = new MailAddress("your@gmail.com", "Your Name");
MailAddress to1 = new MailAddress("user1@example.com", "User One");
MailAddress to2 = new MailAddress("user2@example.com", "User Two");
// Create a mail message
MailMessage message = new MailMessage(from, to1);
message.To.Add(to2);
message.Cc.Add(new MailAddress("cc@example.com", "CC Person"));
message.Bcc.Add(new MailAddress("bcc@example.com"));
// Set the body HTML and text for the message
message.Subject = "Monthly Report - June 2025";
message.BodyHtml = "<h2 style='color:#2E86C1;'>Report Summary</h2><p>Please see the attached PDF report.</p>";
message.BodyText = "Report Summary - please see the attached PDF.";
// Add an attachment to the email
Attachment attachment = new Attachment(@"Sample.pdf");
message.Attachments.Add(attachment);
// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Username = "your@gmail.com";
smtp.Password = "your_app_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Sen the email
smtp.SendOne(message);
Explanation:
- Uses MailAddress, MailMessage, Attachment, and SmtpClient from Spire.Email
- Combines BodyHtml and BodyText to support HTML and plain-text email clients
- Adds multiple recipients via To.Add(), Cc.Add(), and Bcc.Add()
- Sends email securely through Gmail using ConnectionProtocols.StartTls
Gmail requires App Passwords if 2FA is enabled.
The following screenshot shows the HTML-formatted email with rich text, CC and BCC recipients, and a PDF attachment, as received from Gmail SMTP.

Related article: How to Send an Email with Attachments in C#
4. Advanced Email Features with Spire.Email
This section demonstrates advanced C# email-sending capabilities using Spire.Email, including embedded images and batch dispatch.
// Prepare an email with embedded image
MailMessage message = new MailMessage(
new MailAddress("your@domain.com", "Sender"),
new MailAddress("client@domain.com", "Client"));
message.Subject = "Branding Update";
message.BodyHtml = "<h1>Our New Logo</h1><img src=\"cid:logo\">";
message.BodyText = "Please view this message in HTML to see the image.";
Attachment logo = new Attachment(@"C:\Images\logo.png");
logo.ContentId = "logo";
logo.DispositionType = "Inline";
message.Attachments.Add(logo);
// Prepare a second email
MailMessage message2 = new MailMessage(
new MailAddress("your@domain.com"),
new MailAddress("sales@domain.com"));
message2.Subject = "Weekly Summary";
message2.BodyText = "This is an automated weekly update.";
// Create SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.domain.com";
smtp.Port = 587;
smtp.Username = "your@domain.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Send one email
smtp.SendOne(message);
// Send emails in batch
smtp.SendSome(new List<MailMessage> { message, message2 });
Explanation:
Attachment.ContentIdandDispositionType = "Inline"allow inline images using CID references in HTML.SendOne()sends a single message.SendSome()sends multiple messages as a batch. Ideal for scheduled reports or group notifications.
The following screenshot shows an email with an embedded company logo and a plain-text fallback, demonstrating how Spire.Email renders HTML content with inline images.

You may also like: Creating MSG Files with RTF Body and Attachments Using C#
5. Common Errors and Troubleshooting
| Error | Likely Cause |
|---|---|
| Authentication failed | Incorrect credentials or missing app password |
| Secure connection required | Use StartTLS or SSL in ConnectionProtocols |
| HTML content not displaying | Ensure BodyHtml and fallback BodyText are set |
| File not found | Incorrect file path for attachment |
6. Use Cases for Spire.Email
Spire.Email for .NET is suitable for:
- Daily/weekly automated reporting
- User signup and notification emails
- Order confirmations with attachments
- Form submission alerts
- Embedded-image newsletters
Its clean API removes the need to manually handle SMTP headers, MIME formatting, and encoding issues.
Conclusion
With Spire.Email for .NET, developers can quickly build robust and flexible email-sending features directly into C# applications. Whether the goal is to deliver transactional messages, generate styled reports, or dispatch scheduled newsletters, this component provides a clean, reliable API that simplifies every step of the process.
By supporting plain-text and HTML formats, attachments, Gmail SMTP, embedded images, and batch sending, Spire.Email helps streamline email integration without the overhead of external dependencies.
7. Apply for a Free Temporary License
To remove the evaluation warning in the email body or attachment footer, you can apply for a free temporary license:
Request a Free 1-Month License
Simply fill out the form and follow the instructions to apply the license in your project. This enables full feature access during evaluation.
8. FAQ
How to send HTML email in C#?
You can set the BodyHtml property of the MailMessage object to send an HTML email using Spire.Email. You can also include BodyText as a fallback for clients that don't support HTML.
How to send email to multiple recipients in C#?
Add multiple recipients using message.To.Add(), message.Cc.Add(), and message.Bcc.Add() methods. Spire.Email supports To, Cc, and Bcc fields.
How to use SMTP to send email in ASP.NET or MVC projects?
The SMTP usage in ASP.NET or MVC is the same as in Console applications. Simply configure the SmtpClient with host, port, credentials, and use the same SendOne() or SendSome() methods to dispatch your message.

QR codes have become a common part of modern applications — from user authentication and digital payments to product packaging and event tickets. In many of these scenarios, developers often need to read QR codes in C# as part of their workflow, especially when working with image-based inputs like scanned documents or uploaded files.
To handle such tasks reliably, a decoding method that’s both accurate and easy to implement is essential. In this tutorial, we’ll walk through a straightforward approach to reading QR codes from images using C#, with minimal setup and clean integration.
Quick Navigation
- Project Setup
- Read QR Code from Image Using C#
- Read QR Code from Stream Using C#
- Improve Accuracy and Handle Errors
- Bonus: Get QR Code Coordinates
- FAQ
- Final Thoughts
1. Project Setup
To begin, we’ll use a .NET barcode library that supports QR code decoding. In this guide, we demonstrate with Spire.Barcode for .NET, which provides a simple API for reading QR codes from image files and streams.
1.1 Install the Library via NuGet
You can install the library through NuGet Package Manager:
Install-Package Spire.Barcode
For basic scenarios, you can also use Free Spire.Barcode for .NET:
Install-Package FreeSpire.Barcode
1.2 Create a New Console Project
For demonstration, create a C# Console App in Visual Studio:
- Target .NET Framework, .NET Core/.NET 6+, ASP.NET, or Xamarin for cross-platform mobile development
- Add reference to Spire.Barcode.dll (if not using NuGet)
2. Read QR Code from Image in C#
To read QR codes from an image file in C#, you can simply use the static BarcodeScanner.Scan() method provided by the library. This method takes an image path and the BarCodeType as input and returns all decoded results that match the specified barcode type — in this case, QR codes.
This method supports scanning images in formats like JPG, PNG, and EMF. It’s the most direct way to scan QR code data in desktop applications or backend services that receive uploaded files.
2.1 Sample Code: Decode QR Code from an Image File
using Spire.Barcode;
class Program
{
static void Main(string[] args)
{
// Load the QR code image
string imagePath = @"C:\qr-code.png";
// Barcode scanner reads QR code from image file
string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);
// Display QR code result(s)
foreach (string result in results)
{
Console.WriteLine("QR Code Data: " + result + "\n");
}
}
}
The QR code image and the scan results from C# code:

2.2 Explanation
- Scan() reads and decodes all barcodes found in the image.
- BarCodeType.QRCode ensures only QR codes are detected (you can change it to detect other types).
- Returns an array in case the image contains multiple QR codes.
You may also like: How to Generate QR Codes Using C#
3. Read QR Code from Stream in C#
In web APIs or modern applications where images are processed in memory, you’ll often deal with Stream objects—such as when handling file uploads or reading from cloud storage.
The BarcodeScanner.Scan() method also accepts a Stream directly, allowing you to decode QR codes from memory streams without converting them to Bitmap.
using Spire.Barcode;
using System.IO;
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream(@"C:\qr-code.png", FileMode.Open, FileAccess.Read))
{
// Directly scan the QR codes from the image stream
string[] results = BarcodeScanner.Scan(fs, BarCodeType.QRCode, false);
foreach (string result in results)
{
Console.WriteLine("QR Code Data: " + result);
}
}
}
}
This method is useful for WPF or ASP.NET Core apps that handle QR code images in memory.
Related article: Scan Barcodes from PDF Using C#
4. Improve Accuracy and Handle Errors
In real-world scenarios, QR code recognition may occasionally fail due to image quality or unexpected input issues. Here are best practices to improve decoding accuracy and handle failures in C#:
4.1 Boost Recognition Accuracy
- Use high-resolution images. Avoid blurred or overcompressed files.
- Ensure quiet zone (white space) around the QR code is preserved.
- Use formats like PNG for better clarity.
- Avoid perspective distortion — use straight, scanned images.
4.2 Add Robust Error Handling
Wrap your decoding logic in a try-catch block to prevent crashes and inform the user clearly:
try
{
string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);
if (results.Length == 0)
{
Console.WriteLine("No QR code found.");
}
else
{
Console.WriteLine("QR Code: " + results[0]);
}
}
catch (Exception ex)
{
Console.WriteLine("Error decoding QR code: " + ex.Message);
}
5. Bonus: Get QR Code Coordinates
Sometimes, you may need to locate the QR code’s exact position in the image—for cropping, overlay, or annotation. The ScanInfo() method helps retrieve bounding boxes:
BarcodeInfo[] results = BarcodeScanner.ScanInfo(imagePath, BarCodeType.QRCode);
foreach (BarcodeInfo result in results)
{
Console.WriteLine("Data: " + result.DataString);
Console.WriteLine($"Coordinates: " + string.Join(",", result.Vertexes.Select(p => $"({p.X},{p.Y})")) + "\n");
}
This provides both the data and the coordinates of each detected QR code.
The reading results:

6. FAQ
How to read QR code in C#?
You can use the Spire.Barcode for .NET library and its BarcodeScanner.Scan() method to read QR codes from image files or memory streams in just a few lines of code.
How do I read my own QR code image?
Load your QR code image file path into the scanner, or open it as a stream if you're working in a web or WPF application. The scanner will decode all readable QR codes in the image.
How to read barcodes in C# (not just QR codes)?
You can simply pass the image path to the Scan() method, and it will automatically detect and read all supported barcode types. To restrict detection to a specific type (e.g., only QR codes or Code128), pass the corresponding BarCodeType as the second parameter.
What is the best barcode reader library for C#?
Spire.Barcode for .NET is a popular choice for its simplicity, format support, and clean API. It supports both free and commercial use cases.
7. Final Thoughts
Reading QR codes in C# can be implemented with just a few lines of code using Spire.Barcode for .NET. It supports image and stream-based decoding, works well for desktop, server-side, or WPF applications, and offers solid performance with minimal setup.
You can further explore QR code generation, document integration, and real-time scanning workflows based on this foundation.
Need to unlock full barcode reading features?
Request a free temporary license and try the full capabilities of Spire.Barcode for .NET without limitations.
How to Read Barcodes from PDF in C# – Easy Methods with Code
2025-06-19 06:58:45 Written by Administrator
Reading barcodes from PDF in C# is a common requirement in document processing workflows, especially when dealing with scanned forms or digital PDFs. In industries like logistics, finance, healthcare, and manufacturing, PDFs often contain barcodes—either embedded as images or rendered as vector graphics. Automating this process can reduce manual work and improve accuracy.
This guide shows how to read barcode from PDF with C# using two practical methods: extracting images embedded in PDF pages and scanning them, or rendering entire pages as images and detecting barcodes from the result. Both techniques support reliable recognition of 1D and 2D barcodes in different types of PDF documents.
Table of Contents
- Getting Started: Tools and Setup
- Step-by-Step: Read Barcodes from PDF in C#
- Which Method Should You Use?
- Real-World Use Cases
- FAQ
Getting Started: Tools and Setup
To extract or recognize barcodes from PDF documents using C#, make sure your environment is set up correctly.
Here’s what you need:
- Any C# project that supports NuGet package installation (such as .NET Framework, .NET Core, or .NET).
- The following libraries, Spire.Barcode for .NET for barcode recognition and Spire.PDF for .NET for PDF processing, can be installed via NuGet Package Manager:
Install-Package Spire.Barcode
Install-Package Spire.PDF
Step-by-Step: Read Barcodes from PDF in C#
There are two ways to extract barcode data from PDF files. Choose one based on how the barcode is stored in the document.
Method 1: Extract Embedded Images and Detect Barcodes
This method is suitable for scanned PDF documents, where each page often contains a raster image with one or more barcodes. The BarcodeScanner.ScanOne() method can read one barcode from one image.
Code Example: Extract and Scan
using Spire.Barcode;
using Spire.Pdf;
using Spire.Pdf.Utilities;
using System.Drawing;
namespace ReadPDFBarcodeByExtracting
{
class Program
{
static void Main(string[] args)
{
// Load a PDF file
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");
// Get a page and the image information on the page
PdfPageBase page = pdf.Pages[0];
PdfImageHelper imageHelper = new PdfImageHelper();
PdfImageInfo[] imagesInfo = imageHelper.GetImagesInfo(page);
// Loop through the image information
int index = 0;
foreach (PdfImageInfo imageInfo in imagesInfo)
{
// Get the image as an Image object
Image image = imageInfo.Image;
// Scan the barcode and output the result
string scanResult = BarcodeScanner.ScanOne((Bitmap)image);
Console.WriteLine($"Scan result of image {index + 1}:\n" + scanResult + "\n");
index++;
}
}
}
}
The following image shows a scanned PDF page and the barcode recognition result using Method 1 (extracting embedded images):

When to use: If the PDF is a scan or contains images with embedded barcodes.
You may also like: Generate Barcodes in C# (QR Code Example)
Method 2: Render Page as Image and Scan
When barcodes are drawn using vector elements (not embedded images), you can render each PDF page as a bitmap and perform barcode scanning on it. The BarcodeScanner.Scan() method can read multiple barcodes from one image.
Code Example: Render and Scan
using Spire.Barcode;
using Spire.Pdf;
using System.Drawing;
namespace ReadPDFBarcodeByExtracting
{
class Program
{
static void Main(string[] args)
{
// Load a PDF file
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");
// Save each page as an image
for (int i = 0; i < pdf.Pages.Count; i++)
{
Image image = pdf.SaveAsImage(i);
// Read the barcodes on the image
string[] scanResults = BarcodeScanner.Scan((Bitmap)image);
// Output the results
for (int j = 0; j < scanResults.Length; j++)
{
Console.WriteLine($"Scan result of barcode {j + 1} on page {i + 1}:\n" + scanResults[j] + "\n");
}
}
}
}
}
Below is the result of applying Method 2 (rendering full PDF page) to detect vector barcodes on the page:

When to use: When barcodes are drawn on the page directly, not embedded as image elements.
Related article: Convert PDF Pages to Images in C#
Which Method Should You Use?
| Use Case | Recommended Method |
|---|---|
| Scanned pages or scanned barcodes | Extract embedded images |
| Digital PDFs with vector barcodes | Render full page as image |
| Hybrid or unknown structure | Try both methods optionally |
You can even combine both methods for maximum reliability when handling unpredictable document structures.
Real-World Use Cases
Here are some typical scenarios where barcode recognition from PDFs in C# proves useful:
-
Logistics automation Extract tracking numbers and shipping IDs from scanned labels, dispatch forms, or signed delivery receipts in bulk.
-
Invoice and billing systems Read barcode-based document IDs or payment references from digital or scanned invoices in batch processing tasks.
-
Healthcare document digitization Automatically scan patient barcodes from lab reports, prescriptions, or admission forms in PDF format.
-
Manufacturing and supply chain Recognize barcodes from packaging reports, quality control sheets, or equipment inspection PDFs.
-
Educational institutions Process barcoded student IDs on scanned test forms or attendance sheets submitted as PDFs.
Tip: In many of these use cases, PDFs come from scanners or online systems, which may embed barcodes as images or page content—both cases are supported with the two methods introduced above.
Conclusion
Reading barcodes from PDF files in C# can be achieved reliably using either image extraction or full-page rendering. Whether you need to extract a barcode from a scanned document or recognize one embedded in PDF content, both methods provide flexible solutions for barcode recognition in C#.
FAQ
Q: Does this work with multi-page PDFs?
Yes. You can loop through all pages in the PDF and scan each one individually.
Q: Can I extract multiple barcodes per page?
Yes. The BarcodeScanner.Scan() method can detect and return all barcodes found on each image.
Q: Can I improve recognition accuracy by increasing resolution?
Yes. When rendering a PDF page to an image, you can set a higher DPI using PdfDocument.SaveAsImage(pageIndex: int, PdfImageType.Bitmap: PdfImageType, dpiX: int, dpiY: int). For example, 300 DPI is ideal for small or low-quality barcodes.
Q: Can I read barcodes from PDF using C# for free?
Yes. You can use Free Spire.Barcode for .NET and Free Spire.PDF for .NET to read barcodes from PDF files in C#. However, the free editions have feature limitations, such as page count or supported barcode types. If you need full functionality without restrictions, you can request a free temporary license to evaluate the commercial editions.
Extract Background Images from PowerPoint Presentations using C# .NET
2025-05-16 09:01:16 Written by Administrator
PowerPoint presentations often contain background images that enhance the visual appeal of slides. Extracting these background images can be crucial for designers and content managers who wish to reuse, analyze, or archive slide visuals independently of the slide content.
This guide provides a clear, step-by-step approach to extracting background images from PowerPoint presentations in .NET using C# and the Spire.Presentation for .NET library.
Table of Contents
- Why Extract Background Images from PowerPoint
- Install .NET PowerPoint Library – Spire.Presentation for .NET
- Extract Background Images from PowerPoint in .NET using C#
- FAQs
- Conclusion
Why Extract Background Images from PowerPoint
Extracting background images from PowerPoint provides several key benefits:
- Reuse Designs: Repurpose background images in other presentations or design projects.
- Analyze Slides: Review and understand slide designs by examining background images separately.
- Archive Visuals: Store background images for documentation, backup, or future use.
Install .NET PowerPoint Library – Spire.Presentation for .NET
Spire.Presentation for .NET is a robust .NET PowerPoint library that enables developers to create, manipulate, and convert PowerPoint presentations without the need for Microsoft PowerPoint.
Key Features of Spire.Presentation for .NET
Here are some key features of Spire.Presentation for .NET:
- Create and edit PowerPoint presentations.
- Convert PowerPoint to other formats such as PDF, Images, HTML, Markdown, and XPS.
- Secure PowerPoint presentations
- Merge/split PowerPoint presentations.
- Slides management, including adding/removing slides, setting/extracting/removing backgrounds, and more.
- Image/shape/chart/smartart insertion and manipulation.
- Animate text/shapes.
Install Spire.Presentation for .NET
Before starting the background image extraction process, you will need to install Spire.Presentation for .NET into your C# project using one of the following methods:
Option1. Install via NuGet (Recommended)
Install-Package Spire.Presentation
Option 2: Manually Add DLLs to Your Project
- Download the Spire.Presentation package and extract the files.
- In Visual Studio, right-click References > Add Reference > Browse, then select the appropriate Spire.Presentation.dll based on your target framework.
Extract Background Images from PowerPoint in .NET using C#
Background images in PowerPoint can be applied directly to individual slides or inherited from slide masters. This section demonstrates how to extract both types of background images using Spire.Presentation.
Extract Background Images from Individual Slides
To extract background images from individual slides in PowerPoint, follow these steps:
- Create a Presentation object and load the presentation.
- Loop through all slides in the presentation.
- Check if the slide’s background fill type is image fill (FillFormatType.Picture).
- If yes, retrieve and save the background image.
Sample Code
- C#
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.IO;
namespace ExtractSlideBackgroundImages
{
internal class Program
{
static void Main(string[] args)
{
// Specify the input file path and output folder
string inputFile = @"example1.pptx";
string outputFolder = @"ExtractedBackgrounds\Slides";
// Load the PowerPoint presentation
Presentation presentation = new Presentation();
presentation.LoadFromFile(inputFile);
// Create the output folder
Directory.CreateDirectory(outputFolder);
// Loop through all slides
for (int i = 0; i < presentation.Slides.Count; i++)
{
// Check if the slide's background fill type is image fill
var fill = presentation.Slides[i].SlideBackground.Fill;
if (fill.FillType == FillFormatType.Picture)
{
// Extract and save the background image
var image = fill.PictureFill.Picture.EmbedImage;
if (image != null)
{
string outputPath = Path.Combine(outputFolder, $"SlideBackground_{i + 1}.png");
image.Image.Save(outputPath, ImageFormat.Png);
}
}
}
}
}
}
Extract Background Images from Slide Masters
Slide masters define the design and layout of slides, including background images. To extract background images from slide masters:
- Create a Presentation object and load the presentation.
- Loop through all slide masters in the presentation.
- For each master, check if its background fill type is image fill.
- If yes, extract and save the background image.
Sample Code
- C#
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace ExtractBackgroundImages
{
internal class Program
{
static void Main(string[] args)
{
// Specify the input file path and output folder
string inputFile = @"example2.pptx";
string outputFolder = @"C:\ExtractedBackgrounds\Masters";
// Load the PowerPoint presentation
Presentation presentation = new Presentation();
presentation.LoadFromFile(inputFile);
// Create the output folder
Directory.CreateDirectory(outputFolder);
// Loop through all slide masters
for (int i = 0; i < presentation.Masters.Count; i++)
{
// Check if the slide master's background fill type is image fill
var fill = presentation.Masters[i].SlideBackground.Fill;
if (fill.FillType == FillFormatType.Picture)
{
// Extract and save the background image
var image = fill.PictureFill.Picture.EmbedImage;
if (image != null)
{
string outputPath = Path.Combine(outputFolder, $"MasterBackground_{i + 1}.png");
image.Image.Save(outputPath, ImageFormat.Png);
}
}
}
}
}
}
Conclusion
Extracting background images from PowerPoint presentations is a crucial technique for developers and designers who want to access slide visuals independently of content. By leveraging the Spire.Presentation for .NET library with C#, you can programmatically extract background images from both individual slides and slide masters with ease.
FAQs
Q: What image formats are supported for extraction?
A: Extracted images can be saved in PNG, JPEG, BMP, or other formats supported by .NET.
Q: In addition to background images, can I extract other images from PowerPoint slides?
A: Yes, you can extract other images, such as those embedded within slide content or shapes, using Spire.Presentation.
Q: Does Spire.Presentation supports extracting text from PowerPoint presentations?
A: Yes, Spire.Presentation can also extract text from slides, including text in shapes, tables, and more.
Get a Free License
To fully experience the capabilities of Spire.Presentation for .NET without any evaluation limitations, you can request a free 30-day trial license.

In data processing and management scenarios, efficiently transforming raw text (TXT) files into structured Excel spreadsheets is a common requirement. For developers who are automating reports or processing log files, converting TXT to Excel using C# streamlines data organization and analysis. This guide explores how to achieve this using Spire.XLS for .NET, a powerful library designed to handle Excel XLS or XLSX files without requiring Microsoft Office.
- Why Convert TXT to Excel Programmatically?
- How to Convert Text Files to Excel in C# (Step-by-Step Guide)
- Pro Tips for TXT to Excel Conversion
Why Convert TXT to Excel Programmatically?
Text files are simple but lack the analytical power of Excel. Key advantages of converting TXT to XLS or XLSX format include:
- Automation: Process large or recurring files without manual intervention.
- Data Structuring: Organize raw text into rows, columns, and sheets.
- Advanced Features: Leverage Excel formulas, charts, and pivot tables.
- Integration: Embed conversion feature into .NET applications or APIs.
How to Convert Text Files to Excel in C# (Step-by-Step Guide)
Install Spire.XLS for .NET
Spire.XLS for .NET is a professional Excel document processing component, provides efficient and convenient APIs that allow developers to achieve TXT to Excel conversion through simple code.
Before getting started, you can choose one of these methods to install the library:
Method 1: NuGet Package Manager
- Open your project in Visual Studio.
- Right-click on the project in the Solution Explorer and select "Manage NuGet Packages."
- Search for "Spire.XLS" and click "Install".
Method 2: Package Manager Console
- Go to "Tools > NuGet Package Manager > Package Manager Console."
- Run the following command in the console:
PM> Install-Package Spire.XLS
Method 3: Manual Installation with DLL Files
- Visit the Spire.XLS Download Page and get the latest version.
- Extract the files and then add the Spire.Xls.dll to your project.
Import a Text File into Excel Using C#
Follow the below steps to write the data in a txt file into an Excel worksheet:
- Read TXT File: use the File.ReadAllLines() method to read all lines in a text file and returns them as an array of strings.
- Parse each line:
- Use the string.Trim() method to remove the leading/trailing whitespaces.
- Use the string.Split() method to split the data based on specified delimiters.
- Add the split text data to a list.
- Create a Workbook instance and get a worksheet
- Write Data to specified cells:
- Iterate through the rows and columns in the list.
- Assign the data in the list to the corresponding Excel cells through the Worksheet.Range[].Value property.
- Save the Excel File.
Code Example:
- C#
using Spire.Xls;
using System.IO;
using System.Collections.Generic;
class TxtToExcelConverter
{
static void Main()
{
// Open a text file and read all lines in it
string[] lines = File.ReadAllLines("Data.txt");
// Create a list to store the data in text file
List data = new List();
// Split data into rows and columns and add to the list
foreach (string line in lines)
{
data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
}
// Create a Workbook object
Workbook workbook = new Workbook();
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Iterate through the rows and columns in the data list
for (int row = 0; row < data.Count; row++)
{
for (int col = 0; col < data[row].Length; col++)
{
// Write the text data in specified cells
sheet.Range[row + 1, col + 1].Value = data[row][col];
// Set the header row to Bold
sheet.Range[1, col + 1].Style.Font.IsBold = true;
}
}
// Autofit columns
sheet.AllocatedRange.AutoFitColumns();
// Save the Excel file
workbook.SaveToFile("TXTtoExcel.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
Result:

Pro Tips for TXT to Excel Conversion
- Handling Different Delimiters:
If your TXT file uses a different delimiter (e.g., space, comma, semicolon), modify the parameter of the Split(params char[] separator) method.
- Format Cells:
After a text file being converted to an Excel file, you can take advantage of the Spire.XLS library’s rich features to format cells, such as setting the background colors, adding cell borders, applying number formats, etc.
Conclusion
By following this step-by-step guide, you can efficiently transform unstructured text data into organized Excel spreadsheets, which is ideal for data analysis, reporting, and management. Remember to optimize your implementation for your specific delimiters and leverage Spire.XLS's advanced features for complex conversion scenarios.
Get a Free License
To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.
Generating Word documents programmatically is a common requirement in business applications, whether for creating reports, contracts, or personalized letters. Spire.Doc for .NET provides a comprehensive solution for working with Word documents in C# without Microsoft Office dependencies.
This article explores two effective approaches for document generation from templates: replacing text placeholders and modifying bookmark content.
- Create a Word Document By Replacing Text Placeholders
- Create a Word Document By Replacing Bookmark Content
.NET Library for Creating Word Documents
Spire.Doc for .NET is a professional Word API that enables developers to perform a wide range of document processing tasks. Key features include:
- Creating, reading, editing, and converting Word documents
- Support for DOC, DOCX, RTF, and other formats
- Template-based document generation
- Mail merge functionality
- Preservation of original formatting
The library is particularly useful for automating document generation in enterprise applications, where consistency and efficiency are crucial.
To begin generating Word documents from a template, donwload Spire.Doc for .NET from our official website or install it using the NuGet Package Manager with the following command:
PM> Install-Package Spire.Doc
Create a Word Document By Replacing Text Placeholders
The Document.Replace method in the Spire.Doc library is used to find and replace specific text within a Word document. This method allows for the efficient modification of text placeholders, enabling the dynamic generation of documents based on templates.
Here are the steps for Word generation through text pattern replacement:
- Document Initialization: Create a new Document object and load the template file.
- Placeholder Definition: Use a dictionary to map placeholders (like #name#) to their replacement values.
- Text Replacement: The Document.Replace method performs case-sensitive and whole-word replacement of all placeholders.
- Image Handling: The custom ReplaceTextWithImage method locates a text placeholder and substitutes it with an image.
- Document Saving: The modified document is saved with a new filename.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace CreateWordByReplacingTextPlaceholders
{
class Program
{
static void Main(string[] args)
{
// Initialize a new Document object
Document document = new Document();
// Load the template Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");
// Dictionary to hold text placeholders and their replacements
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "#name#", "John Doe" },
{ "#gender#", "Male" },
{ "#birthdate#", "January 15, 1990" },
{ "#address#", "123 Main Street" },
{ "#city#", "Springfield" },
{ "#state#", "Illinois" },
{ "#postal#", "62701" },
{ "#country#", "United States" }
};
// Replace placeholders in the document with corresponding values
foreach (KeyValuePair<string, string> kvp in replaceDict)
{
document.Replace(kvp.Key, kvp.Value, true, true);
}
// Path to the image file
String imagePath = "C:\\Users\\Administrator\\Desktop\\portrait.png";
// Replace the placeholder “#photo#” with an image
ReplaceTextWithImage(document, "#photo#", imagePath);
// Save the modified document
document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx);
// Release resources
document.Dispose();
}
// Method to replace a placeholder in the document with an image
static void ReplaceTextWithImage(Document document, String stringToReplace, String imagePath)
{
// Load the image from the specified path
Image image = Image.FromFile(imagePath);
DocPicture pic = new DocPicture(document);
pic.LoadImage(image);
// Find the placeholder in the document
TextSelection selection = document.FindString(stringToReplace, false, true);
// Get the range of the found text
TextRange range = selection.GetAsOneRange();
int index = range.OwnerParagraph.ChildObjects.IndexOf(range);
// Insert the image and remove the placeholder text
range.OwnerParagraph.ChildObjects.Insert(index, pic);
range.OwnerParagraph.ChildObjects.Remove(range);
}
}
}

Create a Word Document By Replacing Bookmark Content
The BookmarksNavigator class in Spire.Doc is specifically designed to manage and navigate through bookmarks in a Word document. This class simplifies the process of finding and replacing content in bookmarks, making it easy to update sections of a document without manually searching for each bookmark.
The following are the steps for Word generation using bookmark content replacement:
- Document Initialization: Create a new Document object and load the template file.
- Bookmark Content Definitions: Create a dictionary mapping bookmark names to their replacement content.
- Bookmark Navigation: The BookmarksNavigator class provides precise control over bookmark locations.
- Content Replacement: The ReplaceBookmarkContent method preserves the bookmark while updating its content.
- Document Saving: The modified document is saved with a new filename.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
namespace CreateWordByReplacingBookmarkContent
{
class Program
{
static void Main(string[] args)
{
// Initialize a new Document object
Document document = new Document();
// Load the template Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");
// Define bookmark names and their replacement values
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "name", "Tech Innovations Inc." },
{ "year", "2015" },
{ "headquarter", "San Francisco, California, USA" },
{ "history", "Tech Innovations Inc. was founded by a group of engineers and " +
"entrepreneurs with a vision to revolutionize the technology sector. Starting " +
"with a focus on software development, the company expanded its portfolio to " +
"include artificial intelligence and cloud computing solutions." }
};
// Create a BookmarksNavigator to manage bookmarks in the document
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
// Replace each bookmark's content with the corresponding value
foreach (KeyValuePair<string, string> kvp in replaceDict)
{
bookmarkNavigator.MoveToBookmark(kvp.Key); // Navigate to bookmark
bookmarkNavigator.ReplaceBookmarkContent(kvp.Value, true); // Replace content
}
// Save the modified document
document.SaveToFile("ReplaceBookmarkContent.docx", FileFormat.Docx2013);
// Release resources
document.Dispose();
}
}
}

Conclusion
Both approaches provide effective ways to generate documents from templates, but with important differences:
- Text Replacement Method:
- Permanently removes placeholders during replacement
- Best for one-time document generation
- Better suited for replacing text with images
- Bookmark Replacement Method:
- Preserves bookmarks for future updates
- Ideal for templates requiring periodic updates
Additionally, Spire.Doc for .NET supports Mail Merge functionality, which provides another powerful way to dynamically generate documents from templates. This feature is particularly useful for creating personalized documents in bulk, such as form letters or reports, where data comes from a database or other structured source.
Get a Free License
To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.
Microsoft Excel is a powerful tool for data management; however, its proprietary format can pose challenges for sharing and integrating data into web workflows. In contrast, Markdown is a lightweight and widely supported markup language that simplifies text formatting for documentation, wikis, and platforms like GitHub.
By converting Excel files to Markdown, you can seamlessly incorporate structured data into technical documents, READMEs, and static websites. This article will guide you through the steps to programmatically convert Excel files to Markdown format using C# and the Spire.XLS for .NET library.
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
Convert an Excel XLS or XLSX File to Markdown in C#
Developers can effortlessly convert Excel XLS or XLSX files to Markdown files by using the Workbook.SaveToMarkdown() method provided by Spire.XLS for .NET. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load a sample Excel XLS or XLSX file into the Workbook object using the Workbook.LoadFromFile() method.
- Save the Excel file as a Markdown file using the Workbook.SaveToMarkdown() method.
- C#
using Spire.Xls;
namespace ConvertExcelToMarkdown
{
internal class Program
{
static void Main(string[] args)
{
// Create an object of the Workbook class
Workbook workbook = new Workbook();
// Load a sample Excel XLS file
//workbook.LoadFromFile("Sample.xls");
// Load a sample Excel XLSX file
workbook.LoadFromFile("Sample.xlsx");
// Save the Excel file as a Markdown file
workbook.SaveToMarkdown("output.md");
// Release the resources used by the Workbook object
workbook.Dispose();
}
}
}

Get a Free License
To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.
When working with Word documents, batch extraction of hyperlinks has significant practical applications. Manually extracting URLs from technical documents or product manuals is not only inefficient but also prone to omissions and errors. To address this, this article presents an automated solution using C# to accurately extract hyperlink anchor text, corresponding URLs, and screen tips by parsing document elements. The extracted hyperlink data can support data analysis, SEO optimization, and other applications. The following sections demonstrate how to use Spire.Doc for .NET to extract hyperlinks from a Word document with C# code in .NET programs.
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
Extracting All Hyperlinks from a Word Document Using C#
In a Word document, hyperlinks are stored as fields. To extract them, the first step is to identify all field objects by checking whether each document object is an instance of the Field class. Then, by checking whether the field object's Type property equals FieldType.FieldHyperlink, we can extract all hyperlink fields.
Once the hyperlinks are identified, we can use the Field.FieldText property to retrieve the hyperlink anchor text and the Field.GetFieldCode() method to obtain the full field code in the following format:
| Hyperlink Type | Field Code Example |
| Standard Hyperlink | HYPERLINK "https://www.example.com/example" |
| Hyperlink with ScreenTip | HYPERLINK "https://www.example.com/example" \o "ScreenTip" |
By parsing the field code, we can extract both the hyperlink URL and the screen tip text, enabling complete retrieval of hyperlink information.
- Create a Document object and use the Document.LoadFromFile() method to load the target Word document.
- Iterate through all sections in the document using foreach (Section section in doc.Sections) to retrieve each section object.
- For each section, iterate through its child objects using foreach (DocumentObject secObj in section.Body.ChildObjects) to access individual elements.
- If a child object is of type Paragraph:
- Iterate through the child objects within the paragraph using foreach (DocumentObject paraObj in paragraph.ChildObjects).
- If a paragraph child object is of type Field and its Field.Type property value equals FieldType.FieldHyperlink, process the Field object.
- For each Field object:
- Extract the anchor text using the Field.FieldText property.
- Retrieve the field code string using the Field.GetFieldCode() method.
- Process the field code string:
- Extract the URL enclosed in quotation marks after "HYPERLINK".
- Check if the field code contains the \o parameter; if present, extract the screen tip text enclosed in double quotes.
- Store the extracted hyperlinks and write them to an output file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ExtractWordHyperlink
{
class Program
{
static void Main(string[] args)
{
// Create an instance of Document
Document doc = new Document();
// Load a Word document
doc.LoadFromFile("Sample.docx");
// Create a string list to store the hyperlink information
List<string> hyperlinkInfoList = new List<string>();
// Iterate through the sections in the document
foreach (Section section in doc.Sections)
{
// Iterate through the child objects in the section
foreach (DocumentObject secObj in section.Body.ChildObjects)
{
// Check if the current document object is a Paragraph instance
if (secObj is Paragraph paragraph )
{
// Iterate through the child objects in the paragraph
foreach (DocumentObject paraObj in paragraph.ChildObjects)
{
// Check if the current child object is a field
if (paraObj is Field field && field.Type == FieldType.FieldHyperlink)
{
string hyperlinkInfo = "";
// Get the anchor text
string anchorText = field.FieldText;
// Get the field code
string fieldCode = field.GetFieldCode();
// Get the URL from the field code
string url = fieldCode.Split('"')[1];
// Check if there is a ScreenTip
if (fieldCode.Contains("\\o"))
{
// Get the ScreenTip text
string screenTip = fieldCode.Split("\"")[3].Trim();
// Consolidate the information
hyperlinkInfo += $"Anchor Text: {anchorText}\nURL: {url}\nScreenTip: {screenTip}";
}
else
{
hyperlinkInfo += $"Anchor Text: {anchorText}\nURL: {url}";
}
hyperlinkInfo += "\n";
// Append the hyperlink information to the list
hyperlinkInfoList.Add(hyperlinkInfo);
}
}
}
}
}
// Write the extracted hyperlink information to a text file
File.WriteAllLines("output/ExtractedHyperlinks.txt", hyperlinkInfoList);
doc.Close();
}
}
}

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.
When printing a PDF, ensuring the content appears as intended is crucial. Depending on your needs, you may want to print the document at the actual size to maintain the original dimensions or scale it to fit the entire page for a better presentation.

To accommodate different printing needs, Spire.PDF for .NET provides flexible printing options that allow developers to control the output easily. This article will demonstrate how to print a PDF either at the actual size or fit to page in C# using the Spire.PDF for .NET library.
- Print a PDF to Fit the Page Size in C#
- Print a PDF at the Actual Size in C#
- Print a PDF at the Actual Size on Custom-Sized Paper
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 DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Print a PDF to Fit the Page Size in C#
When printing a PDF to fit the page, the content is automatically scaled to match the dimensions of the paper. This ensures that the document fits within the printed area, regardless of its original size.
To fit the content to the page, you can use the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method. The detailed steps are as follows.
- Create an instance of the PdfDocument class.
- Load the PDF file using the PdfDocument.LoadFromFile() method.
- Configure print settings to scale the PDF to fit the page size for printing using the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method.
- Call the PdfDocument.Print() method to print the PDF file.
- C#
using Spire.Pdf;
using Spire.Pdf.Print;
namespace PrintPdfToFitPageSize
{
internal class Program
{
static void Main(string[] args)
{
// Create an instance of the PdfDocument class
PdfDocument pdf = new PdfDocument();
// Load the specified PDF file into the PdfDocument object
pdf.LoadFromFile("Sample.pdf");
// Configure print settings to scale the PDF to fit the page size for printing
pdf.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode.FitSize, false);
// Execute the print command to print the loaded PDF document
pdf.Print();
}
}
}
Print a PDF at the Actual Size in C#
When printing a PDF at the actual size, the original document dimensions are preserved without scaling. This ensures that the printed output matches the PDF's defined measurements.
To print a PDF at its actual size, you can also use the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method. The detailed steps are as follows.
- Create an instance of the PdfDocument class.
- Load the PDF file using the PdfDocument.LoadFromFile() method.
- Configure print settings to print the PDF at its actual size without scaling using the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method.
- Call the PdfDocument.Print() method to print the PDF file.
- C#
using Spire.Pdf;
using Spire.Pdf.Print;
using System.Drawing.Printing;
namespace PrintPdfAtActualSize
{
internal class Program
{
static void Main(string[] args)
{
// Create a new instance of the PdfDocument class
PdfDocument pdf = new PdfDocument();
// Load the PDF file into the PdfDocument object
pdf.LoadFromFile("Sample.pdf");
// Set paper margins as 0
pdf.PrintSettings.SetPaperMargins(0, 0, 0, 0);
// Configure print settings to print the PDF at its actual size without scaling
pdf.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode.ActualSize, false);
// Execute the print command to print the loaded PDF document
pdf.Print();
}
}
}
Print a PDF at the Actual Size on Custom-Sized Paper
In some cases, you may need to print a PDF at its actual size on a specific size of paper. Spire.PDF allows you to define a custom paper size using the PaperSize class and then you can assign it to the print settings of the document using the PdfDocument.PrintSettings.PaperSize property. The detailed steps are as follows.
- Create an instance of the PdfDocument class.
- Load the PDF file using the PdfDocument.LoadFromFile() method.
- Define a custom paper size for printing using the PaperSize class.
- Assign the custom paper size to the print settings of the file using the using the PdfDocument.PrintSettings.PaperSize property.
- Configure print settings to print the PDF at its actual size without scaling using the PdfDocument.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode pageScalingMode, bool autoPortraitOrLandscape) method.
- Call the PdfDocument.Print() method to print the PDF file.
- C#
using Spire.Pdf;
using Spire.Pdf.Print;
using System.Drawing.Printing;
namespace PrintPdfOnCustomSizedPaper
{
internal class Program
{
static void Main(string[] args)
{
// Create a new instance of the PdfDocument class
PdfDocument pdf = new PdfDocument();
// Load the specified PDF file into the PdfDocument object
pdf.LoadFromFile("Sample.pdf");
//// Define an A3 paper size for printing
//PaperSize paperSize = new PaperSize
//{
// // Set paper size to A3
// RawKind = (int)PaperKind.A3
//};
// Define a custom paper size for printing
PaperSize paperSize = new PaperSize
{
// Set the width of the paper
Width = 283 * 100, //inch*100
// Set the height of the paper
Height = 826 * 100, //inch*100
// Set paper size to custom
RawKind = (int)PaperKind.Custom
};
// Assign the custom paper size to the print settings of the PdfDocument
pdf.PrintSettings.PaperSize = paperSize;
// Set paper margins as 0
pdf.PrintSettings.SetPaperMargins(0, 0, 0, 0);
// Set print settings to print the PDF at its actual size without scaling
pdf.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode.ActualSize, false);
// Execute the print command to print the loaded PDF document
pdf.Print();
}
}
}
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.