È necessario caricare una stringhe HTML o una pagina web in Excel per il trattamento, la visualizzazione o lo storage?Questo manuale spiega come convertire il contenuto HTML direttamente in un libretto di lavoro Excel utilizzando Aspose.Cells per .NET.

Introduzione

Convertire i dati HTML in Excel può essere un compito impegnativo a causa della complessità delle strutture HTML e della necessità di formattamento accurato nell’Excel. tuttavia, con Aspose.Cells per .NET, questo processo diventa semplice ed efficiente.

Questo articolo vi accompagnerà attraverso i passaggi necessari per convertire una stringhe HTML o file in un libretto di lavoro di Excel utilizzando C#. Ci copriremo tutto dall’installazione del pacchetto necessario per salvare il risultato finale come un .xlsx Il file.

Utilizzare i casi per la conversione HTML a Excel

  • Convertire i dati di e-mail o CMS in Excel
  • Processare i rapporti HTML o le esportazioni da piattaforme di terze parti
  • Importare tabelle web in schede di diffusione strutturate

Guida passo dopo passo

Passo 1: Installare Aspose.Cells per .NET

$ dotnet add package Aspose.Cells

Passo 2: Preparare HTML come stringa

Prepara il tuo contenuto HTML da una fonte esterna o direttamente all’interno del codice.

string htmlString = "<html><body><table><tr><td>Item</td><td>Price</td></tr><tr><td>Book</td><td>20</td></tr></table></body></html>";

Passo 3: Convertire String in Stream

Convertire la stringhe HTML in una MemoryStream oggetto, che è necessario per caricare il contenuto HTML.

using (MemoryStream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlString)))
{
    // Proceed with loading the stream into an Excel workbook
}

Passo 4: Caricare il flusso HTML con HtmlLoadOptions

Utilizzo HtmlLoadOptions per caricare il contenuto HTML dal MemoryStream Creare una nuova Workbook Gli oggetti.

using (MemoryStream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlString)))
{
    Workbook workbook = new Workbook(htmlStream, new HtmlLoadOptions());
}

Passo 5: Lavorare con il libro di lavoro (opzionale)

Una volta che il contenuto HTML è caricato in un Workbook, puoi manipolare come necessario. ad esempio, potrebbe voler aggiungere formule o stili.

using (MemoryStream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlString)))
{
    Workbook workbook = new Workbook(htmlStream, new HtmlLoadOptions());
    Worksheet sheet = workbook.Worksheets[0];
    // Add formulas, styles, or modify data
}

Passo 6: Salva il file di Excel

Infine, salvi il modificato Workbook per un file sul disco.

using (MemoryStream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlString)))
{
    Workbook workbook = new Workbook(htmlStream, new HtmlLoadOptions());
    // Optional: Modify the data or format
    Worksheet sheet = workbook.Worksheets[0];
    sheet.AutoFitColumns();
    workbook.Save("converted.xlsx", SaveFormat.Xlsx);
}

Esempio di codice completo

Ecco un esempio completo che dimostra come convertire una stringhe HTML in un file Excel utilizzando Aspose.Cells per .NET.

using System;
using System.IO;
using System.Text;
using Aspose.Cells;

public class HtmlToExcelConverter
{
    public 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());
            Worksheet sheet = workbook.Worksheets[0];
            sheet.AutoFitColumns();
            workbook.Save("html_to_excel.xlsx", SaveFormat.Xlsx);
        }

        Console.WriteLine("HTML converted to Excel.");
    }
}

Migliori pratiche

La praticaIl vantaggio
Utilizzare i flussi per l’integrazione webPiù facile da gestire in API
Utilizzo HtmlLoadOptionsPersonalizzare o gestire contenuti HTML avanzati
Colonne di auto-fitMigliorare la leggibilità della produzione

Titolo: Strutture HTML complesse

Quando si tratta di strutture HTML complesse, è importante utilizzare HtmlLoadOptions Classe per personalizzare come Aspose.Cells parsi il HTML. Questo può includere opzioni di impostazione come ignorare alcuni elementi o gestire specifiche etichette in modo diverso.

using System;
using System.IO;
using System.Text;
using Aspose.Cells;

public class ComplexHtmlToExcelConverter
{
    public static void Main()
    {
        string complexHtml = @"
            <html>
                <body>
                    <table border='1'>
                        <tr>
                            <th>Product</th>
                            <th>Price</th>
                            <th>Quantity</th>
                        </tr>
                        <tr>
                            <td>Laptop</td>
                            <td>$999.99</td>
                            <td>5</td>
                        </tr>
                        <tr>
                            <td>Smartphone</td>
                            <td>$699.99</td>
                            <td>10</td>
                        </tr>
                    </table>
                </body>
            </html>";

        // Create a MemoryStream from the HTML string
        using (MemoryStream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(complexHtml)))
        {
            // Use HtmlLoadOptions to customize parsing if needed
            HtmlLoadOptions loadOptions = new HtmlLoadOptions();
            loadOptions.AutoFilterColumns = true;  // Enable auto-filter for columns

            // Load the HTML content into a Workbook
            Workbook workbook = new Workbook(htmlStream, loadOptions);

            // Access the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Auto-fit all columns to improve readability
            sheet.AutoFitColumns();

            // Save the resulting Excel file
            workbook.Save("complex_html_to_excel.xlsx", SaveFormat.Xlsx);
        }

        Console.WriteLine("Complex HTML converted to Excel.");
    }
}

conclusione

Convertire il contenuto HTML in Excel utilizzando Aspose.Cells per .NET è un potente modo per integrare i dati web nei tuoi flussi di lavoro Excel. Seguendo questo manuale, sarai in grado di gestire sia le strutture HTML semplici e complesse con facilità.

More in this category