Click here to Skip to main content
15,884,628 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
Export datagridview data to Excel
Posted

Hi, see this thread:

Exporting DataGridview To Excel[^]

and
I've also used below code: (It works for me)
C#
using Excel; //add Interop.Excel in the References

private void CreateExcelFile(DataSet ds, string filename)
{
    if (ds.Tables[0].Rows.Count > 0)
    {
        Excel.Application objApp = new Excel.Application();
        Excel.Workbooks objBooks = objApp.Workbooks;
        Excel.Workbook objBook = objBooks.Add(Missing.Value);
        Excel.Worksheet objSheet = null;

        try
        {
            objSheet = (Excel.Worksheet)objBook.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            ((Excel.Worksheet)objBook.Sheets[1]).Select(Missing.Value);

            int row = 0;

            //Headers
            objSheet.Cells[row + 1, 1] = "Employee ID";
            objSheet.Cells[row + 1, 2] = "Last Name";
            objSheet.Cells[row + 1, 3] = "First Name";

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                row++;
                for (int col = 0; col < ds.Tables[0].Columns.Count; col++)
                {
                    objSheet.Cells[row + 1, col + 1] = dr[col].ToString();
                }
            }
            objBook.Close(true, filename, Missing.Value);
            objBooks.Close();

            //string nopath = @"C:\Users\user\Documents\test.xlsx"; //name of the filename
            //objApp.Workbooks.Open(nopath);
            //objApp.Visible = true;

        }
        catch (Exception e)
        {
            MessageBox.Show("Successfully Exported!", "Export to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
        }
    }

    else
    {
        MessageBox.Show("No Records Found!", "Export to Excel", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
    }

}

Hope it helps! :)
 
Share this answer
 
v3
 
Share this answer
 
I would suggest you to look at some tip here.
 
Share this answer
 
Comments
krishna97 12-Aug-13 1:04am    
not for web
windows application using datagridview export to Excel
Pasan Eeriyagama 12-Aug-13 5:11am    
Hi,
It can be used for both web or desktop, it's really faster and you don't need EXCEL installed in the machine. Hope you get it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900