Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datagridview export to excel

Tags:

c#

I could export data of datagridview to excel. But the actual format of datagridview was not exported i.e., font, color and space. So, is there any best way to export datagridview to excel i.e. not only data but also the look.

The sample look is this:

enter image description here

like image 764
Nhuren Avatar asked Jun 01 '11 05:06

Nhuren


People also ask

How do I export DataGridView to excel?

Right click on your project and select Add Reference menu. After that go to COM tab and select and add Microsoft Excel 12.0 object library. Now here is my Button click event handler where I create Excel object and document, get data from DataGridView and add rows and columns to the document.

How do I export data from Excel to ASP NET?

Add a link button in the View and name it DownloadExcel. Now, create a Method in Controller and add the following code to Export the data in Excel. Now, run the project and click on the "Download Excel" button. The data is downloaded in Excel format.


1 Answers

Try CSV export

private void ToCsV(DataGridView dGV, string filename)
    {
        string separator = ",";
        StringBuilder stOutput = new StringBuilder();
        // Export titles: 
        StringBuilder sHeaders = new StringBuilder();
        for (int j = 0; j < dGV.Columns.Count; j++)
        {
            sHeaders.Append(dGV.Columns[j].HeaderText);
            sHeaders.Append(separator);
        }
        stOutput.AppendLine(sHeaders.ToString());
        // Export data. 
        for (int i = 0; i < dGV.RowCount - 1; i++)
        {
            StringBuilder stLine = new StringBuilder();
            for (int j = 0; j < dGV.ColumnCount; j++)
            {
                stLine.Append(Convert.ToString(dGV[j, i].Value));
                stLine.Append(separator);
            }
            stOutput.AppendLine(stLine.ToString());
        }

        File.WriteAllText(filename, stOutput.ToString());
    } 
like image 79
Soner Gönül Avatar answered Sep 16 '22 17:09

Soner Gönül