DataGridView to Word And Excel



As I have seen in the forums regarding a question about how to export DataGridView to Word, I started writing this article.
 
This is a sample way of doing it. In this you can find how we can export DataGridView to Word and Excel documents.

I added some dynamic data as needed, whatever data it may be, the process is the same for all.

Initially I added some dynamic data to DataGridView; for this I referred to the example from here.

http://www.dotnetperls.com/datatable

Initially after binding data to a DataGridView it will look as follows:

Data Grid View

By clicking on the respective button, it will export the data to the respective format.

The code which I used to export this is as follows:

private void ToCsV(DataGridView dGV, string filename)
{
    string stOutput = "";
    // Export titles:
    string sHeaders = "";

    for (int j = 0; j < dGV.Columns.Count; j++)
        sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";
    stOutput += sHeaders + "\r\n";
    // Export data.
    for (int i = 0; i < dGV.RowCount - 1; i++)
    {
        string stLine = "";
        for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
            stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "\t";
        stOutput += stLine + "\r\n";
    }
    Encoding utf16 = Encoding.GetEncoding(1254);
    byte[] output = utf16.GetBytes(stOutput);
    FileStream fs = new FileStream(filename, FileMode.Create);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.Write(output, 0, output.Length); //write the encoded file
    bw.Flush();
    bw.Close();
    fs.Close();
}

Call this method in your button click with the respective DataGridView name as per you taken.

For example:

private void btnWord_Click(object sender, EventArgs e)
{
    SaveFileDialog sfd = new SaveFileDialog();
 
    sfd.Filter = "Word Documents (*.doc)|*.doc";

    sfd.FileName = "export.doc";
 
    if (sfd.ShowDialog() == DialogResult.OK)
    {

        //ToCsV(dataGridView1, @"c:\export.xls");

        ToCsV(dataGridView1, sfd.FileName); // Here dataGridview1 is your grid view name 

    }

}

Download the code and try it your self.