How to Export Data into XML in C#?

2013-10-24 06:20:01 Written by  Administrator
Rate this item
(0 votes)

The aim of the article is to introduce the procedure of exporting data into Office OpenXML in only two steps with a .net component. Spire.DataExport is a completely pure .NET component suit for exporting data into MS Excel, MS Word, HTML, Office OpenXML, PDF, MS Access, DBF, RTF, SQL Script, SYLK, DIF, CSV, MS Clipboard format. It has high performance for exporting data from Command, ListView, DataTable components, which help you to save much time and money.

Please download Spire.DataExport for .NET, add Spire.DataExport.dll as reference and set its target framework as .NET 4. Besides, many developers also check and download another C# excel component together - Spire.XLS for .NET.

Step1: Function to fill data in datatable

In this step, Spire.DataExport will help to load Data information from the datatable. After setting up the data source and SQL command, we can even preview and modify data through DataGridVew before exporting.

[C#]
private void Form1_Load(object sender, EventArgs e)
        {
            oleDbConnection1.ConnectionString = txtConnectString.Text;
            oleDbCommand1.CommandText = txtCommandText.Text;
            using (OleDbDataAdapter da = new OleDbDataAdapter())
            {
                da.SelectCommand = oleDbCommand1;
                da.SelectCommand.Connection = oleDbConnection1;
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
            }
        }

Check the Screenshot below:

Datatable_to_XML_01

Step2: Export Data to Office OpenXML

The code below shows how to export data from the datatable to Office OpenXML. Spire.DataExport will create a new Office OpenXML and export data into Office OpenXML through DataGridView. It also allows you to rename the generated Office OpenXML in this step.

[C#]
private void btnExportToXml_Click(object sender, EventArgs e)
        {
            Spire.DataExport.XML.XMLExport xmlExport = new Spire.DataExport.XML.XMLExport();
            xmlExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
            xmlExport.DataTable = this.dataGridView1.DataSource as DataTable;
            xmlExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
            xmlExport.FileName = @"..\..\ToXml.xml";
            xmlExport.SaveToFile();
        }

Check the Screenshot below:

Datatable_to_XML_02

Additional Info

  • tutorial_title: Export Data to Office OpenXML
Last modified on Wednesday, 15 September 2021 03:39