How to Export Data from Datatable to Word Document in C#?

There are some requirements to export datatable or dataset to word file on many occasions at work. The aim of this article is to help you complete this requirement. Spire.DataExport can help easily load data from the datatable and create a new Word file for storing the data. In addition to this, Spire.DataExport (or Spire.Office) can export data into MS Excel, HTML, XML, PDF, MS Access, DBF, SQL Script, SYLK, DIF, CSV and MS Clipboard format as well, which can be downloaded here. The following code is the example of showing how Spire.DataExport works.

Step 1: Function to fill data in datatable

In this step, Spire.DataExport will help load Data information from the datatable. After setting up the data source and SQL command, it allows you to preview and edit data in DataGridView component 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;
            }
        }

Effect Picture

datatable to word

Step 2: Export Data to word document

The code below shows how to export data from the datatable to Word file. Spire.DataExport will create a new MS Word for storing exported Data. It also allows you to rename the generated Word file in this step.

[C#]
private void btnExportToWord_Click(object sender, EventArgs e)
        {
            Spire.DataExport.RTF.RTFExport rtfExport = new Spire.DataExport.RTF.RTFExport();
            rtfExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
            rtfExport.DataTable = this.dataGridView1.DataSource as DataTable;
            rtfExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
            RTFStyle rtfStyle = new RTFStyle();
            rtfStyle.FontColor = Color.Blue;
            rtfStyle.BackgroundColor = Color.LightGreen;
            rtfExport.RTFOptions.DataStyle = rtfStyle;
            rtfExport.FileName=@"..\..\ToWord.doc";
            rtfExport.SaveToFile();
        }

Effect Picture

datatable to word