Conversion (30)
Convert Excel to JSON and JSON to Excel in C# .NET – Step-by-Step Guide
2025-08-13 09:40:46 Written by zaki zou
Converting between Excel and JSON formats is a valuable skill for developers dealing with data exchange, API integration, and modern web applications.
Excel files (.xls, .xlsx) are excellent for organizing and analyzing tabular data, while JSON (JavaScript Object Notation) is lightweight, human-readable, and ideal for transmitting data across platforms.
In this step-by-step tutorial, you’ll learn how to seamlessly convert Excel to JSON and JSON to Excel in C# using the Spire.XLS for .NET library. Whether you’re exporting Excel data for frontend apps, feeding structured datasets into APIs, or importing JSON into spreadsheets, this guide provides clear explanations, complete code samples, and tips to help you get started quickly.
What You Will Learn
- Why Convert Between Excel and JSON Formats
- Prerequisites
- Installing Required Packages
- How to Convert Excel to JSON in C# .NET (Step-by-Step)
- How to Convert JSON to Excel in C# .NET (Step-by-Step)
- Tips and Best Practices
- Conclusion
- Further Reading
- FAQs
Why Convert Between Excel and JSON Formats?
Converting between Excel and JSON can be beneficial for several reasons:
- Data Exchange: JSON is a standard format for data interchange in web applications, making it easier to share data across platforms.
- Integration with APIs: Many web APIs require data in JSON format, necessitating conversion from Excel for seamless integration.
- Lightweight and Compact: JSON files are generally smaller in size compared to Excel files, leading to faster data transfer and reduced storage needs.
- Readability: JSON is human-readable and easier to understand, which can simplify data analysis and troubleshooting.
- Compatibility with NoSQL Databases: JSON format is commonly used in NoSQL databases, facilitating easy data migration and storage.
Prerequisites
Before we start, ensure you have the following:
- Visual Studio or any C# development IDE installed.
- .NET Framework or .NET Core installed.
- Spire.XLS package installed for handling Excel files.
- Newtonsoft.Json package installed for handling JSON serialization and deserialization.
Installing Required Packages
You can install the required packages using NuGet Package Manager in Visual Studio:
Install-Package Spire.XLS
Install-Package Newtonsoft.Json
How to Convert Excel to JSON in C# .NET (Step-by-Step)
Exporting Excel files to JSON format in C# involves extracting data from Excel spreadsheets and transforming it into a structured JSON string. This process is particularly useful for applications that require data interchange between web services or databases. Below are detailed steps to guide you through the conversion process.
Steps to Export Excel to JSON
- Load the Excel File:
- Begin by creating a Workbook object that will hold the Excel file's content using the Spire.XLS library. Load the Excel file into this object.
- Access the Desired Worksheet:
- Identify and access the specific worksheet from which you want to extract data. This is done by referencing the appropriate index of the Worksheets collection.
- Export to DataTable:
- Utilize the ExportDataTable() method to convert the worksheet's content into a DataTable. This provides a structured representation of the data, making it easier to manipulate.
- Serialize to JSON:
- Use the Newtonsoft.Json library to serialize the DataTable into a JSON string. This step involves converting the structured data into a JSON format, which is human-readable and suitable for web applications.
- Save the JSON to a File:
- Finally, write the generated JSON string to a file. This allows for easy access and reuse of the data in future applications or processes.
Complete Code Example: Excel to JSON
Here’s a complete code example demonstrating the process:
using Newtonsoft.Json;
using Spire.Xls;
using System.Data;
using System.IO;
namespace ConvertExcelToJSON
{
class Program
{
static void Main(string[] args)
{
// Path to the Excel file
string excelFilePath = @"Sample.xlsx";
// Create a new Workbook instance
Workbook workbook = new Workbook();
// Load the Excel file
workbook.LoadFromFile(excelFilePath);
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Export the worksheet content to a DataTable
DataTable dataTable = worksheet.ExportDataTable();
// Convert the DataTable to a JSON string
string jsonResult = JsonConvert.SerializeObject(dataTable, Formatting.Indented);
// Save JSON string to a text file
File.WriteAllText("output.txt", jsonResult);
}
}
}

How to Convert JSON to Excel in C# .NET (Step-by-Step)
Importing JSON data into an Excel file is a valuable process, especially when you need to analyze or present data in a more user-friendly format. JSON is easy for humans to read and write, and easy for machines to parse and generate. However, for many users, Excel remains the preferred tool for data analysis, reporting, and visualization.
In the following steps, we will outline the process of importing JSON into Excel, enabling you to effectively utilize your JSON data within Excel for further analysis and reporting.
Steps to Import JSON into Excel
- Read the JSON String:
- Start by reading the JSON data from a file or other sources. This could include API responses, local files, or even hardcoded strings for testing purposes.
- Deserialize to DataTable:
- Use the Newtonsoft.Json library to deserialize the JSON string into a DataTable. This structured format makes it easy to manipulate data before inserting it into Excel.
- Create a New Excel Workbook:
- Initialize a new Workbook instance using the Spire.XLS library. This workbook will serve as the container for your Excel data.
- Insert the DataTable into the Worksheet:
- Use the InsertDataTable() method to transfer the contents of the DataTable into the first worksheet of the workbook. This method allows you to include column headers and organize the data neatly.
- Apply Optional Formatting:
- Enhance the visual appeal of your Excel file by applying formatting to headers and data cells. This step involves defining styles for fonts, background colors, and borders, making the data easier to read.
- Save the Workbook:
- Finally, save the populated workbook as an Excel file. Choose an appropriate file format (e.g., .xlsx) to ensure compatibility with modern Excel versions.
Complete Code Example: JSON to Excel
Here’s a complete code snippet demonstrating the conversion process:
using Newtonsoft.Json;
using Spire.Xls;
using System.Data;
using System.Drawing;
namespace ConvertJSONToExcel
{
class Program
{
static void Main(string[] args)
{
// Sample JSON data
string json = @"
[
{""Name"":""John Smith"",""Age"":30,""Department"":""Sales"",""StartDate"":""2020-05-12"",""FullTime"":true},
{""Name"":""Jane Doe"",""Age"":25,""Department"":""Marketing"",""StartDate"":""2021-09-01"",""FullTime"":false},
{""Name"":""Michael Lee"",""Age"":40,""Department"":""IT"",""StartDate"":""2018-03-15"",""FullTime"":true},
{""Name"":""Emily Davis"",""Age"":35,""Department"":""Finance"",""StartDate"":""2019-07-20"",""FullTime"":true}
]";
// Deserialize JSON into DataTable
DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(json);
// Create a new Excel workbook
Workbook workbook = new Workbook();
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Insert DataTable into worksheet with column headers
worksheet.InsertDataTable(dataTable, true, 1, 1);
// (Optional) Applying formatting to Excel data
// Set style for heading row
CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
headerStyle.Font.IsBold = true;
headerStyle.Font.Size = 12;
headerStyle.Font.Color = Color.White;
headerStyle.HorizontalAlignment = HorizontalAlignType.Center;
headerStyle.VerticalAlignment = VerticalAlignType.Center;
headerStyle.Color = Color.DarkBlue;
int colCount = dataTable.Columns.Count;
for (int c = 1; c <= colCount; c++)
{
worksheet.Range[1, c].CellStyleName = "HeaderStyle";
}
// Set style for data cells
CellStyle dataStyle = workbook.Styles.Add("DataStyle");
dataStyle.HorizontalAlignment = HorizontalAlignType.Center;
dataStyle.VerticalAlignment = VerticalAlignType.Center;
dataStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
dataStyle.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
dataStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
dataStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
int rowCount = dataTable.Rows.Count;
worksheet.Range[2, 1, rowCount + 1, colCount].CellStyleName = "DataStyle";
// Auto-fit column widths
worksheet.AllocatedRange.AutoFitColumns();
// Save Excel file
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2013);
// Release resources
workbook.Dispose();
}
}
}

Tips and Best Practices
When converting between Excel and JSON, following best practices can help ensure data integrity and usability. Here are some key tips to keep in mind:
- Validate Data Types: Ensure that data types (e.g., dates, numbers) are correctly formatted to avoid issues during conversion.
- Handle Empty Cells: Decide how to treat empty cells (e.g., convert to null or omit) to maintain data integrity.
- Use Consistent Naming Conventions: Standardize column names in Excel for clear and consistent JSON keys.
- Test Thoroughly: Always test the conversion processes to ensure valid JSON output and accurate Excel representation.
- Include Headers: When converting JSON to Excel, always insert headers for improved readability and usability.
Conclusion
Converting Excel to JSON and JSON to Excel is a common but critical operation in modern C# development, especially for applications involving data exchange and API integration. Using Spire.XLS together with Newtonsoft.Json simplifies this process with intuitive APIs and robust functionality.
This guide has walked you through every step—from installing necessary packages to implementing complete converters—with clear explanations and sample code. With these tools and knowledge, you can confidently integrate Excel-JSON conversion into your applications, improving flexibility and interoperability.
Further Reading
FAQs
Q1: How to convert multiple worksheets to JSON at once?
You can iterate through the Workbook.Worksheets collection and export each worksheet’s data individually, supporting batch Excel to JSON conversion.
Q2: How to customize JSON output formatting?
JsonConvert.SerializeObject allows you to set indentation, camelCase naming, or ignore null values. You can also use custom converters for more control.
Q3: How to improve readability when converting JSON to Excel?
Keep column headers, set alignment, apply borders and styles to generate a clear and easy-to-read Excel report.
Q4: Is this method compatible with .NET Core?
Yes, it is fully compatible. Both Spire.XLS and Newtonsoft.Json support .NET Core and .NET Framework, making it usable in various C# projects.
How to Convert Markdown to PDF and Excel in C# .NET: A Complete Guide
2025-07-18 06:09:23 Written by zaki zou
Markdown is a lightweight markup language widely used for writing formatted text using simple plain syntax. Favored by developers, writers, and technical content creators for its readability and ease of use, Markdown is perfect for drafting documents, notes, and technical content. However, Markdown files (.md) often need to be converted into other formats such as PDF for official distribution or Excel for data analysis and reporting.
In this comprehensive guide, you will learn how to convert Markdown files to PDF and Excel using C# and Spire.XLS for .NET — a powerful and easy-to-use library that supports direct Markdown loading and exporting to multiple formats. Whether you want to generate polished PDF documents or structured Excel spreadsheets, this tutorial covers everything you need.
Table of Contents
- Why Convert Markdown to PDF and Excel?
- Prerequisites (Library & Environment Setup)
- How to Convert Markdown to PDF in C# (Step-by-Step with Code)
- How to Convert Markdown to Excel in C# (Step-by-Step with Code)
- Complete C# Code Example: Convert Markdown to PDF and Excel in One Go
- Best Practices for Markdown Conversion
- Conclusion
- FAQs
Why Convert Markdown to PDF and Excel?
Markdown is great for writing, but it has limitations when sharing or processing documents:
- PDF files provide a fixed-layout, platform-independent format ideal for sharing polished reports, manuals, or official documentation. PDFs maintain the original style and layout regardless of device or software.
- Excel files are essential when Markdown contains tabular data that you want to analyze, manipulate, or integrate into business processes. Converting Markdown tables to Excel spreadsheets lets you utilize formulas, filters, charts, and data tools effectively.
By converting Markdown to these formats programmatically in C#, you can automate documentation workflows, batch-process files, and integrate with other .NET applications.
Prerequisites (Library & Environment Setup)
Before you start converting Markdown files, ensure your development environment meets the following requirements:
- .NET Framework or .NET Core installed.
- Spire.XLS for .NET: A comprehensive Excel library that supports loading Markdown and exporting to PDF and Excel formats.
Install Spire.XLS via NuGet
You can easily install Spire.XLS in your C# project via NuGet by opening the NuGet Package Manager and executing the following command:
Install-Package Spire.XLS
This package provides all the necessary classes and methods to load Markdown and export documents without relying on Microsoft Office automation.
How to Convert Markdown to PDF in C# (Step-by-Step with Code)
To convert a Markdown file to PDF in C#, follow the steps below:
Step 1: Load the Markdown File
Create a new instance of the Workbook class and load your Markdown file:
Workbook workbook = new Workbook();
workbook.LoadFromMarkdown("test.md");
This method parses the Markdown content, including text and tables, into an Excel workbook structure that Spire.XLS can manipulate.
Step 2: Customize Conversion Settings (Optional)
After loading the Markdown file, you can apply conversion settings to ensure the PDF output retains a clean and readable layout. For example, enabling the SheetFitToPage option ensures that the entire Markdown content fits within a single PDF page.
workbook.ConverterSetting.SheetFitToPage = true;
Step 3: Export as PDF
Save the workbook as a PDF file:
workbook.SaveToFile("output.pdf", FileFormat.PDF);
This generates a well-formatted PDF document preserving the Markdown layout and styling suitable for printing or sharing.

How to Convert Markdown to Excel in C# (Step-by-Step with Code)
After loading the Markdown file into the workbook, you can also export it to an Excel spreadsheet format:
workbook.SaveToFile("output.xls", ExcelVersion.Version97to2003);
You may also choose other Excel versions depending on your target compatibility:
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2016);
The exported Excel file retains tables and structured data from your Markdown, allowing further analysis or manipulation.

Complete C# Code Example: Convert Markdown to PDF and Excel in One Go
Here’s the full example combining both PDF and Excel exports in a single run:
using Spire.Xls;
namespace MarkdownToPdfAndExcel
{
internal class Program
{
static void Main(string[] args)
{
// Initialize the workbook
Workbook workbook = new Workbook();
// Load Markdown content
workbook.LoadFromMarkdown("test.md");
// Fit the sheet data to one page (optional)
workbook.ConverterSetting.SheetFitToPage = true;
// Export to PDF
workbook.SaveToFile("output.pdf", FileFormat.PDF);
// Export to xls (Excel 97-2003 format)
workbook.SaveToFile("output.xls", ExcelVersion.Version97to2003);
// Export to xlsx (Excel 2016 format)
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}
Best Practices for Markdown Conversion
- Use UTF-8 Encoding: Ensure your Markdown files use UTF-8 encoding, especially if they contain special or non-English characters. This ensures proper character display and avoids encoding errors during conversion.
- Maintain Clean and Well-Formatted Markdown Tables: To achieve accurate and reliable Excel conversions, structure your Markdown tables carefully. Use consistent pipe (|) delimiters and avoid malformed syntax to preserve table integrity in the output spreadsheet.
- Load Once, Export Multiple Formats: For optimal performance, load your Markdown content into the Workbook object a single time, then export it to various formats such as PDF and Excel. This reduces processing overhead and speeds up batch conversions.
- Assess Markdown Complexity: Spire.XLS effectively supports basic Markdown syntax, such as headings and tables. However, advanced features like embedded images or code blocks with syntax highlighting might require pre-processing or conversion through intermediate formats like HTML.
- Choose Appropriate Excel Export Versions: To maximize compatibility with your users’ software, select the Excel file format based on their environment. For example, use the .xls format for legacy Excel 97–2003 users, and .xlsx for Excel 2007 and later versions to ensure broad accessibility and full feature support.
Conclusion
Converting Markdown to PDF and Excel using C# and Spire.XLS is a fast, flexible, and reliable approach to modern document workflows. With minimal code, developers can automate the transformation of lightweight Markdown into professional PDFs for distribution and Excel spreadsheets for business analytics.
This method streamlines technical writing, reporting, and data handling tasks within .NET applications and enables seamless integration with other business processes.
FAQs
Q1: Can I batch convert multiple Markdown files using Spire.XLS in C#?
A1: Yes, you can loop through multiple Markdown files, load each one using Spire.XLS, and export them individually to PDF or Excel formats within the same C# project.
Q2: Is Microsoft Office required to use Spire.XLS for Markdown conversion?
A2: No, Spire.XLS is a standalone library and does not rely on Microsoft Office or Excel being installed on the machine.
Q3: Is Spire.XLS free to use?
A3: Spire.XLS offers a free version with some limitations. A commercial license is available for full features.
Get a Free License
To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.

In data processing and management scenarios, efficiently transforming raw text (TXT) files into structured Excel spreadsheets is a common requirement. For developers who are automating reports or processing log files, converting TXT to Excel using C# streamlines data organization and analysis. This guide explores how to achieve this using Spire.XLS for .NET, a powerful library designed to handle Excel XLS or XLSX files without requiring Microsoft Office.
- Why Convert TXT to Excel Programmatically?
- How to Convert Text Files to Excel in C# (Step-by-Step Guide)
- Pro Tips for TXT to Excel Conversion
Why Convert TXT to Excel Programmatically?
Text files are simple but lack the analytical power of Excel. Key advantages of converting TXT to XLS or XLSX format include:
- Automation: Process large or recurring files without manual intervention.
- Data Structuring: Organize raw text into rows, columns, and sheets.
- Advanced Features: Leverage Excel formulas, charts, and pivot tables.
- Integration: Embed conversion feature into .NET applications or APIs.
How to Convert Text Files to Excel in C# (Step-by-Step Guide)
Install Spire.XLS for .NET
Spire.XLS for .NET is a professional Excel document processing component, provides efficient and convenient APIs that allow developers to achieve TXT to Excel conversion through simple code.
Before getting started, you can choose one of these methods to install the library:
Method 1: NuGet Package Manager
- Open your project in Visual Studio.
- Right-click on the project in the Solution Explorer and select "Manage NuGet Packages."
- Search for "Spire.XLS" and click "Install".
Method 2: Package Manager Console
- Go to "Tools > NuGet Package Manager > Package Manager Console."
- Run the following command in the console:
PM> Install-Package Spire.XLS
Method 3: Manual Installation with DLL Files
- Visit the Spire.XLS Download Page and get the latest version.
- Extract the files and then add the Spire.Xls.dll to your project.
Import a Text File into Excel Using C#
Follow the below steps to write the data in a txt file into an Excel worksheet:
- Read TXT File: use the File.ReadAllLines() method to read all lines in a text file and returns them as an array of strings.
- Parse each line:
- Use the string.Trim() method to remove the leading/trailing whitespaces.
- Use the string.Split() method to split the data based on specified delimiters.
- Add the split text data to a list.
- Create a Workbook instance and get a worksheet
- Write Data to specified cells:
- Iterate through the rows and columns in the list.
- Assign the data in the list to the corresponding Excel cells through the Worksheet.Range[].Value property.
- Save the Excel File.
Code Example:
- C#
using Spire.Xls;
using System.IO;
using System.Collections.Generic;
class TxtToExcelConverter
{
static void Main()
{
// Open a text file and read all lines in it
string[] lines = File.ReadAllLines("Data.txt");
// Create a list to store the data in text file
List data = new List();
// Split data into rows and columns and add to the list
foreach (string line in lines)
{
data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
}
// Create a Workbook object
Workbook workbook = new Workbook();
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Iterate through the rows and columns in the data list
for (int row = 0; row < data.Count; row++)
{
for (int col = 0; col < data[row].Length; col++)
{
// Write the text data in specified cells
sheet.Range[row + 1, col + 1].Value = data[row][col];
// Set the header row to Bold
sheet.Range[1, col + 1].Style.Font.IsBold = true;
}
}
// Autofit columns
sheet.AllocatedRange.AutoFitColumns();
// Save the Excel file
workbook.SaveToFile("TXTtoExcel.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
Result:

Pro Tips for TXT to Excel Conversion
- Handling Different Delimiters:
If your TXT file uses a different delimiter (e.g., space, comma, semicolon), modify the parameter of the Split(params char[] separator) method.
- Format Cells:
After a text file being converted to an Excel file, you can take advantage of the Spire.XLS library’s rich features to format cells, such as setting the background colors, adding cell borders, applying number formats, etc.
Conclusion
By following this step-by-step guide, you can efficiently transform unstructured text data into organized Excel spreadsheets, which is ideal for data analysis, reporting, and management. Remember to optimize your implementation for your specific delimiters and leverage Spire.XLS's advanced features for complex conversion scenarios.
Get a Free License
To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.
Microsoft Excel is a powerful tool for data management; however, its proprietary format can pose challenges for sharing and integrating data into web workflows. In contrast, Markdown is a lightweight and widely supported markup language that simplifies text formatting for documentation, wikis, and platforms like GitHub.
By converting Excel files to Markdown, you can seamlessly incorporate structured data into technical documents, READMEs, and static websites. This article will guide you through the steps to programmatically convert Excel files to Markdown format using C# and the Spire.XLS for .NET library.
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.XLS
Convert an Excel XLS or XLSX File to Markdown in C#
Developers can effortlessly convert Excel XLS or XLSX files to Markdown files by using the Workbook.SaveToMarkdown() method provided by Spire.XLS for .NET. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load a sample Excel XLS or XLSX file into the Workbook object using the Workbook.LoadFromFile() method.
- Save the Excel file as a Markdown file using the Workbook.SaveToMarkdown() method.
- C#
using Spire.Xls;
namespace ConvertExcelToMarkdown
{
internal class Program
{
static void Main(string[] args)
{
// Create an object of the Workbook class
Workbook workbook = new Workbook();
// Load a sample Excel XLS file
//workbook.LoadFromFile("Sample.xls");
// Load a sample Excel XLSX file
workbook.LoadFromFile("Sample.xlsx");
// Save the Excel file as a Markdown file
workbook.SaveToMarkdown("output.md");
// Release the resources used by the Workbook object
workbook.Dispose();
}
}
}

Get a Free License
To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.
XML is often used for data interchange between different systems, while Excel is a widely recognized format for data analysis and reporting. By converting XML data to Excel, you can leverage Excel's powerful features to analyze and visualize the data more effectively. This conversion process is essential in various industries, including finance, healthcare, and e-commerce.
In this article, you will learn how to convert XML to Excel and PDF in C# using Spire.XLS for .NET.
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.XLS
Understanding XML Structure: Elements, Attributes, and Data
Before converting XML to Excel, it's crucial to understand the structure of XML files. XML is a markup language that uses tags to define elements, attributes, and data. Here’s a breakdown of these components:
- Elements: These are the building blocks of XML. They are defined by start and end tags and can contain data or other elements.
<person>
<name>John Doe</name>
<age>30</age>
</person>
- Attributes: These provide additional information about elements. They are specified within the start tag of an element.
<person id="1">
<name>John Doe</name>
<age>30</age>
</person>
- Data: This is the content enclosed within the start and end tags of an element.
Understanding these components will help you map XML data to Excel effectively.
Convert XML to Excel in C#
In .NET, you can use the System.Xml.Linq namespace, which provides classes for working with XML files. The primary class used is XDocument, which allows you to load, navigate, and manipulate XML documents effortlessly.
Here's an example:
- C#
using System;
using System.Xml.Linq;
class Program
{
static void Main()
{
// Load the XML file
XDocument doc = XDocument.Load("data.xml");
XElement root = doc.Root;
// Iterate through elements
foreach (XElement person in root.Elements("person"))
{
string name = person.Element("name")?.Value;
string age = person.Element("age")?.Value;
// Output the name and age
Console.WriteLine($"Name: {name}, Age: {age}");
}
}
}
After parsing the XML data, the next step is to map it to an Excel worksheet. You can use Spire.XLS for .NET to create a new workbook, input data into specific cells, and apply various styles and formatting options. These include auto-fitting column widths, adjusting text alignment, and making the header bold.
To convert XML to Excel in C#, follow these steps:
- Utilize the System.Xml.Linq library to extract data from the XML file.
- Create a Workbook object.
- Add a worksheet using the Workbook.Worksheets.Add() method.
- Write the extracted data into the worksheet cells using the Worksheet.SetValue() method.
- Apply styles and formatting to enhance the appearance of the worksheet.
- Save the workbook to an Excel file using the Workbook.SaveToFile() method.
The following code demonstrates an efficient and advanced method for reading data from XML and importing it into an Excel file.
- C#
using Spire.Xls;
using System.Xml.Linq;
namespace ConvertXmlToExcel
{
class Program
{
static void Main(string[] args)
{
// Create a Workbook object
Workbook workbook = new Workbook();
// Remove default worksheets
workbook.Worksheets.Clear();
// Add a worksheet and name it
Worksheet worksheet = workbook.Worksheets.Add("Books");
// Load an XML file
XDocument xmlDoc = XDocument.Load(@"C:\Users\Administrator\Desktop\Books.xml");
XElement xmlRoot = xmlDoc.Root;
// Get the first "book" element
XElement firstBook = xmlRoot.Element("book");
// Extract header information and convert it into a list
var headers = firstBook.Elements().ToList();
// Write header to Excel
for (int colIndex = 0; colIndex < headers.Count; colIndex++)
{
string headerText = headers[colIndex].Name.LocalName;
worksheet.SetValue(1, colIndex + 1, headerText);
}
// Write other data to Excel by iterating over each book element and each data node within it
int rowIndex = 2;
foreach (XElement book in xmlRoot.Elements("book"))
{
var dataNodes = book.Elements().ToList();
for (int colIndex = 0; colIndex < dataNodes.Count; colIndex++)
{
string value = dataNodes[colIndex].Value;
worksheet.SetValue(rowIndex, colIndex + 1, value);
}
rowIndex++;
}
// Set column width
worksheet.AllocatedRange.AutoFitColumns();
// Set alignment
worksheet.AllocatedRange.HorizontalAlignment = HorizontalAlignType.Left;
// Set font style
worksheet.Range["A1:F1"].Style.Font.IsBold = true;
// Save the workbook to an Excel file
workbook.SaveToFile("output/XmlToExcel.xlsx");
// Dispose resources
workbook.Dispose();
}
}
}

Convert XML to PDF in C#
The previous example effectively imports data from an XML file into an Excel worksheet. This worksheet can subsequently be converted to a PDF file using the Worksheet.SaveToPdf() method. To ensure a well-structured PDF, you may want to adjust page layout settings, such as margins and the preservation of gridlines, during the conversion process.
Here are the steps to convert XML to PDF using C#:
- Use the System.Xml.Linq library to retrieve data from the XML file.
- Create a Workbook object.
- Add a worksheet with the Workbook.Worksheets.Add() method.
- Populate the worksheet cells with data extracted from the XML file using the Worksheet.SetValue() method.
- Apply styles and formatting to improve the worksheet's appearance.
- Configure page settings using properties from the PageSetup object, accessible via Worksheet.PageSetup.
- Save the worksheet as a PDF file using the Worksheet.SaveToPdf() method.
The following code snippet illustrates how to import data from XML into a worksheet and then save that worksheet as a PDF file.
- C#
using Spire.Xls;
using Spire.Xls.Core;
using System.Xml.Linq;
namespace ConvertXmlToPdf
{
class Program
{
static void Main(string[] args)
{
// Create a Workbook object
Workbook workbook = new Workbook();
// Remove default worksheets
workbook.Worksheets.Clear();
// Add a worksheet and name it
Worksheet worksheet = workbook.Worksheets.Add("Books");
// Load an XML file
XDocument xmlDoc = XDocument.Load(@"C:\Users\Administrator\Desktop\Books.xml");
XElement xmlRoot = xmlDoc.Root;
// Get the first "book" element
XElement firstBook = xmlRoot.Element("book");
// Extract header information and convert it into a list
var headers = firstBook.Elements().ToList();
// Write header to Excel
for (int colIndex = 0; colIndex < headers.Count; colIndex++)
{
string headerText = headers[colIndex].Name.LocalName;
worksheet.SetValue(1, colIndex + 1, headerText);
}
// Write other data to Excel by iterating over each book element and each data node within it
int rowIndex = 2;
foreach (XElement book in xmlRoot.Elements("book"))
{
var dataNodes = book.Elements().ToList();
for (int colIndex = 0; colIndex < dataNodes.Count; colIndex++)
{
string value = dataNodes[colIndex].Value;
worksheet.SetValue(rowIndex, colIndex + 1, value);
}
rowIndex++;
}
// Set column width
worksheet.AllocatedRange.AutoFitColumns();
// Set alignment
worksheet.AllocatedRange.HorizontalAlignment = HorizontalAlignType.Left;
// Set font style
worksheet.Range["A1:F1"].Style.Font.IsBold = true;
// Fit worksheet on one page
workbook.ConverterSetting.SheetFitToPage = true;
// Get the PageSetup object
PageSetup pageSetup = worksheet.PageSetup;
// Set page margins
pageSetup.TopMargin = 0.3;
pageSetup.BottomMargin = 0.3;
pageSetup.LeftMargin = 0.3;
pageSetup.RightMargin = 0.3;
// Preserve gridlines
pageSetup.IsPrintGridlines = true;
// Save the worksheet to a PDF file
worksheet.SaveToPdf("output/XmlToPdf.pdf");
// Dispose resources
workbook.Dispose();
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
This article demonstrates how to convert shapes and SmartArt graphics in Excel to Image in C# using Spire.XLS for .NET.
The input Excel file:

using Spire.Xls;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
namespace Convert_Shapes_and_SmartArt_to_Image
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook object
Workbook workbook = new Workbook();
//Load the Excel file
workbook.LoadFromFile("Sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Create a SaveShapeTypeOption object
SaveShapeTypeOption shapelist = new SaveShapeTypeOption();
//Save shapes and SmartArt graphics in the worksheet to images
List images = sheet.SaveShapesToImage(shapelist);
//Save images to file
int index = 0;
foreach (Image img in images)
{
img.Save("Image/" + "toImage" + index + ".Png", ImageFormat.Png);
index++;
}
}
}
}
Imports Spire.Xls
Imports System.Collections.Generic
Imports System.Drawing.Imaging
Namespace Convert_Shapes_and_SmartArt_to_Image
Friend Class Program
Private Shared Sub Main(ByVal args As String())
'Create a Workbook object
Dim workbook As Workbook = New Workbook()
'Load the Excel file
workbook.LoadFromFile("Sample.xlsx")
'Get the first worksheet
Dim sheet As Worksheet = workbook.Worksheets(0)
'Create a SaveShapeTypeOption object
Dim shapelist As SaveShapeTypeOption = New SaveShapeTypeOption()
'Save shapes and SmartArt graphics in the worksheet to images
Dim images As List(Of Bitmap) = sheet.SaveShapesToImage(shapelist)
'Save images to file
Dim index As Integer = 0
For Each img As Image In images
img.Save("Image/" & "toImage" & index & ".Png", ImageFormat.Png)
index += 1
Next
End Sub
End Class
End Namespace
Converted images:

HTML (HyperText Markup Language) is primarily used for structuring content on web pages. While it excels at presenting information visually on the web, it lacks the robust analytical capabilities and data manipulation features found in spreadsheet software like Excel. By converting HTML data to Excel, users can leverage Excel's advanced functionalities like formulas, charts, tables, and macros to organize and analyze data efficiently. In this article, we will explain how to convert HTML to Excel in C# using Spire.XLS for .NET.
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.XLS
Convert HTML to Excel in C#
Spire.XLS for .NET offers the Workbook.LoadFromHtml() method to load an HTML file. After loading the HTML file, you can easily save it in Excel format using the Workbook.SaveToFile() method. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an HTML file using the Workbook.LoadFromHtml() method.
- Save the HTML file in Excel format using the Workbook.SaveToFile() method.
- C#
using Spire.Xls;
namespace ConvertHtmlToExcel
{
internal class Program
{
static void Main(string[] args)
{
// Specify the input HTML file path
string filePath = @"C:\Users\Administrator\Desktop\Sample.html";
// Create an object of the workbook class
Workbook workbook = new Workbook();
// Load the HTML file
workbook.LoadFromHtml(filePath);
// Save the HTML file in Excel XLSX format
string result = @"C:\Users\Administrator\Desktop\ToExcel.xlsx";
workbook.SaveToFile(result, ExcelVersion.Version2013);
workbook.Dispose();
}
}
}

Insert HTML String to Excel in C#
In addition to converting HTML files to Excel, Spire.XLS for .NET also allows you to insert HTML strings into Excel cells by using the CellRange.HtmlString property. The detailed steps are as follows.
- Create an object of the Workbook class.
- Get a specific worksheet by its index (0-based) using the Workbook.Worksheets[index] property.
- Get the cell that you want to add an HTML string to using the Worksheet.Range[] property.
- Add an HTML sting to the cell using the CellRange.HtmlString property.
- Save the resulting workbook to a new file using the Workbook.SaveToFile() method.
- C#
using Spire.Xls;
namespace InsertHtmlStringInExcel
{
internal class Program
{
static void Main(string[] args)
{
// Create an object of the workbook class
Workbook workbook = new Workbook();
// Get the first sheet
Worksheet sheet = workbook.Worksheets[0];
// Specify the HTML string
string htmlCode = "<p><font size='12'>This is a <b>paragraph</b> with <span style='color: red;'>colored text</span>.</font></p>";
// Get the cell that you want to add the HTML string to
CellRange range = sheet.Range["A1"];
// Add the HTML string to the cell
range.HtmlString = htmlCode;
// Auto-adjust the width of the first column based on its content
sheet.AutoFitColumn(1);
// Save the resulting workbook to a new file
string result = @"C:\Users\Administrator\Desktop\InsertHtmlStringIntoCell.xlsx";
workbook.SaveToFile(result, ExcelVersion.Version2013);
workbook.Dispose();
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
A ChartSheet represents a chart sheet. It is a worksheet that contains only a chart. This article will demonstrate how to convert a chart sheet to SVG stream by using Spire.XLS.
Firstly, view the sample Excel worksheets with two chart sheets.

Convert all the chart sheets to SVG stream:
using System.Drawing.Imaging;
using System.IO;
namespace Convert
{
class Program
{
static void Main(string[] args)
{
//load the document from file
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
//call ToSVGStream(Stream stream) method to save each chart sheet to SVG stream
for (int i = 0; i < workbook.Chartsheets.Count; i++)
{
FileStream fs = new FileStream(string.Format("chartsheet-{0}.svg", i), FileMode.Create);
workbook.Chartsheets[i].ToSVGStream(fs);
fs.Flush();
fs.Close();
}
}
}
}
Effective screenshot of the two chart sheets to SVG.

using System.Drawing.Imaging;
using System.IO;
namespace Convert
{
class Program
{
static void Main(string[] args)
{
//load the document from file
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
//get the second chartsheet by name
ChartSheet cs = workbook.GetChartSheetByName("Chart2");
//save to SVG stream
FileStream fs = new FileStream(string.Format("chart2.svg"), FileMode.Create);
cs.ToSVGStream(fs);
fs.Flush();
fs.Close();
}
}
}

Charts are commonly used in Microsoft Excel files to visualize numeric data. In some cases, you may need to save the charts in an Excel file as images in order to use them in other programs or other files such as PDFs and PowerPoint presentations. In this article, we will demonstrate how to convert charts in Excel to images in C# and VB.NET using Spire.XLS for .NET.
- Convert a Specific Chart in an Excel Worksheet to Image
- Convert All Charts in an Excel Worksheet to Images
- Convert a Chart Sheet to Image in Excel
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.XLS
Convert a Specific Chart in an Excel Worksheet to Image in C# and VB.NET
Spire.XLS provides the Workbook.SaveChartAsImage(Worksheet worksheet, int chartIndex) method which enables you to convert a specific chart in a worksheet as image. The following are the detailed steps:
- Initialize an instance of the Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index through Workbook.Worksheets[int worksheetIndex] property.
- Save a specific chart in the worksheet as image using Workbook.SaveChartAsImage(Worksheet worksheet, int chartIndex) method.
- Save the image to a PNG file.
- C#
- VB.NET
using Spire.Xls;
using System.Drawing;
using System.Drawing.Imaging;
namespace ConvertAExcelChartToImage
{
internal class Program
{
static void Main(string[] args)
{
//Initialize an instance of the Workbook class
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("Charts.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Save the first chart in the first worksheet as image
Image image = workbook.SaveChartAsImage(sheet, 0);
//Save the image to .png file
image.Save(@"output\chart.png", ImageFormat.Png);
}
}
}

Convert All Charts in an Excel Worksheet to Images in C# and VB.NET
To convert all charts in an Excel worksheet to images, you can use the Workbook.SaveChartAsImage(Worksheet worksheet) method. The following are the detailed steps:
- Initialize an instance of the Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index through Workbook.Worksheets[int worksheetIndex] property.
- Save all charts in the worksheet as images using Workbook.SaveChartAsImage(Worksheet worksheet) method.
- Save the images to PNG files.
- C#
- VB.NET
using Spire.Xls;
using System.Drawing;
using System.Drawing.Imaging;
namespace ConvertAllExcelChartsToImages
{
internal class Program
{
static void Main(string[] args)
{
//Initialize an instance of the Workbook class
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("Charts.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Save charts in the first worksheet as images
Image[] imgs = workbook.SaveChartAsImage(sheet);
//Save the images to png files
for (int i = 0; i < imgs.Length; i++)
{
imgs[i].Save(string.Format(@"output\chart-{0}.png", i), ImageFormat.Png);
}
}
}
}

Convert a Chart Sheet to Image in Excel in C# and VB.NET
You can use the Workbook.SaveChartAsImage(ChartSheet chartSheet) method to convert a chart sheet in Excel to image. The following are the detailed steps:
- Initialize an instance of the Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specific chart sheet by its index through Workbook.Chartsheets[int chartSheetIndex] property.
- Save the chart sheet as image using Workbook.SaveChartAsImage(ChartSheet chartSheet) method.
- Save the image to .png file.
- C#
- VB.NET
using Spire.Xls;
using System.Drawing;
using System.Drawing.Imaging;
namespace ConvertExcelChartSheetToImage
{
internal class Program
{
static void Main(string[] args)
{
//Initialize an instance of the Workbook class
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("ChartSheet.xlsx");
//Get the first chart sheet
ChartSheet chartSheet = workbook.Chartsheets[0];
//Save the first chart sheet as image
Image image = workbook.SaveChartAsImage(chartSheet);
//Save the image to .png file
image.Save(@"output\chartSheet.png", ImageFormat.Png);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Sometimes, you may want to convert Excel sheet to a high-resolution image, especially when the Excel report contains graphs or pictures. This article will show you how to set image resolution when saving Excel sheet to JPG using Spire.XLS.
Step 1: Create a custom function that you can use to reset the image resolution.
private static Bitmap ResetResolution(Metafile mf, float resolution)
{
int width = (int)(mf.Width * resolution / mf.HorizontalResolution);
int height = (int)(mf.Height * resolution / mf.VerticalResolution);
Bitmap bmp = new Bitmap(width, height);
bmp.SetResolution(resolution, resolution);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(mf, 0, 0);
g.Dispose();
return bmp;
}
Step 2: Create a workbook instance and load the sample Excel file.
Workbook workbook = new Workbook();
workbook.LoadFromFile("Chart.xlsx",ExcelVersion.Version2013);
Step 3: Get the worksheet you want to convert.
Worksheet worksheet = workbook.Worksheets[0];
Step 4: Convert the worksheet to EMF stream.
MemoryStream ms = new MemoryStream(); worksheet.ToEMFStream(ms, 1, 1, worksheet.LastRow, worksheet.LastColumn);
Step 5: Create an image from the EMF stream, and call ResetResolution to reset the resolution for the image.
Image image = Image.FromStream(ms); Bitmap images = ResetResolution(image as Metafile, 300);
Step 6: Save the image in JPG file format.
images.Save("Result.jpg", ImageFormat.Jpeg);
Output:

Full Code:
using Spire.Xls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace Convert
{
class Program
{
static void Main(string[] args)
{
Workbook workbook = new Workbook();
workbook.LoadFromFile("Chart.xlsx", ExcelVersion.Version2013);
Worksheet worksheet = workbook.Worksheets[0];
using (MemoryStream ms = new MemoryStream())
{
worksheet.ToEMFStream(ms, 1, 1, worksheet.LastRow, worksheet.LastColumn);
Image image = Image.FromStream(ms);
Bitmap images = ResetResolution(image as Metafile, 300);
images.Save("Result.jpg", ImageFormat.Jpeg);
}
}
private static Bitmap ResetResolution(Metafile mf, float resolution)
{
int width = (int)(mf.Width * resolution / mf.HorizontalResolution);
int height = (int)(mf.Height * resolution / mf.VerticalResolution);
Bitmap bmp = new Bitmap(width, height);
bmp.SetResolution(resolution, resolution);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(mf, 0, 0);
g.Dispose();
return bmp;
}
}
}
Imports Spire.Xls
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Namespace Convert
Class Program
Private Shared Sub Main(args As String())
Dim workbook As New Workbook()
workbook.LoadFromFile("Chart.xlsx", ExcelVersion.Version2013)
Dim worksheet As Worksheet = workbook.Worksheets(0)
Using ms As New MemoryStream()
worksheet.ToEMFStream(ms, 1, 1, worksheet.LastRow, worksheet.LastColumn)
Dim image__1 As Image = Image.FromStream(ms)
Dim images As Bitmap = ResetResolution(TryCast(image__1, Metafile), 300)
images.Save("Result.jpg", ImageFormat.Jpeg)
End Using
End Sub
Private Shared Function ResetResolution(mf As Metafile, resolution As Single) As Bitmap
Dim width As Integer = CInt(mf.Width * resolution / mf.HorizontalResolution)
Dim height As Integer = CInt(mf.Height * resolution / mf.VerticalResolution)
Dim bmp As New Bitmap(width, height)
bmp.SetResolution(resolution, resolution)
Dim g As Graphics = Graphics.FromImage(bmp)
g.DrawImage(mf, 0, 0)
g.Dispose()
Return bmp
End Function
End Class
End Namespace