This article explains how to export a DataTable to Excel using HTML text in C#.
Introduction
We have various ways to export a DataTable to Excel. The following are common ways:
At this time I want to introduce an alternative way to create an Excel file for a required DataTable.Let us first discuss some basics of how to export a HTML text to an Excel file.Please use the following procedure to understand this technique.
1. Create sample HTML fileCode below
OutputHere we can see the HTML in the web browser.Now we will open this file in Excel.The following will be the screen if we open the HTML file in Excel.ConclusionHere we created a HTML file and opened it in an Excel file. So the table row and table cell of the HTML file fits into rows and cells of the Excel file with proper formatting and borders and background color and so on.So we will create HTML text for the data table and then save it as a .xls file, it would work as expected.We will use the following approach to export the DataTable to Excel.This code can be used for reporting purposes where sometimes the client needs to output the data in HTML/Excel format.A. Binding DataGridView using DataTableProcedure
B. Exporting DataTable to HTML.I have written generic code that could create HTML text for every DataTable.You can use this code directly in your project for reporting purposes.Code below
C. Understanding the code
D. Output
After executing the code above we would get the following HTML:
E. Creating HTML file
Exporting DataTable to Excel in C# Using Interop
Beginning C# Object Oriented Programming