Knowledgebase (2613)
Children categories
How to Generate QR Codes in Python (Full Tutorial with Examples)
2025-07-15 02:49:34 Written by zaki zaki
QR codes have transformed how we bridge physical and digital experiences—from marketing campaigns to secure data sharing. For developers looking to generate QR codes in Python , Spire.Barcode for Python provides a complete toolkit for seamless QR code generation, offering both simplicity for basic needs and advanced customization for professional applications.
This step-by-step guide walks you through the entire QR code generation process in Python. You'll learn to programmatically create scannable codes, customize their appearance, embed logos, and optimize error correction - everything needed to implement robust QR code generation solutions for any business or technical requirement.
Table of Contents
- Introduction to Spire.Barcode for Python
- Setting Up the Environment
- Basic Example: Generating QR Codes in Python
- Customizing QR Code Appearance
- Generating QR Code with Logo
- Wrapping up
- FAQs
1. Introduction to Spire.Barcode for Python
Spire.Barcode for Python is a powerful library that enables developers to generate and read various barcode types, including QR codes, in Python applications. This robust solution supports multiple barcode symbologies while offering extensive customization options for appearance and functionality.
Key features of Spire.Barcode include:
- Support for QR Code generation with customizable error correction levels
- Flexible data encoding options (numeric, alphanumber, byte/binary)
- Comprehensive appearance customization (colors, sizes, fonts)
- High-resolution output capabilities
- Logo integration within QR codes
2. Setting Up the Environment
Before we dive into generating QR codes, you need to set up your Python environment. Ensure you have Python installed, and then install the Spire.Barcode library using pip:
pip install spire.barcode
For the best results, obtain a free temporary license from our website. This will allow you to create professional QR code images without evaluation messages, enhancing both user experience and quality of the generated codes.
3. Basic Example: Generating QR Codes in Python
Now that we have everything set up, let's generate our first QR code. Below is the step-by-step process:
-
Initial Setup :
- Import the Spire.Barcode library.
- Activate the library with a valid license key to remove the
-
Configure Barcode Settings :
- Create a BarcodeSettings object to control QR code properties.
- Set barcode type to QR code.
- Configure settings such as data mode and error correction level.
- Define the content to encode.
- Configure visual aspects like module width and text display options.
-
Generate Barcode Image :
- Create a BarCodeGenerator object with the configured settings.
- Convert the configured QR code into an image object in memory.
-
Save Image to File :
- Write the generated QR code image to a specified file path in PNG format.
The following code snippet demonstrates how to generate QR codes in Python:
from spire.barcode import *
# Function to write all bytes to a file
def WriteAllBytes(fname: str, data):
with open(fname, "wb") as fp:
fp.write(data)
fp.close()
# Apply license key for the barcode generation library
License.SetLicenseKey("your license key")
# Create a BarcodeSettings object to configure barcode properties
barcodeSettings = BarcodeSettings()
# Set the type of barcode to QR code
barcodeSettings.Type = BarCodeType.QRCode
# Set the data mode for QR code (automatic detection of data type)
barcodeSettings.QRCodeDataMode = QRCodeDataMode.Auto
# Set the error correction level (M means medium level of error correction)
barcodeSettings.QRCodeECL = QRCodeECL.M
# Set the data that will be encoded in the QR code
barcodeSettings.Data2D = "visit us at www.e-iceblue.com"
# Set the width of each module (the square bars) in the barcode
barcodeSettings.X = 3
# Hide the text that typically accompanies the barcode
barcodeSettings.ShowText = False
# Create a BarCodeGenerator object with the specified settings
barCodeGenerator = BarCodeGenerator(barcodeSettings)
# Generate the image for the barcode based on the settings
image = barCodeGenerator.GenerateImage()
# Write the generated PNG image to disk at the specified path
WriteAllBytes("output/QRCode.png", image)
Key Concepts:
A. QRCodeDataMode (Data Encoding Scheme)
Controls how the input data is encoded in the QR code:
| Mode | Best For | Example Use Cases |
|---|---|---|
| Auto | Let library detect automatically | General purpose (default choice) |
| Numeric | Numbers only (0-9) | Product codes, phone numbers |
| AlphaNumber | A-Z, 0-9, and some symbols | URLs, simple messages |
| Byte | Binary/Unicode data | Complex text, special characters |
Why it matters:
- Different modes have different storage capacities.
- Numeric mode can store more digits than other modes.
- Auto mode is safest for mixed content.
B. QRCodeECL (Error Correction Level)
Determines how much redundancy is built into the QR code:
| Level | Recovery Capacity | Use Case |
|---|---|---|
| L (Low) | 7% damage recovery | Small codes, short URLs |
| M (Medium) | 15% damage recovery | General purpose (recommended) |
| Q (Quartile) | 25% damage recovery | Codes with logos or decorations |
| H (High) | 30% damage recovery | Critical applications |
Visual Impact:
Higher ECLs:
- Increase QR code complexity (more modules/squares).
- Make the code more scannable when damaged.
- Are essential when adding logos (use at least Q or H).
Output:

4. Customizing QR Code Appearance
Once you've generated a basic QR code, you can further customize its appearance to make it more visually appealing or to fit your brand. Here are some customization options:
4.1 Adjusting DPI Settings
The DPI (dots per inch) settings control the image quality of the QR code. Higher DPI values result in sharper images suitable for printing, while lower values (72-150) are typically sufficient for digital use.
barcodeSettings.DpiX = 150
barcodeSettings.DpiY = 150
4.2 Changing Foreground and Background Colors
You can customize your QR code’s color scheme. The ForeColor determines the color of the QR code modules (squares), while BackColor sets the background color. Ensure sufficient contrast for reliable scanning.
barcodeSettings.BackColor = Color.get_GhostWhite()
barcodeSettings.ForeColor = Color.get_Purple()
4.3 Displaying the Encoded Data
If you want users to see the encoded information without scanning, set the following properties:
barcodeSettings.ShowTextOnBottom = True
barcodeSettings.TextColor = Color.get_Purple()
barcodeSettings.SetTextFont("Arial", 13, FontStyle.Bold)
4.4 Adding Text Under QR Code
You can also add custom text under the QR code, which could be a call-to-action or instructions.
barcodeSettings.ShowBottomText = True
barcodeSettings.BottomText = "Scan Me"
barcodeSettings.SetBottomTextFont("Arial", 13, FontStyle.Bold)
barcodeSettings.BottomTextColor = Color.get_Black()
4.5 Setting Margins and Border
Defining margins and border styles enhances the presentation of the QR code. Here’s how to do it:
barcodeSettings.LeftMargin = 2
barcodeSettings.RightMargin = 2
barcodeSettings.TopMargin = 2
barcodeSettings.BottomMargin = 2
barcodeSettings.HasBorder = True
barcodeSettings.BorderWidth = 0.5
barcodeSettings.BorderColor = Color.get_Black()
5. Generating QR Code with Logo
For branding purposes, you might want to add a logo to your QR code. Spire.Barcode makes this process seamless while maintaining scannability. Here’s how:
barcodeSettings.SetQRCodeLogoImage("C:\\Users\\Administrator\\Desktop\\logo.png")
When adding a logo:
- Use a simple, high-contrast logo for best results.
- Test the scannability after adding the logo.
- The QR code's error correction (set earlier) helps compensate for the obscured area.
The logo will be centered within the QR code, and Spire.Barcode will automatically resize it to ensure the QR code remains scannable.
Output:

6. Wrapping up
Generating QR codes in Python using Spire.Barcode is a straightforward process that offers extensive customization options. From basic QR codes to branded versions with logos and custom styling, the library provides all the tools needed for professional barcode generation.
Key Benefits:
- Spire.Barcode simplifies QR code generation with a clean API.
- Extensive customization options allow for branded, visually appealing QR codes.
- Error correction ensures reliability even with added logos.
- High-resolution output supports both digital and print use cases.
Whether you're building an inventory system, creating marketing materials, or developing a mobile app integration, Spire.Barcode provides a robust solution for all your QR code generation needs in Python.
7. FAQs
Q1: What is a QR code?
A QR code (Quick Response code) is a type of matrix barcode that can store URLs and other information. It is widely used for quickly linking users to websites, apps, and digital content through mobile devices.
Q2: Can I generate QR codes without a license key?
Yes, you can generate QR codes without a license key; however, the generated barcode will display an evaluation message along with our company logo, which may detract from the user experience.
Q3: Can I generate different types of barcodes with Spire.Barcode?
Yes, Spire.Barcode supports various barcode types, not just QR codes. Detailed documentation can be found here: How to Generate Barcode in Python
Q4: How can I implement a QR code generator in Python using Spire.Barcode?
To implement a QR code generator in Python with Spire.Barcode, create a BarcodeSettings object to configure the QR code properties. Then, use the BarCodeGenerator class to generate the QR code image by calling the GenerateImage() method.
Q5: Can I scan or read QR code using Spire.Barcode?
Yes, you can scan and read QR codes using Spire.Barcode for Python. The library provides functionality for both generating and decoding QR codes. Follow this guide: How to Read Barcode Using Python
Get a Free License
To fully experience the capabilities of Spire.Barcode for Python without any evaluation limitations, you can request a free 30-day trial license.
How to Add Text to PDF in Python (Create & Edit with Examples)
2025-07-10 08:51:40 Written by zaki zaki
Adding text to a PDF is a common task in Python — whether you're generating reports, adding annotations, filling templates, or labeling documents. This guide will walk you through how to write text in a PDF file using Python, including both creating new PDF documents and updating existing ones.
We’ll be using a dedicated Python PDF library - Spire.PDF for Python, which allows precise control over text placement, font styling, and batch processing. The examples are concise, beginner-friendly, and ready for real-world projects.
Sections Covered
- Setup: Install the PDF Library in Python
- Add Text to a New PDF
- Add Text to an Existing PDF
- Control Text Style, Position, Transparency, and Rotation
- Common Pitfalls and Cross-Platform Tips
- Conclusion
- FAQ
Setup: Install the PDF Library in Python
To get started, install Spire.PDF for Python, a flexible and cross-platform PDF library.
pip install Spire.PDF
Or use Free Spire.PDF for Python:
pip install spire.pdf.free
Why use this library?
- Works without Adobe Acrobat or Microsoft Office
- Add and format text at exact positions
- Supports both new and existing PDF editing
- Runs on Windows, macOS, and Linux
Add Text to a New PDF Using Python
If you want to create a PDF from text using Python, the example below shows how to insert a line of text into a blank PDF page using custom font and position settings.
Example: Create and write text to a blank PDF
from spire.pdf import PdfDocument, PdfTrueTypeFont, PdfFontStyle, PdfSolidBrush, PdfRGBColor, PointF, RectangleF, \
PdfStringFormat, PdfTextAlignment, PdfVerticalAlignment
# Create a new PDF document and add a new page
pdf = PdfDocument()
page = pdf.Pages.Add()
text = ("This report summarizes the sales performance of various products in the first quarter of 2025. " +
"Below is a breakdown of the total sales by product category, " +
"followed by a comparison of sales in different regions.")
# Set the font, brush, and point
font = PdfTrueTypeFont("Arial", 14.0, PdfFontStyle.Regular, True)
brush = PdfSolidBrush(PdfRGBColor(0, 0, 0)) # black
point = PointF(50.0, 100.0)
# Set the layout area and string format
layoutArea = RectangleF(50.0, 50.0, page.GetClientSize().Width - 100.0, page.GetClientSize().Height)
stringFormat = PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Top)
page.Canvas.DrawString(text, font, brush, layoutArea, stringFormat, False)
pdf.SaveToFile("output/new.pdf")
pdf.Close()
Technical Notes
- PdfTrueTypeFont() loads a TrueType font from the system with customizable size and style (e.g., regular, bold). It ensures consistent text rendering in the PDF.
- PdfSolidBrush() defines the fill color for text or shapes using RGB values. In this example, it's set to black ((0, 0, 0)).
- RectangleF(x, y, width, height) specifies a rectangular layout area for drawing text. It enables automatic line wrapping and precise control of text boundaries.
- PdfStringFormat() controls the alignment of the text inside the rectangle. Here, text is aligned to the top-left (Left and Top).
- DrawString() draws the specified text within the defined layout area without affecting existing content on the page.
Example output PDF showing wrapped black text starting at coordinates (50, 50).

Tip: To display multiple paragraphs or line breaks, consider adjusting the Y-coordinate dynamically or using multiple DrawString() calls with updated positions.
If you want to learn how to convert TXT files to PDF directly using Python, please check: How to Convert Text Files to PDF Using Python.
Add Text to an Existing PDF in Python
Need to add text to an existing PDF using Python? This method lets you load a PDF, access a page, and write new text anywhere on the canvas.
This is helpful for:
- Adding comments or annotations
- Labeling document versions
- Filling pre-designed templates
Example: Open an existing PDF and insert text
from spire.pdf import PdfDocument, PdfFontStyle, PdfSolidBrush, PdfRGBColor, PointF, PdfFont, PdfFontFamily
pdf = PdfDocument()
pdf.LoadFromFile("input.pdf")
page = pdf.Pages.get_Item(0)
font = PdfFont(PdfFontFamily.TimesRoman, 12.0, PdfFontStyle.Bold)
brush = PdfSolidBrush(PdfRGBColor(255, 0, 0)) # red
location = PointF(150.0, 110.0)
page.Canvas.DrawString("This document is approved.", font, brush, location)
pdf.SaveToFile("output/modified.pdf")
pdf.Close()
Technical Notes
- LoadFromFile() loads an existing PDF into memory.
- You can access specific pages via pdf.Pages[index].
- New content is drawn on top of the existing layout, non-destructively.
- The text position is again controlled via PointF(x, y).
Modified PDF page with newly added red text annotation on the first page.

Use different x, y coordinates to insert content at custom positions.
Related article: Replace Text in PDF with Python
Control Text Style, Positioning, Transparency, and Rotation
When adding text to a PDF, you often need more than just plain content—you may want to customize the font, color, placement, rotation, and transparency, especially for annotations or watermarks.
Spire.PDF for Python offers fine-grained control for these visual elements, whether you’re building structured reports or stamping dynamic text overlays.
Set Font Style and Color
# Create PdfTrueTypeFont
font = PdfTrueTypeFont("Calibri", 16.0, PdfFontStyle.Italic, True)
# Create PdfFont
font = PdfFont(PdfFontFamily.TimesRoman, 16.0, PdfFontStyle.Italic)
# Create PdfBrush to specify text drawing color
brush = PdfSolidBrush(PdfRGBColor(34, 139, 34)) # forest green
PdfTrueTypeFont will embed the font into the PDF file. To reduce file size, you may use PdfFont, which uses system fonts without embedding them.
Apply Transparency and Rotation
You can adjust transparency and rotation when drawing text to achieve effects like watermarks or angled labels.
# Save the current canvas state
state = page.Canvas.Save()
# Set semi-transparency (0.0 = fully transparent, 1.0 = fully opaque)
page.Canvas.SetTransparency(0.4)
# Move the origin to the center of the page
page.Canvas.TranslateTransform(page.Size.Width / 2, page.Size.Height / 2)
# Rotate the canvas -45 degrees (counterclockwise)
page.Canvas.RotateTransform(-45)
# Draw text at new origin
page.Canvas.DrawString("DRAFT", font, brush, PointF(-50, -20))
Example: Add a Diagonal Watermark to the Center of the Page
The following example demonstrates how to draw a centered, rotated, semi-transparent watermark using all the style controls above:
from spire.pdf import PdfDocument, PdfTrueTypeFont, PdfFontStyle, PdfSolidBrush, PdfRGBColor, PointF
from spire.pdf.common import Color
pdf = PdfDocument()
pdf.LoadFromFile("input1.pdf")
page = pdf.Pages.get_Item(0)
text = "Confidential"
font = PdfTrueTypeFont("Arial", 40.0, PdfFontStyle.Bold, True)
brush = PdfSolidBrush(PdfRGBColor(Color.get_DarkBlue())) # gray
# Measure text size to calculate center
size = font.MeasureString(text)
x = (page.Canvas.ClientSize.Width - size.Width) / 2
y = (page.Canvas.ClientSize.Height - size.Height) / 2
state = page.Canvas.Save()
page.Canvas.SetTransparency(0.3)
page.Canvas.TranslateTransform(x + size.Width / 2, y + size.Height / 2)
page.Canvas.RotateTransform(-45.0)
page.Canvas.DrawString(text, font, brush, PointF(-size.Width / 2, -size.Height / 2))
page.Canvas.Restore(state)
pdf.SaveToFile("output/with_watermark.pdf")
pdf.Close()
PDF page displaying a centered, rotated, semi-transparent watermark text.

This approach works well for dynamic watermarking, diagonal stamps like "VOID", "COPY", or "ARCHIVED", and supports full automation.
Make sure all files are closed and not in use to avoid PermissionError.
For more details on inserting watermarks into PDF with Python, please refer to: How to Insert Text Watermarks into PDFs Using Python.
Common Pitfalls and Cross-Platform Considerations
Even with the right API, issues can arise when deploying PDF text operations across different environments or font configurations. Here are some common problems and how to resolve them:
| Issue | Cause | Recommended Fix |
|---|---|---|
| Text appears in wrong position | Hardcoded coordinates not accounting for page size | Use ClientSize and MeasureString() for dynamic layout |
| Font not rendered | Font lacks glyphs or isn't supported | Use PdfTrueTypeFont to embed supported fonts like Arial Unicode |
| Unicode text not displayed | Font does not support full Unicode range | Use universal fonts (e.g., Arial Unicode, Noto Sans) |
| Text overlaps existing content | Positioning too close to body text | Adjust Y-offsets or add padding with MeasureString() |
| Watermark text appears on output | You are using the paid version without a license | Use the free version or apply for a temporary license |
| Font file too large | Embedded font increases PDF size | Use PdfFont for system fonts (non-embedded), if portability is not a concern |
| Inconsistent results on macOS/Linux | Fonts not available or different metrics | Ship fonts with your application, or use built-in cross-platform fonts |
Conclusion
With Spire.PDF for Python, adding text to PDFs—whether creating new files, updating existing ones, or automating batch edits—can be done easily and precisely. From annotations to watermarks, the library gives you full control over layout and styling.
You can start with the free version right away, or apply for a temporary license to unlock full features.
FAQ
How to add text to a PDF using Python?
Use a PDF library such as Spire.PDF to insert text via the DrawString() method. You can define font, position, and styling.
Can I write text into an existing PDF file with Python?
Yes. Load the file with LoadFromFile(), then use DrawString() to add text at a specific location.
How do I generate a PDF from text using Python?
Create a new document and use drawing methods to write content line by line with precise positioning.
Can I add the same text to many PDFs automatically?
Yes. Use a loop to process multiple files and insert text programmatically using a template script.
Generate Excel File in C# – Create and Export in .NET & ASP.NET
2025-07-09 09:37:39 Written by zaki zaki
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.