How to Convert HTML to Excel in C#
How to Convert HTML to Excel in C#
Need to load an HTML string or webpage into Excel for processing, visualization, or storage? This guide explains how to convert HTML content directly to an Excel workbook using Aspose.Cells for .NET.
Use Cases for HTML to Excel Conversion
- Convert email or CMS data into Excel
- Process HTML reports or exports from third-party platforms
- Import web tables into structured spreadsheets
Step-by-Step Guide
Step 1: Install Aspose.Cells for .NET
dotnet add package Aspose.Cells
Step 2: Prepare HTML as a String
string htmlString = "<html><body><table><tr><td>Item</td><td>Price</td></tr><tr><td>Book</td><td>20</td></tr></table></body></html>";
Step 3: Convert String to Stream
using (MemoryStream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlString)))
Step 4: Load HTML Stream with HtmlLoadOptions
Workbook workbook = new Workbook(htmlStream, new HtmlLoadOptions());
Step 5: Work With the Workbook (Optional)
Worksheet sheet = workbook.Worksheets[0];
// Add formulas, styles, or modify data
Step 6: Save the Resulting Excel File
workbook.Save("converted.xlsx", SaveFormat.Xlsx);
Complete Code Example
using System;
using System.IO;
using System.Text;
using Aspose.Cells;
class Program
{
static void Main()
{
string html = "<html><body><table><tr><td>Name</td><td>Score</td></tr><tr><td>Alice</td><td>92</td></tr></table></body></html>";
using (MemoryStream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(html)))
{
Workbook workbook = new Workbook(htmlStream, new HtmlLoadOptions());
// Optional: Modify the data or format
Worksheet sheet = workbook.Worksheets[0];
sheet.AutoFitColumns();
workbook.Save("html_to_excel.xlsx");
}
Console.WriteLine("HTML converted to Excel.");
}
}
Best Practices
Practice | Benefit |
---|---|
Use streams for web integration | Easier to handle in APIs |
Use HtmlLoadOptions | Customize parsing or handle advanced HTML content |
Auto-fit columns | Improve readability of output |