First add reference Microsoft. Office. InterOP. Excel;
/// <Summary>
/// Export the datagridview Excel
/// </Summary>
/// <Param name = "datagridview"> datagridview </param>
/// <Returns> whether the export is successful, true is returned for success, and false is returned for failure </returns>
Public bool exportexcel (datagridview datagridatagri)
{
Savefiledialog savedialog = new savefiledialog ();
Savedialog. Filter = "Excel files (*. xls) | *. xls ";
Savedialog. filterindex = 0;
Savedialog. restoredirectory = true;
Savedialog. createprompt = true;
Bool filesaved = false;
If (savedialog. showdialog () = dialogresult. OK)
{
If (datagridview = NULL)
{
Return false;
}
Microsoft. Office. InterOP. Excel. Application xlapp = new Microsoft. Office. InterOP. Excel. applicationclass ();
If (xlapp = NULL)
{
Return false;
}
Microsoft. Office. InterOP. Excel. workbooks = xlapp. workbooks;
Microsoft. Office. InterOP. Excel. Workbook workbook = workbooks. Add (Microsoft. Office. InterOP. Excel. xlwbatemplate. xlwbatworksheet );
Microsoft. Office. InterOP. Excel. worksheet = (Microsoft. Office. InterOP. Excel. worksheet) Workbook. worksheets [1];
For (INT I = 0; I <datagridview. Columns. Count; I ++)
{
Worksheet. cells [1, I + 1] = datagridview. Columns [I]. headertext;
}
For (INT r = 0; r <datagridview. Rows. Count; r ++)
{
For (INT I = 0; I <datagridview. Columns. Count; I ++)
{
Worksheet. cells [R + 2, I + 1] = datagridview. Rows [R]. cells [I]. value. tostring ();
}
}
Try
{
Workbook. Saved = true;
Workbook. savecopyas (savedialog. filename );
Filesaved = true;
}
Catch (exception)
{
Filesaved = false;
}
If (worksheet! = NULL)
{
System. runtime. interopservices. Marshal. releasecomobject (worksheet );
Worksheet = NULL;
}
If (workbook! = NULL)
{
System. runtime. interopservices. Marshal. releasecomobject (workbook );
Workbook = NULL;
}
If (workbooks! = NULL)
{
System. runtime. interopservices. Marshal. releasecomobject (workbooks );
Workbooks = NULL;
}
Xlapp. application. workbooks. Close ();
Xlapp. Quit ();
If (xlapp! = NULL)
{
System. runtime. interopservices. Marshal. releasecomobject (xlapp );
Xlapp = NULL;
}
GC. Collect ();
}
Return filesaved;
}