News Category

Embed image in HTML when converting Excel to HTML in C#

2014-08-15 08:02:33 Written by  support iceblue
Rate this item
(0 votes)

If you created a pretty Excel table and now want to publish it online as a web page, the simplest way is to export it to an old good HTML file. However a problem may occur if you just simply transform image in Excel to HTML code with a relative link (URL). This way, your web page may no longer display properly on client machines since the image can't be reached through that URL on client-side. In this article, we’re going to resolve this issue by embedding image in HTML code when converting Excel to HTML.

Here is an Excel table with some images embedded in.

Embed image in HTML when converting Excel to HTML

We're able to convert this Excel file to HTML by following below code snippet:

Step 1: Create a new instance of workbook.

Workbook book = new Workbook();
book.LoadFromFile("Book1.xlsx");

Step 2: Embed images into HTML code using Data URI scheme.

HTMLOptions options = new HTMLOptions();
options.ImageEmbedded = true;

Step 3: Save the worksheet to HTML.

book.Worksheets[0].SaveToHtml("sample.html", options);
System.Diagnostics.Process.Start("sample.html");

Output:

Embed image in HTML when converting Excel to HTML

HTML Code:

Since the HTML code is too long to be displayed here, we have to present it by a screenshot.

Embed image in HTML when converting Excel to HTML

Full C# Code:

using Spire.Xls;
using Spire.Xls.Core.Spreadsheet;
namespace CreateWorkbook
{
    class Program
    {
        static void Main(string[] args)
        {
            // create Workbook instance and load file
            Workbook book = new Workbook();
            book.LoadFromFile("Book1.xlsx");

            // embed image into html when converting
            HTMLOptions options = new HTMLOptions();
            options.ImageEmbedded = true;

            // save the sheet to html
            book.Worksheets[0].SaveToHtml("sample.html", options);
            System.Diagnostics.Process.Start("sample.html"); 

        }
    }
}

Additional Info

  • tutorial_title: Embed image in HTML when converting Excel to HTML
Last modified on Monday, 06 September 2021 02:02