Come convertire HTML in Excel in C#

Come convertire HTML in 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>Elemento</td><td>Prezzo</td></tr><tr><td>Libro</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];
// Aggiungi formule, stili o modifica i dati

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>Nome</td><td>Punteggio</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());

            // Opzionale: Modifica i dati o il formato
            Worksheet sheet = workbook.Worksheets[0];
            sheet.AutoFitColumns();

            workbook.Save("html_to_excel.xlsx");
        }

        Console.WriteLine("HTML convertito in Excel.");
    }
}

Best Practices

PracticeBenefit
Usa stream per integrazione webPiù facile da gestire nelle API
Usa HtmlLoadOptionsPersonalizza il parsing o gestisci contenuti HTML avanzati
Adatta automaticamente le colonneMigliora la leggibilità dell’output
 Italiano