Convert Excel XLSX to Markdown

The Excel to Markdown Converter writes the content of Excel XLSX workbooks as Markdown text. The cells of each worksheet are written as Markdown tables, with the values shown as they are displayed in Excel.

The Excel to Markdown Converter is part of the Excel to PDF component of the EvoPdf Next for .NET library. It is available in the applications that reference the NuGet packages of this component, described in the Convert Excel XLSX to PDF documentation section.

Convert an Excel Workbook to Markdown

The EvoPdf.NextExcelToMarkdownConverter class converts an Excel workbook from a file or from a memory buffer to a Markdown string or to a Markdown file.

Convert an Excel File to Markdown
// Create an Excel to Markdown converter instance
ExcelToMarkdownConverter excelToMarkdownConverter = new ExcelToMarkdownConverter();

// Convert the Excel file to a Markdown string
string markdown = excelToMarkdownConverter.ConvertToMarkdown("workbook.xlsx");
Convert an Excel Workbook from Memory to a Markdown File
ExcelToMarkdownConverter excelToMarkdownConverter = new ExcelToMarkdownConverter();

// Convert the Excel workbook and write the Markdown text to a file encoded as UTF-8
excelToMarkdownConverter.ConvertToMarkdownFile(excelBytes, "workbook.md");

Content Written in Markdown

The Markdown text follows the layout of each worksheet:

  • The rows that follow one another are written as a Markdown table and an empty row starts a new table

  • The numbers, the dates and the results of the formulas are written with the format they have in Excel

  • The columns of numbers are aligned to the right

  • A text alone on its row, like a title above a table, is written as a paragraph

  • The hyperlinks of the cells are written as Markdown links

  • The hidden rows and columns are left out

Pictures of the Worksheets

The pictures of a worksheet are written after the tables of the worksheet. A picture is written by default with its alternative text. The ExcelToMarkdownConverterImageMode property, with a value of the EvoPdf.NextExcelToMarkdownImageMode enumeration, also writes the image of the picture, embedded in the Markdown text or saved as a file in a folder. The charts are not written as pictures: their data is in the cells of the worksheet.

Embed the Pictures in the Markdown Text
excelToMarkdownConverter.ImageMode = ExcelToMarkdownImageMode.Embed;

When the pictures are saved as files, the ExcelToMarkdownConverterImagesFolder property gives the folder and the ExcelToMarkdownConverterImageFileName property gives the name of the files, which is followed by a number. The links of the Markdown text use the name of the images folder or the path given by the ExcelToMarkdownConverterImagesLinkPath property.

Save the Pictures as Files
excelToMarkdownConverter.ImageMode = ExcelToMarkdownImageMode.File;

// The folder where the image files are saved
excelToMarkdownConverter.ImagesFolder = "output/workbook_images";

// Optionally set the path used by the links of the Markdown text and the name of the files
excelToMarkdownConverter.ImagesLinkPath = "workbook_images";
excelToMarkdownConverter.ImageFileName = "picture";

Worksheets to Convert

By default all the worksheets of the workbook are converted and the name of each worksheet is written as a heading before its content. Set the ExcelToMarkdownConverterConvertOnlyFirstWorksheet property to convert only the first worksheet and the ExcelToMarkdownConverterDisplayWorksheetTitle property to control if the worksheet names are written.

Convert the First Worksheet without Its Title
excelToMarkdownConverter.ConvertOnlyFirstWorksheet = true;
excelToMarkdownConverter.DisplayWorksheetTitle = false;

Values of the Formulas

A cell with a formula is written with the value saved in the workbook. The ExcelToMarkdownConverterRecalculateFormulas property calculates the formulas again during the conversion. This is normally not needed. Set it for a workbook saved with values that are out of date or to have the functions that give the current date and time show the time of the conversion.

Calculate the Formulas Again
excelToMarkdownConverter.RecalculateFormulas = true;

Open Password Protected Workbooks

To convert a password protected Excel workbook set the ExcelToMarkdownConverterOpenPassword property before the conversion.

Set the Password of a Protected Excel Workbook
excelToMarkdownConverter.OpenPassword = "open-password";

Asynchronous Methods

The conversion methods have asynchronous versions that accept a cancellation token.

Asynchronously Convert an Excel Workbook to Markdown
string markdown = await excelToMarkdownConverter.ConvertToMarkdownAsync(excelBytes, cancellationToken);

Code Sample - Convert Excel XLSX to Markdown

Convert Excel XLSX to Markdown in ASP.NET Core
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using EvoPdf_Next_AspNetDemo.Models;
using EvoPdf_Next_AspNetDemo.Models.Excel_to_PDF;

// Use EVO PDF Namespace
using EvoPdf.Next;

namespace EvoPdf_Next_AspNetDemo.Controllers.Excel_to_PDF
{
    public class Excel_to_MarkdownController : Controller
    {
        private readonly IWebHostEnvironment m_hostingEnvironment;
        public Excel_to_MarkdownController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            var model = SetViewModel();

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> ConvertExcelToMarkdown(Excel_to_Markdown_ViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
                throw new ValidationException(errorMessage);
            }

            // Set the license key received after purchase to use the library in licensed mode; leave it commented for demo mode
            // Licensing.LicenseKey = "your-license-key";

            // Create the Excel to Markdown converter instance with default options
            ExcelToMarkdownConverter excelToMarkdownConverter = new ExcelToMarkdownConverter();

            // Optionally set the password to open a password-protected Excel workbook
            if (!string.IsNullOrEmpty(model.OpenPassword))
                excelToMarkdownConverter.OpenPassword = model.OpenPassword;

            // Set whether to convert only the first worksheet or all the worksheets of the workbook
            excelToMarkdownConverter.ConvertOnlyFirstWorksheet = model.ConvertOnlyFirstWorksheet;

            // Set whether the name of each worksheet is written as a heading before its content
            excelToMarkdownConverter.DisplayWorksheetTitle = model.DisplayWorksheetTitle;

            // Set whether the formulas are calculated again during the conversion
            excelToMarkdownConverter.RecalculateFormulas = model.RecalculateFormulas;

            // Write the pictures as their alternative text or embed their images in the Markdown text
            excelToMarkdownConverter.ImageMode = model.ImageMode == "Embed" ? ExcelToMarkdownImageMode.Embed : ExcelToMarkdownImageMode.None;

            byte[] inputExcelBytes = null;
            string outputFileName = null;

            // If an uploaded file exists, use it with priority
            if (model.ExcelFile != null && model.ExcelFile.Length > 0)
            {
                try
                {
                    using var ms = new MemoryStream();
                    await model.ExcelFile.CopyToAsync(ms);
                    inputExcelBytes = ms.ToArray();
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to read the uploaded Excel file", ex);
                }

                outputFileName = Path.GetFileNameWithoutExtension(model.ExcelFile.FileName) + ".md";
            }
            else
            {
                // Otherwise, fall back to the URL
                string excelUrl = model.ExcelFileUrl?.Trim();
                if (string.IsNullOrWhiteSpace(excelUrl))
                    throw new Exception("No Excel file provided: upload a file or specify a URL");

                try
                {
                    if (excelUrl.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
                    {
                        string localPath = new Uri(excelUrl).LocalPath;
                        inputExcelBytes = await System.IO.File.ReadAllBytesAsync(localPath);
                    }
                    else
                    {
                        using var httpClient = new System.Net.Http.HttpClient();
                        inputExcelBytes = await httpClient.GetByteArrayAsync(excelUrl);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Could not download the Excel file from URL", ex);
                }

                outputFileName = Path.GetFileNameWithoutExtension(model.ExcelFileUrl) + ".md";
            }

            // Convert the Excel workbook to Markdown
            string markdown = excelToMarkdownConverter.ConvertToMarkdown(inputExcelBytes);

            // Encode the Markdown text as UTF-8 bytes
            byte[] outputMarkdownBytes = Encoding.UTF8.GetBytes(markdown);

            // Return the Markdown text as a downloadable file
            return File(outputMarkdownBytes, "text/markdown; charset=utf-8", outputFileName);
        }

        private Excel_to_Markdown_ViewModel SetViewModel()
        {
            var model = new Excel_to_Markdown_ViewModel();

            HttpRequest request = ControllerContext.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = request.Scheme;
            uriBuilder.Host = request.Host.Host;
            if (request.Host.Port != null)
                uriBuilder.Port = (int)request.Host.Port;
            uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
            uriBuilder.Query = request.QueryString.ToString();

            string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
            string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Excel_to_Markdown".Length);

            model.ExcelFileUrl = rootUrl + "/DemoAppFiles/Input/Excel_Files/Excel_Document.xlsx";

            return model;
        }
    }
}

See Also