How to Convert Excel to HTML in C#
How to Convert Excel to HTML in C#
Exporting Excel data to HTML format is essential when displaying spreadsheet content in browsers, email templates, or web applications. This guide shows how to convert an Excel workbook to HTML using Aspose.Cells for .NET.
When to Use Excel to HTML Conversion
- Generate previews of Excel data on websites
- Enable web-based spreadsheet viewing
- Embed tabular data in CMS or blogs
Step-by-Step Guide
Step 1: Install Aspose.Cells for .NET
dotnet add package Aspose.Cells
Step 2: Load the Workbook
Workbook workbook = new Workbook("path/to/excel.xlsx");
Step 3: Set HTML Save Options (Optional)
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
Step 4: Export Excel to HTML File
workbook.Save("path/to/output.html", options);
Step 5: Save to a MemoryStream Instead of a File
using (MemoryStream outputStream = new MemoryStream())
{
workbook.Save(outputStream, SaveFormat.Html);
outputStream.Position = 0;
// Use the stream in a web response, save to disk, etc.
}
Complete Code Example
using System;
using System.IO;
using Aspose.Cells;
class Program
{
static void Main()
{
Workbook workbook = new Workbook("input.xlsx");
// Option 1: Save to HTML file
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
workbook.Save("output.html", options);
// Option 2: Save to stream for web applications
using (MemoryStream stream = new MemoryStream())
{
workbook.Save(stream, SaveFormat.Html);
stream.Position = 0;
// Use the stream as needed (e.g., send in API response)
}
Console.WriteLine("Excel exported to HTML.");
}
}
Tips and Best Practices
Tip | Description |
---|---|
Use HtmlSaveOptions | Fine-tune output HTML structure, character encoding, or image embedding |
Save to stream | Useful for APIs or serverless functions |
Preserve styling | Aspose.Cells ensures most styling and layout elements are retained |